@alexsun-top/opencode-chat-room 0.8.2 → 0.8.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.
Files changed (92) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +466 -188
  5. package/package.json +8 -5
  6. package/packages/chat-room-channeld/README.md +25 -3
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +5 -0
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +17 -2
  11. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  12. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  13. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  14. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  15. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  16. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  17. package/packages/chat-room-channeld/src/protocol.ts +1 -0
  18. package/packages/chat-room-channeld/src/state.ts +73 -97
  19. package/packages/chat-room-channeld/src/stats.ts +140 -109
  20. package/server/assets/base.css +3 -1
  21. package/server/assets/chat/admin-badge.js +32 -30
  22. package/server/assets/chat/admin.js +198 -161
  23. package/server/assets/chat/announcements.js +295 -208
  24. package/server/assets/chat/attachment-store.js +106 -75
  25. package/server/assets/chat/attachments.js +686 -441
  26. package/server/assets/chat/chat-background.js +185 -156
  27. package/server/assets/chat/clipboard.js +44 -25
  28. package/server/assets/chat/confirm-dialog.js +36 -33
  29. package/server/assets/chat/copy-action.js +40 -40
  30. package/server/assets/chat/create-room-dialog.js +50 -47
  31. package/server/assets/chat/diagram-viewer.js +293 -234
  32. package/server/assets/chat/doc-preview.js +507 -441
  33. package/server/assets/chat/editor.js +423 -335
  34. package/server/assets/chat/events.js +637 -510
  35. package/server/assets/chat/files.js +476 -430
  36. package/server/assets/chat/history-loader.js +79 -73
  37. package/server/assets/chat/icons.js +9 -11
  38. package/server/assets/chat/image-zoom.js +239 -176
  39. package/server/assets/chat/index.js +2 -3
  40. package/server/assets/chat/install-prompt.js +86 -66
  41. package/server/assets/chat/integration-account-schema.js +88 -86
  42. package/server/assets/chat/integration-editor.js +162 -153
  43. package/server/assets/chat/integration-values.js +109 -100
  44. package/server/assets/chat/integrations.js +689 -622
  45. package/server/assets/chat/join-requests.js +408 -358
  46. package/server/assets/chat/locales/de.js +193 -194
  47. package/server/assets/chat/locales/es.js +193 -194
  48. package/server/assets/chat/locales/fr.js +193 -194
  49. package/server/assets/chat/locales/index.js +1 -2
  50. package/server/assets/chat/locales/it.js +193 -194
  51. package/server/assets/chat/locales/ja.js +193 -193
  52. package/server/assets/chat/locales/ko.js +193 -193
  53. package/server/assets/chat/markdown-footnotes.js +134 -102
  54. package/server/assets/chat/markdown.js +547 -403
  55. package/server/assets/chat/members.js +236 -197
  56. package/server/assets/chat/mentions.js +157 -133
  57. package/server/assets/chat/message-cache.js +40 -33
  58. package/server/assets/chat/message-polling.js +280 -227
  59. package/server/assets/chat/message-window.js +74 -55
  60. package/server/assets/chat/messages.js +552 -480
  61. package/server/assets/chat/office-preview.js +46 -45
  62. package/server/assets/chat/palette.js +450 -417
  63. package/server/assets/chat/panels.js +94 -78
  64. package/server/assets/chat/pwa.js +144 -73
  65. package/server/assets/chat/questions.js +372 -302
  66. package/server/assets/chat/recall.js +320 -273
  67. package/server/assets/chat/receipts.js +149 -121
  68. package/server/assets/chat/reminders.js +331 -214
  69. package/server/assets/chat/replies.js +165 -130
  70. package/server/assets/chat/resource-format.js +59 -62
  71. package/server/assets/chat/room-list.js +58 -55
  72. package/server/assets/chat/room-watcher.js +72 -50
  73. package/server/assets/chat/rooms.js +623 -500
  74. package/server/assets/chat/search.js +136 -114
  75. package/server/assets/chat/settings.js +223 -200
  76. package/server/assets/chat/shiki.js +61 -62
  77. package/server/assets/chat/shortcuts.js +212 -187
  78. package/server/assets/chat/side-pane.js +160 -150
  79. package/server/assets/chat/state.js +849 -735
  80. package/server/assets/chat/system-events.js +45 -43
  81. package/server/assets/chat/system-messages.js +57 -56
  82. package/server/assets/chat/task-form.js +178 -182
  83. package/server/assets/chat/task-row.js +158 -155
  84. package/server/assets/chat/tasks.js +653 -587
  85. package/server/assets/chat/viewport.js +32 -29
  86. package/server/assets/chat/window-controls.js +32 -32
  87. package/server/assets/conversation.css +10 -4
  88. package/server/chat-server.ts +9 -1
  89. package/server/chat.html +2 -1
  90. package/server/routes/pages.ts +7 -5
  91. package/server/sw.js +346 -268
  92. package/src/web/integration-rules-editor.ts +2 -0
