@alexsun-top/opencode-chat-room 0.8.5 → 0.8.6

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 (119) hide show
  1. package/CHANGELOG.md +12 -2
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +1 -1
  4. package/cli.ts +19 -0
  5. package/dist/cli.js +3747 -1443
  6. package/package.json +6 -1
  7. package/packages/chat-room-channeld/README.md +13 -8
  8. package/packages/chat-room-channeld/src/delivery.ts +0 -4
  9. package/packages/chat-room-channeld/src/host.ts +48 -37
  10. package/packages/chat-room-channeld/src/pg/database.ts +141 -49
  11. package/packages/chat-room-channeld/src/pg/worker.mjs +46 -5
  12. package/packages/chat-room-channeld/src/pg/worker.mts +41 -6
  13. package/packages/chat-room-channeld/src/state-rows.ts +132 -0
  14. package/packages/chat-room-channeld/src/state.ts +129 -157
  15. package/plugin.ts +20 -4
  16. package/server/app.ts +9 -0
  17. package/server/assets/base.css +22 -2
  18. package/server/assets/chat/admin.js +13 -0
  19. package/server/assets/chat/announcements.js +76 -34
  20. package/server/assets/chat/confirm-dialog.js +3 -0
  21. package/server/assets/chat/create-room-dialog.js +7 -0
  22. package/server/assets/chat/diagram-viewer.js +4 -8
  23. package/server/assets/chat/doc-preview.js +70 -30
  24. package/server/assets/chat/editor.js +38 -3
  25. package/server/assets/chat/events.js +6 -1
  26. package/server/assets/chat/files.js +28 -26
  27. package/server/assets/chat/history-loader.js +31 -15
  28. package/server/assets/chat/integration-editor.js +25 -1
  29. package/server/assets/chat/integrations.js +107 -15
  30. package/server/assets/chat/join-requests.js +39 -1
  31. package/server/assets/chat/locales/de.js +5 -3
  32. package/server/assets/chat/locales/es.js +5 -3
  33. package/server/assets/chat/locales/fr.js +5 -3
  34. package/server/assets/chat/locales/it.js +5 -3
  35. package/server/assets/chat/locales/ja.js +5 -3
  36. package/server/assets/chat/locales/ko.js +5 -3
  37. package/server/assets/chat/markdown-footnotes.js +19 -8
  38. package/server/assets/chat/markdown.js +0 -7
  39. package/server/assets/chat/members.js +31 -19
  40. package/server/assets/chat/message-cache.js +8 -2
  41. package/server/assets/chat/message-polling.js +8 -2
  42. package/server/assets/chat/message-window.js +57 -0
  43. package/server/assets/chat/messages.js +79 -40
  44. package/server/assets/chat/operator.js +624 -0
  45. package/server/assets/chat/palette.js +2 -7
  46. package/server/assets/chat/panels.js +31 -8
  47. package/server/assets/chat/questions.js +72 -56
  48. package/server/assets/chat/recall.js +14 -5
  49. package/server/assets/chat/receipts.js +63 -7
  50. package/server/assets/chat/refresh-timing.js +6 -0
  51. package/server/assets/chat/reminders.js +44 -13
  52. package/server/assets/chat/replies.js +33 -22
  53. package/server/assets/chat/resource-format.js +4 -1
  54. package/server/assets/chat/room-list.js +202 -3
  55. package/server/assets/chat/room-watcher.js +3 -1
  56. package/server/assets/chat/rooms.js +22 -3
  57. package/server/assets/chat/settings.js +33 -3
  58. package/server/assets/chat/state.js +21 -7
  59. package/server/assets/chat/tasks.js +33 -11
  60. package/server/assets/chat/window-controls.js +25 -16
  61. package/server/assets/code-highlight.css +0 -13
  62. package/server/assets/conversation.css +31 -3
  63. package/server/assets/doc-preview.css +3 -0
  64. package/server/assets/files.css +4 -0
  65. package/server/assets/monaco/integration-rules.js +1 -1
  66. package/server/assets/responsive.css +12 -2
  67. package/server/assets/settings.css +3 -1
  68. package/server/assets/tasks.css +6 -1
  69. package/server/assets/window-controls.css +3 -1
  70. package/server/channels.ts +3 -2
  71. package/server/chat.html +7 -2
  72. package/server/inbox.ts +3 -1
  73. package/server/join-requests.ts +8 -1
  74. package/server/member-routes.ts +16 -2
  75. package/server/newrooms.ts +2 -13
  76. package/server/operator-auth.ts +21 -0
  77. package/server/operator-routes.ts +150 -0
  78. package/server/operator-state.ts +64 -0
  79. package/server/operator.css +139 -0
  80. package/server/room-owner.ts +17 -0
  81. package/server/routes/inbox.ts +15 -5
  82. package/server/routes/pages.ts +12 -2
  83. package/server/routes/room-actions.ts +4 -3
  84. package/server/system.html +109 -0
  85. package/server/wake.ts +1 -1
  86. package/skills/chatroom/SKILL.md +3 -3
  87. package/src/acp/client.ts +254 -0
  88. package/src/acp/protocol.ts +300 -0
  89. package/src/acp/watch.ts +498 -0
  90. package/src/agent/agent-receipts.ts +87 -5
  91. package/src/center/center-client.ts +5 -0
  92. package/src/center/center-inbox.ts +54 -7
  93. package/src/center/center-wake.ts +57 -3
  94. package/src/center/forward-client.ts +48 -0
  95. package/src/center/mentions.ts +16 -3
  96. package/src/center/notification-delay.ts +139 -0
  97. package/src/center/queue.ts +3 -0
  98. package/src/config/file-config.ts +25 -0
  99. package/src/mcp/server.ts +389 -0
  100. package/src/protocol/config.ts +7 -0
  101. package/src/runtime/plugin-notifications.ts +43 -9
  102. package/src/runtime/v2-plugin.ts +14 -3
  103. package/src/runtime/v2-receiver.ts +10 -2
  104. package/src/runtime/watch.ts +5 -1
  105. package/src/state/pg-database.ts +133 -49
  106. package/src/state/pg-worker.mjs +46 -5
  107. package/src/state/pg-worker.mts +41 -6
  108. package/src/state/receiver-state.ts +47 -0
  109. package/src/state/sqlite-database.ts +6 -2
  110. package/src/state/sqlite-members.ts +48 -4
  111. package/src/state/sqlite-messages.ts +25 -12
  112. package/src/state/sqlite-schema.ts +4 -1
  113. package/src/state/sqlite-state.ts +1 -1
  114. package/src/state/store.ts +10 -4
  115. package/src/tui/app.mjs +57 -10
  116. package/src/tui/app.mts +54 -11
  117. package/src/tui/room-settings-app.mjs +27 -9
  118. package/src/tui/room-settings-app.mts +26 -9
  119. package/src/web/integration-rules-editor.ts +25 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.8.5",
3
+ "version": "0.8.6",
4
4
  "description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -52,6 +52,9 @@
52
52
  "server/message-recall-routes.ts",
53
53
  "server/room-payload.ts",
54
54
  "server/room-owner.ts",
55
+ "server/operator-auth.ts",
56
+ "server/operator-routes.ts",
57
+ "server/operator-state.ts",
55
58
  "server/newrooms.ts",
56
59
  "server/join-requests.ts",
57
60
  "server/room-join.ts",
@@ -65,6 +68,8 @@
65
68
  "server/room-reminders.ts",
66
69
  "server/wake.ts",
67
70
  "server/chat.html",
71
+ "server/system.html",
72
+ "server/operator.css",
68
73
  "server/manifest.webmanifest",
69
74
  "server/sw.js",
70
75
  "server/assets",
@@ -224,19 +224,24 @@ The child process reads:
224
224
  - `FEISHU_HTTP_TIMEOUT_MS` (optional, default `10000`)
225
225
  - `FEISHU_CARD_VERSION` (optional, `1.0` default or `2.0`)
226
226
  - `FEISHU_INBOUND` (optional, `1` enables the event long connection)
227
- - `FEISHU_INBOUND_CHATS` (required with `FEISHU_INBOUND=1`; comma-separated
228
- group `chat_id` allowlist)
227
+ - `FEISHU_INBOUND_CHATS` (comma-separated group `chat_id` allowlist)
228
+ - `FEISHU_INBOUND_DM_CHAT` and `FEISHU_INBOUND_DM_OPEN_ID` (set both with
229
+ `FEISHU_INBOUND=1` to receive only one private chat from one app-scoped user;
230
+ this ignores the group allowlist)
229
231
 