@@ -1,10 +1,18 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { DatabaseSync } from "node:sqlite";
3
2
  import type { RuleConfig, RuleTarget } from "./config.ts";
3
+ import { PgDatabase } from "./pg/database.ts";
4
+ import { initializeChannelSchema } from "./pg/schema.ts";
5
+ import { Database, type StateDatabase } from "./pg/sqlite.ts";
4
6
  import type { IngestEvent } from "./protocol.ts";
5
7
  import { buildPublishedResult, PUBLISHED_RESULT_PREFIX, type PublishedResultEvent } from "./published.ts";
6
-
7
- export { readChannelStats, type ChannelAccountStats, type ChannelStats } from "./stats.ts";
8
+ import { accountKey } from "./stats.ts";
9
+
10
+ export {
11
+ readChannelStats,
12
+ readChannelStatsFromPostgres,
13
+ type ChannelAccountStats,
14
+ type ChannelStats,
15
+ } from "./stats.ts";
8
16
  export type { PublishedResultEvent } from "./published.ts";
9
17
 
10
18
  export const DELIVERY_STATES = [
@@ -106,7 +114,7 @@ export interface ChannelState {
106
114
  pauseAccountDeliveries(accountKey: string, reason: string): number;
107
115
  abandonUnconfiguredDeliveries(configuredAccountKeys: string[]): DeliveryRow[];
108
116
  resumePausedDeliveries(): number;
109
- recoverInFlightDeliveries(): number;
117
+ recoverInFlightDeliveries(idempotentAccountKeys: string[]): number;
110
118
  recordReceipt(input: ReceiptInput): string;
111
119
  recordPublishedResult(delivery: DeliveryRow, receipt?: ReceiptRow): void;
112
120
  getPublishedResult(deliveryId: string): PublishedResultEvent | undefined;
@@ -124,62 +132,13 @@ export interface ChannelState {
124
132
 
125
133
  type RawRow = Record<string, unknown>;
126
134
 
127
- const SCHEMA = `
128
- CREATE TABLE IF NOT EXISTS channel_events (
129
- event_id TEXT PRIMARY KEY,
130
- dedup_key TEXT NOT NULL UNIQUE,
131
- payload TEXT NOT NULL,
132
- ingress_seq INTEGER,
133
- committed_at INTEGER NOT NULL
134
- );
135
- CREATE TABLE IF NOT EXISTS channel_deliveries (
136
- delivery_id TEXT PRIMARY KEY,
137
- event_id TEXT NOT NULL,
138
- rule_id TEXT NOT NULL,
139
- rule_version INTEGER NOT NULL,
140
- target TEXT NOT NULL,
141
- idempotency_key TEXT NOT NULL UNIQUE,
142
- payload TEXT NOT NULL,
143
- state TEXT NOT NULL,
144
- attempt_count INTEGER NOT NULL DEFAULT 0,
145
- next_attempt_at INTEGER,
146
- last_error TEXT,
147
- provider_message TEXT,
148
- created_at INTEGER NOT NULL,
149
- updated_at INTEGER NOT NULL
150
- );
151
- CREATE TABLE IF NOT EXISTS channel_receipts (
152
- receipt_id TEXT PRIMARY KEY,
153
- delivery_id TEXT NOT NULL,
154
- attempt_id TEXT NOT NULL,
155
- state TEXT NOT NULL,
156
- provider_message TEXT,
157
- detail TEXT,
158
- observed_at INTEGER NOT NULL
159
- );
160
- CREATE TABLE IF NOT EXISTS channel_echoes (
161
- endpoint TEXT NOT NULL,
162
- native_message_id TEXT NOT NULL,
163
- logical_message_id TEXT NOT NULL,
164
- delivery_id TEXT,
165
- PRIMARY KEY (endpoint, native_message_id)
166
- );
167
- `;
168
-
169
- function transaction<T>(db: DatabaseSync, fn: () => T): T {
170
- db.exec("BEGIN IMMEDIATE");
171
- try {
172
- const value = fn();
173
- db.exec("COMMIT");
174
- return value;
175
- } catch (error) {
176
- try {
177
- db.exec("ROLLBACK");
178
- } catch {
179
- // Keep the original failure.
180
- }
181
- throw error;
182
- }
135
+ function transaction<T>(db: StateDatabase, fn: () => T): T {
136
+ return db.transaction(fn).immediate();
137
+ }
138
+
139
+ // Escape LIKE wildcards so an account key matches as a literal prefix.
140
+ function likePrefix(value: string): string {
141
+ return `${value.replace(/[\\%_]/g, (ch) => `\\${ch}`)}%`;
183
142
  }
184
143
 
185
144
  function toDelivery(row: RawRow): DeliveryRow {
@@ -214,8 +173,13 @@ function toReceipt(row: RawRow): ReceiptRow {
214
173
  }
215
174
 
216
175
  export function openState(path: string): ChannelState {
217
- const db = new DatabaseSync(path);
218
- db.exec(SCHEMA);
176
+ const url = process.env.CHAT_ROOM_DATABASE_URL?.trim();
177
+ return createChannelState(url ? new PgDatabase(url) : new Database(path));
178
+ }
179
+
180
+ /** Build a state store over an already-opened backend (used by Postgres tests). */
181
+ export function createChannelState(db: StateDatabase): ChannelState {
182
+ initializeChannelSchema(db, { backfillEchoOrder: db instanceof Database });
219
183
  let closed = false;
220
184
 
221
185
  function getDelivery(deliveryId: string): DeliveryRow | undefined {
@@ -286,12 +250,12 @@ export function openState(path: string): ChannelState {
286
250
  const prefix = `${accountKey.replace(/\/+$/, "")}/`;
287
251
  const row = db.prepare(
288
252
  `SELECT * FROM channel_deliveries
289
- WHERE substr(target, 1, length(?)) = ?
253
+ WHERE target LIKE ? ESCAPE '\\'
290
254
  AND state IN ('pending', 'retryable', 'rate_limited')
291
255
  AND (next_attempt_at IS NULL OR next_attempt_at <= ?)
292
256
  ORDER BY created_at ASC, delivery_id ASC
293
257
  LIMIT 1`,
294
- ).get(prefix, prefix, now) as RawRow | undefined;
258
+ ).get(likePrefix(prefix), now) as RawRow | undefined;
295
259
  return row ? toDelivery(row) : undefined;
296
260
  },
297
261
 
@@ -320,6 +284,7 @@ export function openState(path: string): ChannelState {
320
284
 
321
285
  recordSent(input) {
322
286
  const receiptId = `rcp-${randomUUID()}`;
287
+ const observedAt = input.observedAt ?? Date.now();
323
288
  transaction(db, () => {
324
289
  db.prepare(
325
290
  `INSERT INTO channel_receipts
@@ -331,18 +296,19 @@ export function openState(path: string): ChannelState {
331
296
  input.attemptId,
332
297
  input.providerMessage,
333
298
  input.detail ?? null,
334
- input.observedAt ?? Date.now(),
299
+ observedAt,
335
300
  );
336
301
  if (input.echo) {
337
302
  db.prepare(
338
303
  `INSERT OR IGNORE INTO channel_echoes
339
- (endpoint, native_message_id, logical_message_id, delivery_id)
340
- VALUES (?, ?, ?, ?)`,
304
+ (endpoint, native_message_id, logical_message_id, delivery_id, created_at)
305
+ VALUES (?, ?, ?, ?, ?)`,
341
306
  ).run(
342
307
  input.echo.endpoint,
343
308
  input.echo.nativeMessageId,
344
309
  input.echo.logicalMessageId,
345
310
  input.deliveryId,
311
+ observedAt,
346
312
  );
347
313
  }
348
314
  });
@@ -354,36 +320,34 @@ export function openState(path: string): ChannelState {
354
320
  const result = db.prepare(
355
321
  `UPDATE channel_deliveries
356
322
  SET state = 'paused', next_attempt_at = NULL, last_error = ?, updated_at = ?
357
- WHERE substr(target, 1, length(?)) = ?
323
+ WHERE target LIKE ? ESCAPE '\\'
358
324
  AND state IN ('pending', 'retryable', 'rate_limited')`,
359
- ).run(reason, Date.now(), prefix, prefix);
325
+ ).run(reason, Date.now(), likePrefix(prefix));
360
326
  return Number(result.changes);
361
327
  },
362
328
 
363
329
  abandonUnconfiguredDeliveries(configuredAccountKeys) {
364
- const configured = [...new Set(configuredAccountKeys)];
365
- const accountKeySql = `CASE WHEN instr(target, '/') > 0
366
- AND instr(substr(target, instr(target, '/') + 1), '/') > 0
367
- THEN substr(target, 1, instr(target, '/') + instr(substr(target, instr(target, '/') + 1), '/') - 1)
368
- ELSE target END`;
369
- const filter = configured.length > 0
370
- ? `AND (${accountKeySql}) NOT IN (${configured.map(() => "?").join(", ")})`
371
- : "";
372
- const rows = db.prepare(
330
+ const configured = new Set(configuredAccountKeys);
331
+ // Account keys are the first two target segments; filter in JS so the
332
+ // same SQL runs on SQLite and PostgreSQL.
333
+ const rows = (db.prepare(
373
334
  `SELECT * FROM channel_deliveries
374
335
  WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
375
- ${filter}
376
336
  ORDER BY created_at ASC, delivery_id ASC`,
377
- ).all(...configured) as RawRow[];
337
+ ).all() as RawRow[]).filter((row) => !configured.has(accountKey(String(row.target))));
378
338
  if (rows.length === 0) return [];
379
- transaction(db, () =>
380
- db.prepare(
381
- `UPDATE channel_deliveries
382
- SET state = 'unknown', next_attempt_at = NULL, last_error = ?, updated_at = ?
383
- WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
384
- ${filter}`,
385
- ).run("account is not configured; add it back to retry", Date.now(), ...configured)
339
+ const update = db.prepare(
340
+ `UPDATE channel_deliveries
341
+ SET state = 'unknown', next_attempt_at = NULL, last_error = ?, updated_at = ?
342
+ WHERE delivery_id = ?
343
+ AND state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')`,
386
344
  );
345
+ transaction(db, () => {
346
+ const now = Date.now();
347
+ for (const row of rows) {
348
+ update.run("account is not configured; add it back to retry", now, String(row.delivery_id));
349
+ }
350
+ });
387
351
  return rows.map((row) => ({ ...toDelivery(row), state: "unknown" as const }));
388
352
  },
389
353
 
@@ -396,14 +360,26 @@ export function openState(path: string): ChannelState {
396
360
  return Number(result.changes);
397
361
  },
398
362
 
399
- recoverInFlightDeliveries() {
400
- const result = db.prepare(
363
+ recoverInFlightDeliveries(idempotentAccountKeys: string[]): number {
364
+ const idempotent = new Set(idempotentAccountKeys);
365
+ const rows = db.prepare(
366
+ "SELECT delivery_id, target FROM channel_deliveries WHERE state = 'in_flight'",
367
+ ).all() as RawRow[];
368
+ if (!rows.length) return 0;
369
+ const now = Date.now();
370
+ const update = db.prepare(
401
371
  `UPDATE channel_deliveries
402
- SET state = 'pending', next_attempt_at = NULL,
372
+ SET state = ?, next_attempt_at = NULL,
403
373
  last_error = 'recovered stale in_flight after restart', updated_at = ?
404
- WHERE state = 'in_flight'`,
405
- ).run(Date.now());
406
- return Number(result.changes);
374
+ WHERE delivery_id = ? AND state = 'in_flight'`,
375
+ );
376
+ transaction(db, () => {
377
+ for (const row of rows) {
378
+ const state = idempotent.has(accountKey(String(row.target))) ? "pending" : "unknown";
379
+ update.run(state, now, String(row.delivery_id));
380
+ }
381
+ });
382
+ return rows.length;
407
383
  },
408
384
 
409
385
  recordReceipt(input) {
@@ -443,9 +419,9 @@ export function openState(path: string): ChannelState {
443
419
  recordEcho(endpoint, nativeMessageId, logicalMessageId, deliveryId) {
444
420
  db.prepare(
445
421
  `INSERT OR IGNORE INTO channel_echoes
446
- (endpoint, native_message_id, logical_message_id, delivery_id)
447
- VALUES (?, ?, ?, ?)`,
448
- ).run(endpoint, nativeMessageId, logicalMessageId, deliveryId ?? null);
422
+ (endpoint, native_message_id, logical_message_id, delivery_id, created_at)
423
+ VALUES (?, ?, ?, ?, ?)`,
424
+ ).run(endpoint, nativeMessageId, logicalMessageId, deliveryId ?? null, Date.now());
449
425
  },
450
426
 
451
427
  findEcho(endpoint, nativeMessageId) {
@@ -459,7 +435,7 @@ export function openState(path: string): ChannelState {
459
435
  const row = db.prepare(
460
436
  `SELECT native_message_id FROM channel_echoes
461
437
  WHERE endpoint = ? AND logical_message_id = ? AND delivery_id IS NOT NULL
462
- ORDER BY rowid DESC LIMIT 1`,
438
+ ORDER BY created_at DESC LIMIT 1`,
463
439
  ).get(endpoint, logicalMessageId) as RawRow | undefined;
464
440
  return row ? String(row.native_message_id) : undefined;
465
441
  },
@@ -1,8 +1,10 @@
1
- import { DatabaseSync } from "node:sqlite";
1
+ import { PgDatabase } from "./pg/database.ts";
2
+ import { Database, type SQLQueryBindings, type StateDatabase } from "./pg/sqlite.ts";
3
+ import { PUBLISHED_RESULT_PREFIX } from "./published.ts";
2
4
 
3
5
  export type ChannelAccountState = "started" | "failed" | "disabled" | "unknown";
4
6
 
5
- /** Live state supplied by a running host; stats itself only reads SQLite. */
7
+ /** Live state supplied by a running host; stats itself only reads the backend. */
6
8
  export interface ChannelAccountRuntime {
7
9
  state: ChannelAccountState;
8
10
  lastError?: string;
@@ -57,12 +59,12 @@ export function sanitizeAccountError(value: string): string {
57
59
  return redacted.replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim().slice(0, MAX_LAST_ERROR);
58
60
  }
59
61
 
60
- function count(db: DatabaseSync, sql: string): number {
61
- const row = db.prepare(sql).get() as Row;
62
+ function count(db: StateDatabase, sql: string, ...params: SQLQueryBindings[]): number {
63
+ const row = db.query(sql).get(...params) as Row;
62
64
  return Number(row.count);
63
65
  }
64
66
 
65
- function accountKey(target: string): string {
67
+ export function accountKey(target: string): string {
66
68
  const first = target.indexOf("/");
67
69
  if (first < 0) return target;
68
70
  const second = target.indexOf("/", first + 1);
@@ -71,139 +73,168 @@ function accountKey(target: string): string {
71
73
 
72
74
  /**
73
75
  * Read queue and integrity counts without touching message content.
74
- * The database is opened read-only, so a missing state file is never created.
76
+ * The SQLite file is opened read-only, so a missing state file is never created.
75
77
  */
76
78
  export function readChannelStats(
77
79
  path: string,
78
80
  now = Date.now(),
79
81
  runtime: ReadonlyMap<string, ChannelAccountRuntime> = new Map(),
80
82
  ): ChannelStats {
81
- let db: DatabaseSync | undefined;
83
+ let db: Database | undefined;
82
84
  try {
83
- db = new DatabaseSync(path, { readOnly: true });
85
+ db = new Database(path, { readOnly: true });
84
86
  db.exec("PRAGMA busy_timeout = 2000");
85
-
86
87
  const names = new Set(
87
- (db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as Row[]).map((row) =>
88
+ (db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all() as Row[]).map((row) =>
88
89
  String(row.name)
89
90
  ),
90
91
  );
91
92
  if (REQUIRED_TABLES.some((table) => !names.has(table))) {
92
93
  throw new Error(`channel state not found: ${path}`);
93
94
  }
95
+ return buildStats(db, now, runtime);
96
+ } catch {
97
+ throw new Error(`channel state not found: ${path}`);
98
+ } finally {
99
+ try {
100
+ db?.close();
101
+ } catch {
102
+ // Keep the original result or error.
103
+ }
104
+ }
105
+ }
94
106
 
95
- const stateCounts: Record<string, number> = {};
96
- const accounts = new Map<string, ChannelAccountStats>();
97
- let oldestBacklogAt: number | null = null;
98
- const rows = db.prepare("SELECT target, state, created_at FROM channel_deliveries").all() as Row[];
107
+ /** Read the same stats from PostgreSQL without echoing the connection string. */
108
+ export function readChannelStatsFromPostgres(
109
+ url: string,
110
+ now = Date.now(),
111
+ runtime: ReadonlyMap<string, ChannelAccountRuntime> = new Map(),
112
+ ): ChannelStats {
113
+ let db: PgDatabase | undefined;
114
+ try {
115
+ db = new PgDatabase(url);
116
+ return buildStats(db, now, runtime);
117
+ } catch {
118
+ throw new Error("channel state not found: postgres");
119
+ } finally {
120
+ try {
121
+ db?.close();
122
+ } catch {
123
+ // Keep the original result or error.
124
+ }
125
+ }
126
+ }
127
+
128
+ function buildStats(
129
+ db: StateDatabase,
130
+ now: number,
131
+ runtime: ReadonlyMap<string, ChannelAccountRuntime>,
132
+ ): ChannelStats {
133
+ const stateCounts: Record<string, number> = {};
134
+ const accounts = new Map<string, ChannelAccountStats>();
135
+ let oldestBacklogAt: number | null = null;
136
+ const rows = db.query("SELECT target, state, created_at FROM channel_deliveries").all() as Row[];
99
137
 
100
138
  for (const row of rows) {
101
- const state = String(row.state);
102
- stateCounts[state] = (stateCounts[state] ?? 0) + 1;
103
-
104
- const key = accountKey(String(row.target));
105
- let account = accounts.get(key);
106
- if (!account) {
107
- account = {
108
- account: key,
109
- state: "unknown",
110
- queueDepth: 0,
111
- oldestBacklogAt: null,
112
- unknown: 0,
113
- retryable: 0,
114
- rateLimited: 0,
115
- };
116
- accounts.set(key, account);
117
- }
118
- if (state === "unknown") account.unknown += 1;
119
- if (state === "retryable") account.retryable += 1;
120
- if (state === "rate_limited") account.rateLimited += 1;
121
- if (QUEUE_STATES.has(state)) {
122
- const createdAt = Number(row.created_at);
123
- account.queueDepth += 1;
124
- if (account.oldestBacklogAt === null || createdAt < account.oldestBacklogAt) {
125
- account.oldestBacklogAt = createdAt;
126
- }
127
- if (oldestBacklogAt === null || createdAt < oldestBacklogAt) {
128
- oldestBacklogAt = createdAt;
129
- }
130
- }
131
- }
139
+ const state = String(row.state);
140
+ stateCounts[state] = (stateCounts[state] ?? 0) + 1;
132
141
 
133
- // Runtime entries add configured accounts without deliveries and override
134
- // the SQLite-only default of "unknown" for a running host.
135
- for (const [key, live] of runtime) {
136
- const account = accounts.get(key) ?? {
142
+ const key = accountKey(String(row.target));
143
+ let account = accounts.get(key);
144
+ if (!account) {
145
+ account = {
137
146
  account: key,
138
- state: "unknown" as const,
147
+ state: "unknown",
139
148
  queueDepth: 0,
140
149
  oldestBacklogAt: null,
141
150
  unknown: 0,
142
151
  retryable: 0,
143
152
  rateLimited: 0,
144
153
  };
145
- account.state = live.state;
146
- const lastError = live.lastError ? sanitizeAccountError(live.lastError) : "";
147
- if (lastError) account.lastError = lastError;
148
154
  accounts.set(key, account);
149
155
  }
156
+ if (state === "unknown") account.unknown += 1;
157
+ if (state === "retryable") account.retryable += 1;
158
+ if (state === "rate_limited") account.rateLimited += 1;
159
+ if (QUEUE_STATES.has(state)) {
160
+ const createdAt = Number(row.created_at);
161
+ account.queueDepth += 1;
162
+ if (account.oldestBacklogAt === null || createdAt < account.oldestBacklogAt) {
163
+ account.oldestBacklogAt = createdAt;
164
+ }
165
+ if (oldestBacklogAt === null || createdAt < oldestBacklogAt) {
166
+ oldestBacklogAt = createdAt;
167
+ }
168
+ }
169
+ }
150
170
 
151
- const pending = stateCounts.pending ?? 0;
152
- const retryable = stateCounts.retryable ?? 0;
153
- const rateLimited = stateCounts.rate_limited ?? 0;
154
- const failed = (stateCounts.permanent ?? 0)
155
- + (stateCounts.unsupported ?? 0)
156
- + (stateCounts.exhausted ?? 0);
157
-
158
- return {
159
- generatedAt: now,
160
- events: count(db, "SELECT COUNT(*) AS count FROM channel_events"),
161
- publishedResults: count(
162
- db,
163
- "SELECT COUNT(*) AS count FROM channel_events WHERE json_extract(payload, '$.kind') = 'result.published'",
164
- ),
165
- eventsWithoutDeliveries: count(
166
- db,
167
- `SELECT COUNT(*) AS count FROM channel_events e
168
- WHERE json_extract(e.payload, '$.kind') IS NOT 'result.published'
169
- AND NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.event_id = e.event_id)`,
170
- ),
171
- deliveriesWithoutEvent: count(
172
- db,
173
- `SELECT COUNT(*) AS count FROM channel_deliveries d
174
- WHERE NOT EXISTS (SELECT 1 FROM channel_events e WHERE e.event_id = d.event_id)`,
175
- ),
176
- receiptsWithoutDelivery: count(
177
- db,
178
- `SELECT COUNT(*) AS count FROM channel_receipts r
179
- WHERE NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.delivery_id = r.delivery_id)`,
180
- ),
181
- deliveries: {
182
- total: rows.length,
183
- pending,
184
- inFlight: stateCounts.in_flight ?? 0,
185
- retryable,
186
- rateLimited,
187
- paused: stateCounts.paused ?? 0,
188
- unknown: stateCounts.unknown ?? 0,
189
- sent: stateCounts.sent ?? 0,
190
- failed,
191
- },
192
- queueDepth: pending + retryable + rateLimited,
193
- oldestBacklogAt,
194
- oldestBacklogAgeMs: oldestBacklogAt === null ? null : now - oldestBacklogAt,
195
- accounts: [...accounts.values()].sort((left, right) =>
196
- left.account < right.account ? -1 : left.account > right.account ? 1 : 0
197
- ),
171
+ // Runtime entries add configured accounts without deliveries and override
172
+ // the backend default of "unknown" for a running host.
173
+ for (const [key, live] of runtime) {
174
+ const account = accounts.get(key) ?? {
175
+ account: key,
176
+ state: "unknown" as const,
177
+ queueDepth: 0,
178
+ oldestBacklogAt: null,
179
+ unknown: 0,
180
+ retryable: 0,
181
+ rateLimited: 0,
198
182
  };
199
- } catch (error) {
200
- if (error instanceof Error && error.message.startsWith("channel state not found:")) throw error;
201
- throw new Error(`channel state not found: ${path}`);
202
- } finally {
203
- try {
204
- db?.close();
205
- } catch {
206
- // Keep the original result or error.
207
- }
183
+ account.state = live.state;
184
+ const lastError = live.lastError ? sanitizeAccountError(live.lastError) : "";
185
+ if (lastError) account.lastError = lastError;
186
+ accounts.set(key, account);
208
187
  }
188
+
189
+ const pending = stateCounts.pending ?? 0;
190
+ const retryable = stateCounts.retryable ?? 0;
191
+ const rateLimited = stateCounts.rate_limited ?? 0;
192
+ const failed = (stateCounts.permanent ?? 0)
193
+ + (stateCounts.unsupported ?? 0)
194
+ + (stateCounts.exhausted ?? 0);
195
+
196
+ const publishedPattern = `${PUBLISHED_RESULT_PREFIX}%`;
197
+ return {
198
+ generatedAt: now,
199
+ events: count(db, "SELECT COUNT(*) AS count FROM channel_events"),
200
+ publishedResults: count(
201
+ db,
202
+ "SELECT COUNT(*) AS count FROM channel_events WHERE dedup_key LIKE ?",
203
+ publishedPattern,
204
+ ),
205
+ eventsWithoutDeliveries: count(
206
+ db,
207
+ `SELECT COUNT(*) AS count FROM channel_events e
208
+ WHERE e.dedup_key NOT LIKE ?
209
+ AND NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.event_id = e.event_id)`,
210
+ publishedPattern,
211
+ ),
212
+ deliveriesWithoutEvent: count(
213
+ db,
214
+ `SELECT COUNT(*) AS count FROM channel_deliveries d
215
+ WHERE NOT EXISTS (SELECT 1 FROM channel_events e WHERE e.event_id = d.event_id)`,
216
+ ),
217
+ receiptsWithoutDelivery: count(
218
+ db,
219
+ `SELECT COUNT(*) AS count FROM channel_receipts r
220
+ WHERE NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.delivery_id = r.delivery_id)`,
221
+ ),
222
+ deliveries: {
223
+ total: rows.length,
224
+ pending,
225
+ inFlight: stateCounts.in_flight ?? 0,
226
+ retryable,
227
+ rateLimited,
228
+ paused: stateCounts.paused ?? 0,
229
+ unknown: stateCounts.unknown ?? 0,
230
+ sent: stateCounts.sent ?? 0,
231
+ failed,
232
+ },
233
+ queueDepth: pending + retryable + rateLimited,
234
+ oldestBacklogAt,
235
+ oldestBacklogAgeMs: oldestBacklogAt === null ? null : now - oldestBacklogAt,
236
+ accounts: [...accounts.values()].sort((left, right) =>
237
+ left.account < right.account ? -1 : left.account > right.account ? 1 : 0
238
+ ),
239
+ };
209
240
  }
@@ -276,8 +276,10 @@
276
276
  #reminderDialog .reminder-form .announcement-actions { margin-top: 2px; }
277
277
  .reminder-form .field { margin: 0 0 9px; }
278
278
  .reminder-form textarea { resize: vertical; min-height: clamp(110px, 16dvh, 190px); max-height: 30dvh; line-height: 1.6; }
279
- .reminder-list { list-style: none; padding: 0; margin: 10px 0; display: grid; gap: 8px; }
279
+ #reminderStatus { min-height: 1.4em; }
280
+ .reminder-list { list-style: none; padding: 0; margin: 10px 0; display: grid; gap: 8px; min-height: 96px; }
280
281
  .reminder-list li { padding: 9px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); }
282
+ .reminder-list li.is-disabled { color: var(--ink-3); background: color-mix(in srgb, var(--surface) 70%, var(--line)); opacity: .62; }
281
283
  .reminder-list p { margin: 0 0 6px; overflow-wrap: anywhere; }
282
284
  .reminder-list .hint { margin: 2px 0 7px; }
283
285
  .reminder-list .btn { margin: 0 6px 0 0; }
@@ -1,49 +1,51 @@
1
1
  // The administrator is one designated session, never every agent in the room.
2
2
  export function isAdminAgent(app, sessionID) {
3
- const admin = app.state.room?.adminSessionID;
4
- return Boolean(admin) && sessionID === admin;
3
+ const admin = app.state.room?.adminSessionID;
4
+ return Boolean(admin) && sessionID === admin;
5
5
  }
6
-
7
6
  // Browser sessions are people; the backend binds the real membership and re-checks it.
8
7
  export function isRoomAdmin(app) {
9
- const room = app.state.room;
10
- return Boolean(room) && (app.state.myName === room.ownerId || (room.adminIds ?? []).includes(app.state.myName));
8
+ const room = app.state.room;
9
+ return Boolean(room) && (app.state.myName === room.ownerId || (room.adminIds ?? []).includes(app.state.myName));
11
10
  }
12
-
13
11
  // Human administrators may remove any non-owner member; the designated agent only ordinary members.
14
12
  export function canRemoveMember(app, target, selfIsAgent, sessionID) {
15
- const room = app.state.room;
16
- if (!room || room.kind === "direct" || !target || target.name === room.ownerId) return false;
17
- if (!selfIsAgent && isRoomAdmin(app)) return true;
18
- return isAdminAgent(app, sessionID) && !(room.adminIds ?? []).includes(target.name);
13
+ const room = app.state.room;
14
+ if (!room || room.kind === "direct" || !target || target.name === room.ownerId)
15
+ return false;
16
+ if (!selfIsAgent && isRoomAdmin(app))
17
+ return true;
18
+ return isAdminAgent(app, sessionID) && !(room.adminIds ?? []).includes(target.name);
19
19
  }
20
-
21
20
  // One label per member: the owner outranks human administrators, who outrank the
22
21
  // designated agent. Names are the stable identity shared by rooms and members.
23
22
  export function memberRole(app, member) {
24
- const room = app.state.room;
25
- if (!room || !member || room.kind === "direct") return "";
26
- if (member.name === room.ownerId) return "owner";
27
- if ((room.adminIds ?? []).includes(member.name)) return "admin";
28
- return isAdminAgent(app, member.sessionID) ? "agent" : "";
23
+ const room = app.state.room;
24
+ if (!room || !member || room.kind === "direct")
25
+ return "";
26
+ if (member.name === room.ownerId)
27
+ return "owner";
28
+ if ((room.adminIds ?? []).includes(member.name))
29
+ return "admin";
30
+ return isAdminAgent(app, member.sessionID) ? "agent" : "";
29
31
  }
30
-
31
32
  function badge(className, text) {
32
- const node = document.createElement("span");
33
- node.className = className;
34
- node.textContent = text;
35
- node.title = text;
36
- return node;
33
+ const node = document.createElement("span");
34
+ node.className = className;
35
+ node.textContent = text;
36
+ node.title = text;
37
+ return node;
37
38
  }
38
-
39
39
  export function adminAgentBadge(app) {
40
- return badge("admin-agent-badge", app.t("adminAgentLabel"));
40
+ return badge("admin-agent-badge", app.t("adminAgentLabel"));
41
41
  }
42
-
43
42
  export function memberRoleBadge(app, member) {
44
- const role = memberRole(app, member);
45
- if (role === "owner") return badge("admin-badge owner-badge", app.t("roomOwnerBadge"));
46
- if (role === "admin") return badge("admin-badge", app.t("roomAdminBadge"));
47
- if (role === "agent") return adminAgentBadge(app);
48
- return null;
43
+ const role = memberRole(app, member);
44
+ if (role === "owner")
45
+ return badge("admin-badge owner-badge", app.t("roomOwnerBadge"));
46
+ if (role === "admin")
47
+ return badge("admin-badge", app.t("roomAdminBadge"));
48
+ if (role === "agent")
49
+ return adminAgentBadge(app);
50
+ return null;
49
51
  }