230
232
  Set these in the host environment; the host passes its environment to adapter
231
233
  child processes.
232
234
 
233
235
  Inbound requires the app to use long-connection event subscription in the Feishu
234
- developer console and to subscribe `im.message.receive_v1`; the bot must already
235
- be in each allowlisted group. The adapter obtains the WebSocket URL from
236
+ developer console and to subscribe `im.message.receive_v1`. The bot must be in
237
+ each allowlisted group; private chat requires the app's bot DM read permission
238
+ (`im:message.p2p_msg:readonly` or `im:message.p2p_msg`). Add a server `inbound`
239
+ route for the exact source account and chat to relay it into ChatRoom. The
240
+ adapter obtains the WebSocket URL from
236
241
  `POST /callback/ws/endpoint`, pings, reassembles fragmented frames, and
237
- acknowledges only after the host commits the ingest. Only group `text` and `post`
238
- messages from human senders in an allowlisted chat are mapped. Bot/self senders,
239
- other chats, other event types, other apps, and unsupported message types are
242
+ acknowledges only after the host commits the ingest. Supported `text`, `post`,
243
+ `image`, and `file` messages must come from an allowed human sender and chat.
244
+ Bot/self senders, other chats, other event types, other apps, and unsupported message types are
240
245
  acknowledged without ingest. A long-connection start failure logs a warning,
241
246
  keeps the account started for outbound sends, and reports a sanitized
242
247
  `inbound failed: ...` in the account status; outbound forwarding keeps working.
@@ -340,4 +345,4 @@ same terminal result event and message.
340
345
  - no full backpressure (high-water marks, pausing ingress, disk quotas) — only per-account queue/process isolation and `rate_limited` backoff;
341
346
  - no attachments, no rule UI, no multi-tenant permission model, no exactly-once
342
347
  guarantee (inbound room notifications are idempotent per event and route, but
343
- a crash between the ACK and Feishu's next retry can still lose an event).
348
+ a crash between the ACK and Feishu's next retry can still lose an event).
@@ -67,10 +67,6 @@ export function applyReceipt(
67
67
 
68
68
  switch (receipt.state) {
69
69
  case "sent": {
70
- state.markDelivery(row.deliveryId, "sent", {
71
- providerMessage: providerMessage ?? null,
72
- lastError: null,
73
- });
74
70
  const event = state.getEvent(row.eventId);
75
71
  const echo = receipt.providerMessage?.nativeMessageId && receipt.providerMessage.endpoint
76
72
  ? {
@@ -1,4 +1,4 @@
1
- import type { AccountConfig, ChannelConfig, RuleTarget } from "./config.ts";
1
+ import type { AccountConfig, ChannelConfig } from "./config.ts";
2
2
  import { AdapterProcess, type SendReceipt } from "./adapter.ts";
3
3
  import { applyReceipt, notifyDeliveryResult, type DeliveryResultHandler } from "./delivery.ts";
4
4
  import { parseTarget, startFailureReason, toEndpoint, validateTargets } from "./host-helpers.ts";
@@ -8,7 +8,7 @@ import type { AdapterCapabilities, Endpoint, IngestEvent, MessageRef } from "./p
8
8
  import { matchRules, planPayload, sameEndpoint, targetKey } from "./rules.ts";
9
9
  import type { ChannelAccountRuntime } from "./stats.ts";
10
10
  import { sanitizeAccountError } from "./stats.ts";
11
- import { openState, type ChannelState, type DeliveryRow } from "./state.ts";
11
+ import { openState, type ChannelState, type DeliveryRow, type PlannedDelivery } from "./state.ts";
12
12
 
13
13
  export type { IngestResult } from "./ingest-gate.ts";
14
14
 
@@ -213,12 +213,9 @@ export class ChannelHost {
213
213
  .map((account) => `${account.platform}/${account.id}`);
214
214
  const recovered = state.recoverInFlightDeliveries(idempotentKeys);
215
215
  if (recovered > 0) {
216
+ // Every started account already owns one delivery loop, so recovery only
217
+ // makes rows pending; scheduling again would create a second loop.
216
218
  log.warn(`recovered ${recovered} stale in-flight deliveries`);
217
- for (const account of this.#config.accounts) {
218
- if (!this.#disabled.has(account.id) && idempotentKeys.includes(`${account.platform}/${account.id}`)) {
219
- this.#schedule(account.id);
220
- }
221
- }
222
219
  }
223
220
 
224
221
  const usable = started.filter((accountId) => !this.#disabled.has(accountId));
@@ -264,7 +261,14 @@ export class ChannelHost {
264
261
  }
265
262
  }
266
263
 
267
- const result = state.commitIngest(event);
264
+ // The event and its frozen outbound plan commit together. Classification and
265
+ // planning run only for a new insert, on the stored event with its ingressSeq;
266
+ // the frozen decision also governs whether a consumer error rolls the event back.
267
+ let notificationOnly = false;
268
+ const { result, created } = state.commitIngestWithPlan(event, (storedEvent) => {
269
+ notificationOnly = this.#notificationOnly?.(storedEvent) ?? false;
270
+ return notificationOnly ? [] : this.#planDeliveries(storedEvent);
271
+ });
268
272
  if (result.duplicate) {
269
273
  log.info("duplicate ingest skipped", { event: result.existingEventId });
270
274
  return { duplicate: true, eventId: result.existingEventId };
@@ -279,7 +283,7 @@ export class ChannelHost {
279
283
  const message = error instanceof Error ? error.message : String(error);
280
284
  // An inbound notification owns the ACK: roll back and fail the ingest so
281
285
  // the provider retries. Other consumer failures stay contained as before.
282
- if (this.#notificationOnly?.(stored)) {
286
+ if (notificationOnly) {
283
287
  state.deleteIngestEvent(stored.eventId);
284
288
  log.error(`inbound commit rolled back: ${message}`, { event: stored.eventId });
285
289
  throw error;
@@ -288,58 +292,64 @@ export class ChannelHost {
288
292
  }
289
293
  }
290
294
 
291
- if (this.#notificationOnly?.(stored)) {
295
+ if (notificationOnly) {
292
296
  log.info("inbound notification only; outbound rules skipped", { event: stored.eventId });
293
297
  return { duplicate: false, eventId: stored.eventId };
294
298
  }
295
299
 
296
- if (stored.kind === "message.forward_requested") {
297
- const selected = stored.selectedMessage;
300
+ for (const delivery of created) {
301
+ const endpoint = parseTarget(delivery.target);
302
+ if (endpoint && this.#disabled.has(endpoint.accountId)) {
303
+ state.markDelivery(delivery.deliveryId, "paused", {
304
+ lastError: "account disabled until restart",
305
+ });
306
+ }
307
+ log.info(`delivery enqueued rule=${delivery.ruleId}@${delivery.ruleVersion}`, {
308
+ delivery: delivery.deliveryId,
309
+ event: stored.eventId,
310
+ });
311
+ }
312
+ return { duplicate: false, eventId: stored.eventId };
313
+ }
314
+
315
+ /** Freeze matching rules into delivery plans; runs inside the ingest transaction. */
316
+ #planDeliveries(event: IngestEvent): PlannedDelivery[] {
317
+ if (event.kind === "message.forward_requested") {
318
+ const selected = event.selectedMessage;
298
319
  const reason = !selected
299
320
  ? "selectedMessage is required"
300
- : !sameEndpoint(selected.endpoint, stored.source)
321
+ : !sameEndpoint(selected.endpoint, event.source)
301
322
  ? "selectedMessage is outside the source room"
302
323
  : undefined;
303
324
  if (reason) {
304
- log.warn(`forward rejected: ${reason}`, { event: stored.eventId });
305
- return { duplicate: false, eventId: stored.eventId };
325
+ log.warn(`forward rejected: ${reason}`, { event: event.eventId });
326
+ return [];
306
327
  }
307
328
  }
308
329
 
309
- const requestedTarget = stored.kind === "message.forward_requested" ? stored.requestedTarget : undefined;
310
- for (const rule of matchRules(this.#config, stored)) {
311
- const targets: RuleTarget[] = [];
312
- const payloads: string[] = [];
330
+ const requestedTarget = event.kind === "message.forward_requested" ? event.requestedTarget : undefined;
331
+ const planned: PlannedDelivery[] = [];
332
+ for (const rule of matchRules(this.#config, event)) {
313
333
  for (const target of rule.to) {
314
334
  const endpoint = toEndpoint(this.#config, rule.id, target);
315
335
  if (requestedTarget && !sameEndpoint(endpoint, requestedTarget)) continue;
316
- const plan = planPayload(rule, stored, endpoint);
336
+ const plan = planPayload(rule, event, endpoint);
317
337
  if ("dropped" in plan) {
318
338
  log.warn(
319
339
  `rule ${rule.id}@${rule.version} dropped delivery to ${targetKey(endpoint)}: ${plan.dropped}`,
320
- { event: stored.eventId },
340
+ { event: event.eventId },
321
341
  );
322
342
  continue;
323
343
  }
324
- targets.push(target);
325
- payloads.push(JSON.stringify(plan.payload));
326
- }
327
- if (targets.length === 0) continue;
328
- const created = state.enqueueDeliveries(stored.eventId, rule, targets, payloads);
329
- for (const delivery of created) {
330
- const endpoint = parseTarget(delivery.target);
331
- if (endpoint && this.#disabled.has(endpoint.accountId)) {
332
- state.markDelivery(delivery.deliveryId, "paused", {
333
- lastError: "account disabled until restart",
334
- });
335
- }
336
- log.info(`delivery enqueued rule=${rule.id}@${rule.version}`, {
337
- delivery: delivery.deliveryId,
338
- event: stored.eventId,
344
+ planned.push({
345
+ ruleId: rule.id,
346
+ ruleVersion: rule.version,
347
+ target: targetKey(endpoint),
348
+ payload: JSON.stringify(plan.payload),
339
349
  });
340
350
  }
341
351
  }
342
- return { duplicate: false, eventId: stored.eventId };
352
+ return planned;
343
353
  }
344
354
 
345
355
  async stop(options: { abortInFlight?: boolean } = {}): Promise<void> {
@@ -375,6 +385,7 @@ export class ChannelHost {
375
385
 
376
386
  #schedule(accountId: string): void {
377
387
  if (!this.#running || this.#disabled.has(accountId)) return;
388
+ if (this.#timers.has(accountId)) return;
378
389
  const timer = setTimeout(() => {
379
390
  this.#timers.delete(accountId);
380
391
  if (!this.#running) return;
@@ -20,6 +20,8 @@ type Reply = {
20
20
  changes?: number;
21
21
  lastInsertRowid?: number;
22
22
  error?: Record<string, unknown>;
23
+ // The worker's connection is gone; the next top-level call must reconnect.
24
+ broken?: true;
23
25
  };
24
26
 
25
27
  type ReadyMessage = { type: "ready" } | { type: "fatal"; error?: Record<string, unknown> };
@@ -41,11 +43,22 @@ function databaseError(error: Record<string, unknown> | undefined): Error {
41
43
  return result;
42
44
  }
43
45
 
46
+ // A lost transport is not a retryable SQL condition: immediate() retries busy
47
+ // errors, and replaying a statement with an unknown outcome is unsafe.
48
+ function lostError(error: unknown): Error {
49
+ const cause = error instanceof Error ? error : new Error(String(error));
50
+ return Object.assign(new Error(`PostgreSQL connection lost: ${cause.message}`, { cause }), {
51
+ code: "PG_BRIDGE_LOST",
52
+ });
53
+ }
54
+
44
55
  export class PgDatabase implements StateDatabase {
45
- readonly #worker: Worker;
46
- readonly #port: MessagePort;
56
+ readonly #connectionString: string;
47
57
  readonly #timeout: number;
48
58
  readonly #lockTimeout: number;
59
+ #worker: Worker | undefined;
60
+ #port: MessagePort | undefined;
61
+ #generation = 0;
49
62
  #nextID = 1;
50
63
  #depth = 0;
51
64
  #savepoints = 0;
@@ -54,39 +67,90 @@ export class PgDatabase implements StateDatabase {
54
67
 
55
68
  constructor(connectionString: string, options: { timeout?: number } = {}) {
56
69
  if (!connectionString) throw new Error("PostgreSQL connection string is empty");
70
+ this.#connectionString = connectionString;
57
71
  this.#timeout = options.timeout ?? 5_000;
58
72
  this.#lockTimeout = Math.max(1, this.#timeout - 1_000);
73
+ this.#connect();
74
+ }
75
+
76
+ // A worker owns one pg.Client. After a timeout or a lost connection the old
77
+ // worker is disposed instead of reused; the next independent call builds a
78
+ // fresh generation. Work that was already sent is never replayed.
79
+ #connect(): void {
80
+ // Generations hide events from a worker that was already discarded, so a
81
+ // late error or exit cannot mark the replacement connection dead.
82
+ const generation = ++this.#generation;
59
83
  const ready = new SharedArrayBuffer(4);
60
84
  const { port1, port2 } = new MessageChannel();
85
+ const worker = new Worker(workerURL());
86
+ worker.unref();
87
+ port1.unref();
88
+ // A dying worker must not surface as an uncaught 'error' event. Break the
89
+ // bridge so the next top-level call reconnects.
90
+ worker.on("error", (error: Error) => this.#lose(generation, error));
91
+ worker.on("exit", (code: number) => this.#lose(generation, new Error(`PostgreSQL worker exited with code ${code}`)));
92
+ this.#worker = worker;
61
93
  this.#port = port1;
62
- this.#worker = new Worker(workerURL());
63
- this.#worker.unref();
64
- this.#port.unref();
65
94
  try {
66
95
  // No workerData: some Bun versions break `pg` when a worker starts with
67
96
  // any workerData. The default worker channel carries one init message
68
97
  // and transfers the request port.
69
- this.#worker.postMessage({
98
+ worker.postMessage({
70
99
  type: "init",
71
- connectionString,
100
+ connectionString: this.#connectionString,
72
101
  ready,
73
102
  statementTimeout: Math.max(1, this.#timeout - 500),
74
103
  port: port2,
75
104
  }, [port2]);
76
105
  } catch (error) {
77
- void this.#worker.terminate();
78
- this.#port.close();
106
+ this.#dispose();
79
107
  throw error;
80
108
  }
81
109
  const status = Atomics.wait(new Int32Array(ready), 0, 0, this.#timeout);
82
110
  if (status === "timed-out") {
83
- void this.#worker.terminate();
111
+ this.#dispose();
84
112
  throw new Error(`PostgreSQL bridge did not become ready within ${this.#timeout}ms`);
85
113
  }
86
- const message = receiveMessageOnPort(this.#port)?.message as ReadyMessage | undefined;
87
- if (message?.type === "fatal") {
88
- void this.#worker.terminate();
89
- throw databaseError(message.error);
114
+ const message = receiveMessageOnPort(port1)?.message as ReadyMessage | undefined;
115
+ // Only an explicit "ready" makes the bridge healthy; a silent exit between
116
+ // signalReady and this read must not be reported as a usable connection.
117
+ if (message?.type !== "ready") {
118
+ this.#dispose();
119
+ throw message?.type === "fatal"
120
+ ? databaseError(message.error)
121
+ : new Error("PostgreSQL bridge closed before signaling ready");
122
+ }
123
+ this.#broken = undefined;
124
+ }
125
+
126
+ #dispose(): void {
127
+ const port = this.#port;
128
+ const worker = this.#worker;
129
+ this.#port = undefined;
130
+ this.#worker = undefined;
131
+ try { port?.close(); } catch { /* already closed */ }
132
+ void worker?.terminate();
133
+ }
134
+
135
+ #lose(generation: number, error: Error): void {
136
+ if (generation !== this.#generation || this.#broken || this.#closed) return;
137
+ this.#broken = lostError(error);
138
+ this.#dispose();
139
+ }
140
+
141
+ // Fails fast inside a transaction: the old transaction is already lost, so
142
+ // reopening here would run its remaining statements outside that transaction.
143
+ // A closed handle never reopens, even when it is also marked lost.
144
+ #ensureOpen(): void {
145
+ if (this.#closed) throw new Error("PostgreSQL database is closed");
146
+ if (!this.#broken) return;
147
+ if (this.#depth > 0) throw this.#broken;
148
+ this.#dispose();
149
+ try {
150
+ this.#connect();
151
+ } catch (error) {
152
+ this.#broken = lostError(error);
153
+ throw this.#broken;
90
154
  }
91
155
  }
92
156
 
@@ -116,37 +180,39 @@ export class PgDatabase implements StateDatabase {
116
180
  close(): void {
117
181
  if (this.#closed) return;
118
182
  this.#closed = true;
119
- const signal = new SharedArrayBuffer(4);
120
- try {
121
- this.#port.postMessage({ type: "close", signal });
122
- // Give client.end() time to flush before a caller opens the next
123
- // connection (migration and restart tests rely on it).
124
- Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
125
- } catch { /* worker already gone */ }
126
- this.#port.close();
127
- void this.#worker.terminate();
183
+ const port = this.#port;
184
+ if (port && !this.#broken) {
185
+ const signal = new SharedArrayBuffer(4);
186
+ try {
187
+ port.postMessage({ type: "close", signal });
188
+ // Give client.end() time to flush before a caller opens the next
189
+ // connection (migration and restart tests rely on it).
190
+ Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
191
+ } catch { /* worker already gone */ }
192
+ }
193
+ this.#dispose();
128
194
  }
129
195
 
130
196
  #run<T>(fn: () => T, immediate: boolean): T {
197
+ // A new transaction may reconnect, but once its depth is pinned every
198
+ // BEGIN, lock, COMMIT and ROLLBACK runs against the same connection
199
+ // generation. A lost transaction therefore fails on the old bridge instead
200
+ // of continuing on a fresh one.
201
+ this.#ensureOpen();
131
202
  const nested = this.#depth > 0;
132
203
  const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
133
- if (nested) {
134
- this.exec(`SAVEPOINT ${savepoint}`);
135
- } else {
136
- // Deferred reads need one stable snapshot; immediate writers are
137
- // serialized by the transaction-level advisory lock.
138
- this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
139
- if (immediate) {
140
- try {
204
+ this.#depth++;
205
+ try {
206
+ if (nested) {
207
+ this.exec(`SAVEPOINT ${savepoint}`);
208
+ } else {
209
+ // Deferred reads need one stable snapshot; immediate writers are
210
+ // serialized by the transaction-level advisory lock.
211
+ this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
212
+ if (immediate) {
141
213
  this.exec(`SET LOCAL lock_timeout = '${this.#lockTimeout}ms'; SELECT pg_advisory_xact_lock(hashtext('channeld-state')); SET LOCAL lock_timeout = 0`);
142
- } catch (error) {
143
- try { this.exec("ROLLBACK"); } catch { /* keep the original error */ }
144
- throw error;
145
214
  }
146
215
  }
147
- }
148
- this.#depth++;
149
- try {
150
216
  const result = fn();
151
217
  this.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
152
218
  return result;
@@ -161,27 +227,53 @@ export class PgDatabase implements StateDatabase {
161
227
  }
162
228
 
163
229
  #request(mode: "all" | "get" | "run" | "exec", sql: string, params: SQLQueryBindings[]): Reply {
164
- if (this.#broken) throw this.#broken;
165
- if (this.#closed) throw new Error("PostgreSQL database is closed");
230
+ this.#ensureOpen();
231
+ const port = this.#port as MessagePort;
166
232
  const id = this.#nextID++;
167
233
  const signal = new SharedArrayBuffer(4);
168
- this.#port.postMessage({ id, mode, sql, params, signal });
234
+ try {
235
+ port.postMessage({ id, mode, sql, params, signal });
236
+ } catch (error) {
237
+ const failure = lostError(error);
238
+ this.#fail(failure);
239
+ throw this.#broken ?? failure;
240
+ }
169
241
  const status = Atomics.wait(new Int32Array(signal), 0, 0, this.#timeout);
170
242
  if (status === "timed-out") {
171
- // The worker may still be inside the query. Its connection and queue are
172
- // no longer trustworthy, so fail closed rather than desynchronize later calls.
173
- this.#broken = Object.assign(
174
- new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the database connection must be reopened`),
243
+ // The worker may still be inside the statement, so its outcome is unknown.
244
+ // Terminating the worker aborts its transaction; the statement is never
245
+ // replayed and a later independent call reconnects.
246
+ const error = Object.assign(
247
+ new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the connection reopens on the next operation`),
175
248
  { code: "PG_BRIDGE_TIMEOUT" },
176
249
  );
177
- throw this.#broken;
250
+ this.#fail(error);
251
+ throw error;
178
252
  }
179
- const message = receiveMessageOnPort(this.#port)?.message as Reply | undefined;
253
+ const message = receiveMessageOnPort(port)?.message as Reply | undefined;
180
254
  if (!message || message.id !== id) {
181
- this.#broken = Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
182
- throw this.#broken;
255
+ const error = this.#broken ??
256
+ Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
257
+ this.#fail(error);
258
+ throw error;
259
+ }
260
+ if (!message.ok) {
261
+ const error = databaseError(message.error);
262
+ if (message.broken) {
263
+ // A normal SQL error keeps the connection; a lost one cannot be
264
+ // repaired in place, so close it and let the next call reconnect.
265
+ const lost = lostError(error);
266
+ this.#fail(lost);
267
+ throw lost;
268
+ }
269
+ throw error;
183
270
  }
184
- if (!message.ok) throw databaseError(message.error);
185
271
  return message;
186
272
  }
273
+
274
+ #fail(error: Error): void {
275
+ if (this.#broken) return;
276
+ this.#broken = error;
277
+ this.#dispose();
278
+ }
187
279
  }
@@ -10,6 +10,7 @@ let port;
10
10
  let readyFlag;
11
11
  let statementTimeout = 4_500;
12
12
  let connected = false;
13
+ let lost;
13
14
  let draining = false;
14
15
  let closing = false;
15
16
  const queue = [];
@@ -39,15 +40,46 @@ function signalReady() {
39
40
  Atomics.notify(readyFlag, 0);
40
41
  }
41
42
  function reply(request, payload) {
42
- port?.postMessage({ id: request.id, ...payload });
43
+ try {
44
+ port?.postMessage({ id: request.id, ...payload });
45
+ }
46
+ catch { /* port already retired */ }
43
47
  const flag = new Int32Array(request.signal);
44
48
  Atomics.store(flag, 0, 1);
45
49
  Atomics.notify(flag, 0);
46
50
  }
51
+ function markLost(error) {
52
+ if (!lost)
53
+ lost = error instanceof Error ? error : new Error(String(error));
54
+ connected = false;
55
+ return lost;
56
+ }
57
+ // Session-level failures (backend termination, server shutdown, socket error)
58
+ // leave the client unusable. Ordinary statement errors such as 57014 keep it.
59
+ function unusable(error) {
60
+ if (lost)
61
+ return true;
62
+ const source = (error ?? {});
63
+ if (source.severity === "FATAL" || source.severity === "PANIC")
64
+ return true;
65
+ // SQLSTATE class 08 is a connection exception, not a statement failure.
66
+ return typeof source.code === "string" && source.code.startsWith("08");
67
+ }
68
+ // pg emits "error" on the client when the socket dies without an active query
69
+ // (idle connection). Without this listener the event is uncaught and the worker
70
+ // dies, which used to take the whole server process with it.
71
+ function clientLost(error) {
72
+ if (closing)
73
+ return;
74
+ markLost(error);
75
+ if (queue.length && !draining)
76
+ void drain();
77
+ }
47
78
  async function handle(request) {
48
79
  const db = client;
49
- if (!db) {
50
- return reply(request, { ok: false, error: { message: "PostgreSQL worker is not connected" } });
80
+ if (!db || lost) {
81
+ const error = lost ?? new Error("PostgreSQL worker is not connected");
82
+ return reply(request, { ok: false, error: serialize(error), broken: true });
51
83
  }
52
84
  try {
53
85
  const text = translate(request.sql);
@@ -69,7 +101,10 @@ async function handle(request) {
69
101
  return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
70
102
  }
71
103
  catch (error) {
72
- return reply(request, { ok: false, error: serialize(error) });
104
+ if (!unusable(error))
105
+ return reply(request, { ok: false, error: serialize(error) });
106
+ markLost(error);
107
+ return reply(request, { ok: false, error: serialize(error), broken: true });
73
108
  }
74
109
  }
75
110
  async function drain() {
@@ -103,7 +138,9 @@ function handlePortMessage(message) {
103
138
  return;
104
139
  }
105
140
  queue.push(message);
106
- if (connected && !draining)
141
+ // After a loss the queue is still served, but every reply is marked broken so
142
+ // the main thread reopens immediately instead of waiting for its timeout.
143
+ if (!draining && (connected || lost))
107
144
  void drain();
108
145
  }
109
146
  async function startup(connectionString, ready, timeout) {
@@ -115,6 +152,10 @@ async function startup(connectionString, ready, timeout) {
115
152
  application_name: "chat-room-channeld",
116
153
  statement_timeout: statementTimeout,
117
154
  });
155
+ db.on("error", clientLost);
156
+ // pg normally emits "error" before "end"; "end" alone still means the
157
+ // connection is gone, and the first failure keeps its message.
158
+ db.on("end", () => clientLost(new Error("PostgreSQL connection ended")));
118
159
  client = db;
119
160
  await db.connect();
120
161
  connected = true;