@alexsun-top/opencode-chat-room 0.8.1 → 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 (125) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +1008 -274
  5. package/package.json +10 -7
  6. package/packages/chat-room-channeld/README.md +42 -15
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +150 -7
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +41 -11
  11. package/packages/chat-room-channeld/src/inbound.ts +13 -4
  12. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  13. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  14. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  15. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  16. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  17. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  18. package/packages/chat-room-channeld/src/protocol.ts +53 -1
  19. package/packages/chat-room-channeld/src/rules.ts +7 -2
  20. package/packages/chat-room-channeld/src/state.ts +73 -97
  21. package/packages/chat-room-channeld/src/stats.ts +140 -109
  22. package/plugin.ts +1 -1
  23. package/server/assets/base.css +11 -3
  24. package/server/assets/chat/admin-badge.js +32 -30
  25. package/server/assets/chat/admin.js +198 -163
  26. package/server/assets/chat/announcements.js +295 -210
  27. package/server/assets/chat/attachment-store.js +106 -75
  28. package/server/assets/chat/attachments.js +686 -441
  29. package/server/assets/chat/chat-background.js +206 -0
  30. package/server/assets/chat/clipboard.js +44 -25
  31. package/server/assets/chat/confirm-dialog.js +36 -34
  32. package/server/assets/chat/copy-action.js +40 -40
  33. package/server/assets/chat/create-room-dialog.js +50 -48
  34. package/server/assets/chat/diagram-viewer.js +293 -228
  35. package/server/assets/chat/doc-preview.js +510 -388
  36. package/server/assets/chat/editor.js +423 -335
  37. package/server/assets/chat/events.js +637 -502
  38. package/server/assets/chat/files.js +476 -426
  39. package/server/assets/chat/history-loader.js +79 -73
  40. package/server/assets/chat/icons.js +9 -11
  41. package/server/assets/chat/image-zoom.js +239 -169
  42. package/server/assets/chat/index.js +6 -5
  43. package/server/assets/chat/install-prompt.js +86 -66
  44. package/server/assets/chat/integration-account-schema.js +101 -0
  45. package/server/assets/chat/integration-editor.js +162 -153
  46. package/server/assets/chat/integration-values.js +109 -100
  47. package/server/assets/chat/integrations.js +696 -479
  48. package/server/assets/chat/join-requests.js +408 -358
  49. package/server/assets/chat/locales/de.js +193 -194
  50. package/server/assets/chat/locales/es.js +193 -194
  51. package/server/assets/chat/locales/fr.js +193 -194
  52. package/server/assets/chat/locales/index.js +1 -2
  53. package/server/assets/chat/locales/it.js +193 -194
  54. package/server/assets/chat/locales/ja.js +193 -193
  55. package/server/assets/chat/locales/ko.js +193 -193
  56. package/server/assets/chat/markdown-footnotes.js +134 -102
  57. package/server/assets/chat/markdown.js +553 -386
  58. package/server/assets/chat/members.js +236 -197
  59. package/server/assets/chat/mentions.js +157 -133
  60. package/server/assets/chat/message-cache.js +40 -33
  61. package/server/assets/chat/message-polling.js +280 -227
  62. package/server/assets/chat/message-window.js +74 -55
  63. package/server/assets/chat/messages.js +552 -479
  64. package/server/assets/chat/office-preview.js +46 -45
  65. package/server/assets/chat/palette.js +450 -412
  66. package/server/assets/chat/panels.js +94 -58
  67. package/server/assets/chat/pwa.js +144 -73
  68. package/server/assets/chat/questions.js +372 -302
  69. package/server/assets/chat/recall.js +320 -273
  70. package/server/assets/chat/receipts.js +149 -122
  71. package/server/assets/chat/reminders.js +331 -216
  72. package/server/assets/chat/replies.js +165 -136
  73. package/server/assets/chat/resource-format.js +59 -62
  74. package/server/assets/chat/room-list.js +58 -55
  75. package/server/assets/chat/room-watcher.js +72 -50
  76. package/server/assets/chat/rooms.js +623 -505
  77. package/server/assets/chat/search.js +136 -114
  78. package/server/assets/chat/settings.js +229 -140
  79. package/server/assets/chat/shiki.js +61 -62
  80. package/server/assets/chat/shortcuts.js +212 -190
  81. package/server/assets/chat/side-pane.js +166 -131
  82. package/server/assets/chat/state.js +851 -707
  83. package/server/assets/chat/system-events.js +55 -27
  84. package/server/assets/chat/system-messages.js +59 -49
  85. package/server/assets/chat/task-form.js +178 -182
  86. package/server/assets/chat/task-row.js +158 -155
  87. package/server/assets/chat/tasks.js +653 -593
  88. package/server/assets/chat/viewport.js +32 -29
  89. package/server/assets/chat/window-controls.js +37 -0
  90. package/server/assets/code-highlight.css +22 -6
  91. package/server/assets/conversation.css +65 -16
  92. package/server/assets/doc-preview.css +6 -1
  93. package/server/assets/files.css +3 -0
  94. package/server/assets/monaco/integration-rules.css +1 -1
  95. package/server/assets/monaco/integration-rules.js +841 -533
  96. package/server/assets/responsive.css +32 -2
  97. package/server/assets/settings.css +117 -13
  98. package/server/assets/window-controls.css +36 -0
  99. package/server/channel-attachments.ts +133 -0
  100. package/server/channel-integration.ts +79 -26
  101. package/server/channels.ts +15 -5
  102. package/server/chat-server.ts +9 -1
  103. package/server/chat.html +73 -38
  104. package/server/manifest.webmanifest +1 -0
  105. package/server/routes/pages.ts +7 -5
  106. package/server/sw.js +346 -267
  107. package/src/center/center-client.ts +1 -1
  108. package/src/state/pg-database.ts +5 -5
  109. package/src/state/pg-migrate.ts +7 -7
  110. package/src/state/pg-worker.mjs +2 -17
  111. package/src/state/sqlite-database.ts +14 -5
  112. package/src/state/sqlite-rooms.ts +130 -23
  113. package/src/state/sqlite-state-store.ts +6 -5
  114. package/src/state/sqlite.ts +3 -3
  115. package/src/web/integration-rules-editor.ts +141 -5
  116. package/src/web/integration-rules.ts +6 -2
  117. package/src/web/integration-schema.ts +7 -6
  118. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
  119. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
  120. package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
  121. package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
  122. package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
  123. package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
  124. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
  125. package/server/assets/chat/forward.js +0 -69
@@ -422,7 +422,7 @@ export async function centerAction(
422
422
  const sentID = [...parsed.messages].reverse()
423
423
  .find((message) => message.senderSessionID === sessionID && message.text === args.text!.trim())?.id
424
424
  ?? parsed.messages.at(-1)?.id;
425
- return `sent: ${args.text.trim()}\n${sentID ? `message id: ${sentID}\n` : ""}${formatRoom(svcOf(room), parsed)}`;
425
+ return `sent: ${args.text.trim()}\n${sentID ? `message_id=${sentID} room_id=${parsed.id}\n` : ""}${formatRoom(svcOf(room), parsed)}`;
426
426
  }
427
427
  case "recall": {
428
428
  if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
@@ -8,9 +8,9 @@ import type { QueryStatement, SQLQueryBindings, StateDatabase, Transaction } fro
8
8
  // network I/O. The state layer is synchronous by design, so this preserves its
9
9
  // transaction boundaries without turning 100+ call sites into async code.
10
10
  //
11
- // PostgreSQL support is experimental and single-instance in 0.8.1: the worker
12
- // holds a session advisory lock for the lifetime of the connection, and a
13
- // second process fails startup instead of writing concurrently.
11
+ // PostgreSQL support is experimental through the 0.8.2 multi-instance
12
+ // milestone. Writers serialize per transaction with an advisory xact lock;
13
+ // separate processes may share the database and apply disjoint diffs.
14
14
 
15
15
  type Reply = {
16
16
  id: number;
@@ -115,8 +115,8 @@ export class PgDatabase implements StateDatabase {
115
115
  const signal = new SharedArrayBuffer(4);
116
116
  try {
117
117
  this.#port.postMessage({ type: "close", signal });
118
- // Give client.end() a chance to release the session advisory lock before
119
- // a caller opens the next connection (migration and restart tests rely on it).
118
+ // Give client.end() time to flush before a caller opens the next
119
+ // connection (migration and restart tests rely on it).
120
120
  Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
121
121
  } catch { /* worker already gone */ }
122
122
  this.#port.close();
@@ -3,9 +3,9 @@ import { PgDatabase } from "./pg-database.ts";
3
3
  import { Database, type SQLQueryBindings } from "./sqlite.ts";
4
4
  import { closeStateDatabases, initializeAdminSchema, initializeReminderSchema, openStateDatabase } from "./sqlite-state.ts";
5
5
 
6
- // One-shot SQLite -> PostgreSQL copy. PostgreSQL support is experimental and
7
- // single-instance in 0.8.1; the target connection holds the same session lock
8
- // as the server, so a running server makes this command fail before writing.
6
+ // One-shot SQLite -> PostgreSQL copy. PostgreSQL support is experimental through
7
+ // the 0.8.2 multi-instance milestone; nothing stops a running server from
8
+ // writing to the target, so the operator must stop it before migrating.
9
9
 
10
10
  export type MigrationOptions = {
11
11
  sourcePath: string;
@@ -20,9 +20,9 @@ const quote = (name: string) => `"${name.replace(/"/g, '""')}"`;
20
20
  function backupGuidance(sourcePath: string): string[] {
21
21
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
22
22
  return [
23
- "PostgreSQL state is experimental and single-instance in 0.8.1.",
23
+ "PostgreSQL state is experimental (0.8.2 multi-instance milestone).",
24
24
  "Stop the chat-room server before migrating; this command takes a SQLite write lock,",
25
- "but only --yes confirms that the server is actually stopped.",
25
+ "but nothing blocks a running PostgreSQL writer. Only --yes confirms the server is stopped.",
26
26
  "",
27
27
  "Make a WAL-safe SQLite backup first (do not copy only chat-room.sqlite while WAL is active):",
28
28
  ` sqlite3 ${JSON.stringify(sourcePath)} ".backup '${sourcePath}.backup-${stamp}'"`,
@@ -102,8 +102,8 @@ export async function migrateToPostgres(options: MigrationOptions): Promise<Migr
102
102
  probe.close();
103
103
  }
104
104
 
105
- // Opening the PostgreSQL state database also acquires the process-wide
106
- // single-instance lock, so a running server blocks the migration here.
105
+ // The target copy runs in one immediate transaction; a running server is
106
+ // not detected here, so operator confirmation is the only guard.
107
107
  const target = await openStateDatabase(options.sourcePath);
108
108
  await initializeAdminSchema(options.sourcePath);
109
109
  await initializeReminderSchema(options.sourcePath);
@@ -2,19 +2,14 @@ import { parentPort } from "node:worker_threads";
2
2
  import pg from "pg";
3
3
  import { hasSql, translate } from "./pg-sql.mjs";
4
4
 
5
- // One pg.Client per worker: transactions and the process-wide advisory lock
6
- // belong to a single session, so a pool would be incorrect here.
5
+ // One pg.Client per worker: transactions and their advisory locks belong to a
6
+ // single session, so a pool would be incorrect here.
7
7
  //
8
8
  // The worker deliberately starts with no workerData. Some Bun versions fail to
9
9
  // load `pg` in a worker that received any workerData at startup. The main
10
10
  // thread sends one init message over the default worker channel instead; that
11
11
  // message also transfers the request MessagePort and the ready SharedArrayBuffer.
12
12
 
13
- const SINGLE_INSTANCE_KEY = "opencode-chat-room:state-writer";
14
- const SINGLE_INSTANCE_ERROR =
15
- "PostgreSQL backend is experimental and single-instance: another chat-room process already holds the database writer lock. " +
16
- "Multi-instance support is planned for 0.8.2. Stop the other process, or unset CHAT_ROOM_DATABASE_URL to return to SQLite.";
17
-
18
13
  let client;
19
14
  let port;
20
15
  let readyFlag;
@@ -119,16 +114,6 @@ async function startup(connectionString, ready, timeout) {
119
114
  statement_timeout: statementTimeout,
120
115
  });
121
116
  await client.connect();
122
- const guard = await client.query(
123
- "SELECT pg_try_advisory_lock(hashtext($1), 1) AS locked",
124
- [SINGLE_INSTANCE_KEY],
125
- );
126
- if (!guard.rows[0]?.locked) {
127
- port.postMessage({ type: "fatal", error: { code: "PG_SINGLE_INSTANCE", message: SINGLE_INSTANCE_ERROR } });
128
- signalReady();
129
- try { await client.end(); } catch { /* main will terminate this worker */ }
130
- return;
131
- }
132
117
  connected = true;
133
118
  port.postMessage({ type: "ready" });
134
119
  signalReady();
@@ -9,8 +9,8 @@ import { immediate, pause } from "./sqlite-transaction.ts";
9
9
  const databases = new Map<string, Promise<StateDatabase>>();
10
10
 
11
11
  // Set CHAT_ROOM_DATABASE_URL only on the server process. The PostgreSQL
12
- // backend is experimental and single-instance in 0.8.1; the PgDatabase worker
13
- // holds a session advisory lock and a second process fails startup.
12
+ // backend is experimental through the 0.8.2 multi-instance milestone; writers
13
+ // serialize per transaction with a transaction-scoped advisory lock.
14
14
  function postgresURL(): string | undefined {
15
15
  const value = process.env.CHAT_ROOM_DATABASE_URL?.trim();
16
16
  return value || undefined;
@@ -27,8 +27,8 @@ export function openStateDatabase(file: string): Promise<StateDatabase> {
27
27
  return pending;
28
28
  }
29
29
 
30
- // Test and shutdown hook. PgDatabase.close() waits for client.end() so the
31
- // single-instance session lock is released before a new connection is opened.
30
+ // Test and shutdown hook. PgDatabase.close() waits for client.end() so a
31
+ // restart does not overlap the previous connection's shutdown.
32
32
  export async function closeStateDatabases(): Promise<void> {
33
33
  const pending = [...databases.values()];
34
34
  databases.clear();
@@ -78,7 +78,16 @@ export async function initializeReminderSchema(file: string): Promise<void> {
78
78
  async function initializePostgres(connectionString: string): Promise<StateDatabase> {
79
79
  const db = new PgDatabase(connectionString);
80
80
  try {
81
- await initializeSchema(db);
81
+ // Concurrent CREATE TABLE IF NOT EXISTS is not race-free in PostgreSQL:
82
+ // two instances can both try to create the same type and one gets a
83
+ // duplicate pg_type error. Serialize only the startup DDL with a
84
+ // session-scoped lock; the lock is released automatically if a process dies.
85
+ db.exec("SELECT pg_advisory_lock(hashtext('chat-room-schema'))");
86
+ try {
87
+ await initializeSchema(db);
88
+ } finally {
89
+ db.exec("SELECT pg_advisory_unlock(hashtext('chat-room-schema'))");
90
+ }
82
91
  // Legacy rooms.json/registry.json migration is SQLite-only. The migrate
83
92
  // command copies an existing SQLite state database into PostgreSQL.
84
93
  return db;
@@ -1,51 +1,158 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { Message, Participant, Room } from "../rooms/room-service.ts";
3
3
  import type { Registry, RegistryEntry } from "./store.ts";
4
- import { type StateDatabase } from "./sqlite.ts";
4
+ import { type SQLQueryBindings, type StateDatabase } from "./sqlite.ts";
5
5
 
6
6
  export type State = { rooms: Room[]; registry: Registry };
7
7
 
8
+ const ROOM_COLUMNS = "name,owner_id,created_at,kind,direct_sessions,direct_pair,description,admin_names,admin_membership_ids,owner_membership_id,successor_name,successor_membership_id,join_policy";
9
+ const ROOM_FIELDS = ROOM_COLUMNS.split(",");
10
+ const ROOM_INSERT = `INSERT INTO rooms(id,${ROOM_COLUMNS}) VALUES(?,${ROOM_FIELDS.map(() => "?").join(",")})`;
11
+ const MESSAGE_COLUMNS = "id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by,recalled_at,recalled_by";
12
+ const MESSAGE_FIELDS = MESSAGE_COLUMNS.split(",");
13
+ const MESSAGE_INSERT = `INSERT INTO messages(${MESSAGE_COLUMNS}) VALUES(${MESSAGE_FIELDS.map(() => "?").join(",")})`;
14
+ const MESSAGE_UPSERT = `${MESSAGE_INSERT} ON CONFLICT(id) DO UPDATE SET is_question=excluded.is_question,answer_to=excluded.answer_to,answered_by=excluded.answered_by,recalled_at=excluded.recalled_at,recalled_by=excluded.recalled_by`;
15
+ const MESSAGE_MUTABLE_FIELDS = ["is_question", "answer_to", "answered_by", "recalled_at", "recalled_by"];
16
+ const REGISTRY_COLUMNS = "server_url,api_prefix,protocol,name,last_read_ts,last_queued_ts,directory,host,receiver_owner_id,membership_id,work_state,last_seen_at";
17
+ const REGISTRY_FIELDS = REGISTRY_COLUMNS.split(",");
18
+ const REGISTRY_INSERT = `INSERT INTO registry(room_id,session_id,${REGISTRY_COLUMNS}) VALUES(?,?,${REGISTRY_FIELDS.map(() => "?").join(",")})`;
19
+
8
20
  function roomColumns(room: Room): string | null {
9
21
  return room.adminIds?.length ? JSON.stringify([...new Set(room.adminIds)]) : null;
10
22
  }
11
23
  const adminBindings = (room: Room) => room.adminMembershipIDs?.length ? JSON.stringify([...new Set(room.adminMembershipIDs)]) : null;
12
- const roomBindings = (room: Room) => [room.ownerMembershipID ?? null, room.successorId ?? null, room.successorMembershipID ?? null];
24
+
25
+ function roomValues(room: Room): SQLQueryBindings[] {
26
+ return [room.name, room.ownerId, room.createdAt, room.kind ?? "group",
27
+ room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null,
28
+ room.description ?? null, roomColumns(room), adminBindings(room),
29
+ room.ownerMembershipID ?? null, room.successorId ?? null, room.successorMembershipID ?? null,
30
+ room.joinPolicy ?? null];
31
+ }
32
+
33
+ function messageValues(message: Message): SQLQueryBindings[] {
34
+ return [message.id, message.roomId, message.senderId, message.senderSessionID ?? null, message.text,
35
+ message.createdAt, message.isQuestion ? 1 : 0, message.answerToMessageID ?? null,
36
+ message.answeredByMessageID ?? null, message.recalledAt ?? null, message.recalledBy ?? null];
37
+ }
38
+
39
+ function mutableMessageValues(message: Message): SQLQueryBindings[] {
40
+ return [message.isQuestion ? 1 : 0, message.answerToMessageID ?? null, message.answeredByMessageID ?? null,
41
+ message.recalledAt ?? null, message.recalledBy ?? null];
42
+ }
43
+
44
+ function registryValues(entry: RegistryEntry): SQLQueryBindings[] {
45
+ return [entry.serverUrl, entry.apiPrefix, entry.protocol ?? null, entry.name,
46
+ entry.lastReadTs ?? null, entry.lastQueuedTs ?? null, entry.directory ?? null, entry.host ?? null,
47
+ entry.receiverOwnerID ?? null, entry.membershipID ?? null, entry.workState ?? null, entry.lastSeenAt ?? null];
48
+ }
13
49
 
14
50
  export function insertRoom(db: StateDatabase, room: Room): void {
15
- db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description,admin_names,admin_membership_ids,owner_membership_id,successor_name,successor_membership_id,join_policy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null, room.description ?? null, roomColumns(room), adminBindings(room), ...roomBindings(room), room.joinPolicy ?? null);
51
+ db.query(ROOM_INSERT).run(room.id, ...roomValues(room));
16
52
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
17
53
  for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
18
- const message = db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by,recalled_at,recalled_by) VALUES(?,?,?,?,?,?,?,?,?,?,?)");
19
- for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt, m.isQuestion ? 1 : 0, m.answerToMessageID ?? null, m.answeredByMessageID ?? null, m.recalledAt ?? null, m.recalledBy ?? null);
54
+ const message = db.query(MESSAGE_INSERT);
55
+ for (const m of room.messages) message.run(...messageValues(m));
20
56
  }
21
57
 
22
58
  export function replaceRegistry(db: StateDatabase, registry: Registry): void {
23
59
  db.exec("DELETE FROM registry");
24
- const insert = db.query("INSERT INTO registry(room_id,session_id,server_url,api_prefix,protocol,name,last_read_ts,last_queued_ts,directory,host,receiver_owner_id,membership_id,work_state,last_seen_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
60
+ const insert = db.query(REGISTRY_INSERT);
25
61
  for (const [roomID, members] of Object.entries(registry)) for (const [sessionID, r] of Object.entries(members)) {
26
62
  r.membershipID ||= randomUUID();
27
- insert.run(roomID, sessionID, r.serverUrl, r.apiPrefix, r.protocol ?? null, r.name,
28
- r.lastReadTs ?? null, r.lastQueuedTs ?? null, r.directory ?? null, r.host ?? null, r.receiverOwnerID ?? null,
29
- r.membershipID, r.workState ?? null, r.lastSeenAt ?? null);
63
+ insert.run(roomID, sessionID, ...registryValues(r));
30
64
  }
31
65
  }
32
66
 
33
- export function persistState(db: StateDatabase, rooms: Room[], registry: Registry): void {
34
- const roomRow = db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description,admin_names,admin_membership_ids,owner_membership_id,successor_name,successor_membership_id,join_policy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,owner_id=excluded.owner_id,created_at=excluded.created_at,kind=excluded.kind,direct_sessions=excluded.direct_sessions,direct_pair=excluded.direct_pair,description=excluded.description,admin_names=excluded.admin_names,admin_membership_ids=excluded.admin_membership_ids,owner_membership_id=excluded.owner_membership_id,successor_name=excluded.successor_name,successor_membership_id=excluded.successor_membership_id,join_policy=excluded.join_policy");
35
- const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
36
- const message = db.query("INSERT OR IGNORE INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by,recalled_at,recalled_by) VALUES(?,?,?,?,?,?,?,?,?,?,?)");
37
- const removeParticipants = db.query("DELETE FROM participants WHERE room_id=?");
38
- const keep = new Set(rooms.map((room) => room.id));
39
- const existing = db.query("SELECT id FROM rooms").all() as Array<{ id: string }>;
67
+ // Apply only the rows that differ between the snapshot read before a write
68
+ // callback and the state the callback produced. Untouched rows are never
69
+ // deleted or rewritten, so another process's committed changes survive.
70
+ export function persistStateDiff(db: StateDatabase, before: State, after: State): void {
71
+ const beforeRooms = new Map(before.rooms.map((room) => [room.id, room]));
72
+ const afterRooms = new Map(after.rooms.map((room) => [room.id, room]));
40
73
  const deleteRoom = db.query("DELETE FROM rooms WHERE id=?");
41
- for (const row of existing) if (!keep.has(row.id)) deleteRoom.run(row.id);
42
- for (const room of rooms) {
43
- roomRow.run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null, room.description ?? null, roomColumns(room), adminBindings(room), ...roomBindings(room), room.joinPolicy ?? null);
44
- removeParticipants.run(room.id);
45
- for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
46
- for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt, m.isQuestion ? 1 : 0, m.answerToMessageID ?? null, m.answeredByMessageID ?? null, m.recalledAt ?? null, m.recalledBy ?? null);
74
+ for (const room of before.rooms) if (!afterRooms.has(room.id)) deleteRoom.run(room.id);
75
+
76
+ const insertRoomRow = db.query(ROOM_INSERT);
77
+ const insertParticipant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
78
+ const updateParticipant = db.query("UPDATE participants SET name=?,joined_at=? WHERE room_id=? AND id=?");
79
+ const deleteParticipant = db.query("DELETE FROM participants WHERE room_id=? AND id=?");
80
+ const message = db.query(MESSAGE_UPSERT);
81
+
82
+ for (const room of after.rooms) {
83
+ const previous = beforeRooms.get(room.id);
84
+ if (!previous) {
85
+ insertRoomRow.run(room.id, ...roomValues(room));
86
+ for (const p of room.participants.values()) insertParticipant.run(room.id, p.id, p.name, p.joinedAt);
87
+ for (const m of room.messages) message.run(...messageValues(m));
88
+ continue;
89
+ }
90
+ updateChanged(db, "rooms", ROOM_FIELDS, roomValues(previous), roomValues(room), "id=?", [room.id]);
91
+ for (const [id, participant] of room.participants) {
92
+ const prior = previous.participants.get(id);
93
+ if (!prior) insertParticipant.run(room.id, id, participant.name, participant.joinedAt);
94
+ else if (prior.name !== participant.name || prior.joinedAt !== participant.joinedAt) {
95
+ updateParticipant.run(participant.name, participant.joinedAt, room.id, id);
96
+ }
97
+ }
98
+ for (const id of previous.participants.keys()) if (!room.participants.has(id)) deleteParticipant.run(room.id, id);
99
+ const previousMessages = new Map(previous.messages.map((item) => [item.id, item]));
100
+ for (const item of room.messages) {
101
+ const prior = previousMessages.get(item.id);
102
+ if (!prior) message.run(...messageValues(item));
103
+ else updateChanged(db, "messages", MESSAGE_MUTABLE_FIELDS, mutableMessageValues(prior), mutableMessageValues(item), "id=?", [item.id]);
104
+ }
105
+ }
106
+
107
+ for (const members of Object.values(after.registry)) for (const entry of Object.values(members)) entry.membershipID ||= randomUUID();
108
+ const insertRegistry = db.query(REGISTRY_INSERT);
109
+ for (const [roomID, members] of Object.entries(after.registry)) {
110
+ for (const [sessionID, entry] of Object.entries(members)) {
111
+ const previous = before.registry[roomID]?.[sessionID];
112
+ if (!previous) insertRegistry.run(roomID, sessionID, ...registryValues(entry));
113
+ else updateChanged(db, "registry", REGISTRY_FIELDS, registryValues(previous), registryValues(entry), "room_id=? AND session_id=?", [roomID, sessionID]);
114
+ }
115
+ }
116
+ const deleteRegistry = db.query("DELETE FROM registry WHERE room_id=? AND session_id=?");
117
+ for (const [roomID, members] of Object.entries(before.registry)) {
118
+ for (const sessionID of Object.keys(members)) {
119
+ if (!after.registry[roomID]?.[sessionID]) deleteRegistry.run(roomID, sessionID);
120
+ }
121
+ }
122
+ }
123
+
124
+ function updateChanged(db: StateDatabase, table: string, fields: string[], before: SQLQueryBindings[], after: SQLQueryBindings[], where: string, key: SQLQueryBindings[]): void {
125
+ const changed: Array<{ field: string; value: SQLQueryBindings }> = [];
126
+ for (let index = 0; index < fields.length; index++) {
127
+ if (before[index] === after[index]) continue;
128
+ changed.push({ field: fields[index]!, value: after[index] });
129
+ }
130
+ if (!changed.length) return;
131
+ db.query(`UPDATE ${table} SET ${changed.map(({ field }) => `${field}=?`).join(",")} WHERE ${where}`)
132
+ .run(...changed.map(({ value }) => value), ...key);
133
+ }
134
+
135
+ function cloneRoom(room: Room): Room {
136
+ return {
137
+ ...room,
138
+ ...(room.adminIds ? { adminIds: [...room.adminIds] } : {}),
139
+ ...(room.adminMembershipIDs ? { adminMembershipIDs: [...room.adminMembershipIDs] } : {}),
140
+ ...(room.directSessionIDs ? { directSessionIDs: [...room.directSessionIDs] } : {}),
141
+ participants: new Map([...room.participants].map(([id, p]) => [id, { ...p }])),
142
+ messages: room.messages.map((message) => ({ ...message })),
143
+ };
144
+ }
145
+
146
+ // The write path hydrates this copy so the pre-callback snapshot stays
147
+ // untouched for diffing. Registry entries are copied too: callbacks mutate them
148
+ // in place.
149
+ export function cloneState(state: State): State {
150
+ const registry: Registry = Object.create(null);
151
+ for (const [roomID, members] of Object.entries(state.registry)) {
152
+ registry[roomID] = Object.create(null);
153
+ for (const [sessionID, entry] of Object.entries(members)) registry[roomID]![sessionID] = { ...entry };
47
154
  }
48
- replaceRegistry(db, registry);
155
+ return { rooms: state.rooms.map(cloneRoom), registry };
49
156
  }
50
157
 
51
158
  export type RoomSummary = { id: string; name: string; latestMsgTs: number };
@@ -3,7 +3,7 @@ import type { Registry } from "./store.ts";
3
3
  import { type StateDatabase } from "./sqlite.ts";
4
4
  import { openStateDatabase } from "./sqlite-database.ts";
5
5
  import { immediate } from "./sqlite-transaction.ts";
6
- import { persistState, readRoomSummaries, readState, type RoomSummary, type State } from "./sqlite-rooms.ts";
6
+ import { cloneState, persistStateDiff, readRoomSummaries, readState, type RoomSummary, type State } from "./sqlite-rooms.ts";
7
7
 
8
8
  export async function writeSqliteState<T>(file: string, callback: (service: RoomService, registry: Registry) => T): Promise<T> {
9
9
  return writeSqliteStateWithDatabase(file, (service, registry) => callback(service, registry));
@@ -12,12 +12,13 @@ export async function writeSqliteState<T>(file: string, callback: (service: Room
12
12
  export async function writeSqliteStateWithDatabase<T>(file: string, callback: (service: RoomService, registry: Registry, db: StateDatabase) => T): Promise<T> {
13
13
  const db = await openStateDatabase(file);
14
14
  return immediate(db, () => {
15
- const state = readState(db);
15
+ const before = readState(db);
16
+ const working = cloneState(before);
16
17
  const service = new RoomService();
17
- service.hydrate(state.rooms);
18
- const result = callback(service, state.registry, db);
18
+ service.hydrate(working.rooms);
19
+ const result = callback(service, working.registry, db);
19
20
  if (result && typeof (result as { then?: unknown }).then === "function") throw new Error("writeState callback must be synchronous");
20
- persistState(db, service.listRooms(), state.registry);
21
+ persistStateDiff(db, before, { rooms: service.listRooms(), registry: working.registry });
21
22
  return result;
22
23
  });
23
24
  }
@@ -92,9 +92,9 @@ export class Database implements StateDatabase {
92
92
  export function isBusyError(error: unknown): boolean {
93
93
  const err = error as { code?: string; errcode?: number; message?: string } | null;
94
94
  if (!err) return false;
95
- // PostgreSQL serialization failure and deadlock detected. The existing
96
- // immediate() retry loop treats these like SQLITE_BUSY/SQLITE_LOCKED.
97
- if (err.code === "40001" || err.code === "40P01") return true;
95
+ // PostgreSQL serialization failure, deadlock, and advisory-lock timeout. The
96
+ // existing immediate() retry loop treats these like SQLITE_BUSY/SQLITE_LOCKED.
97
+ if (err.code === "40001" || err.code === "40P01" || err.code === "55P03") return true;
98
98
  if (typeof err.errcode === "number" && ((err.errcode & 0xff) === 5 || (err.errcode & 0xff) === 6)) return true;
99
99
  return /SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || /database (?:is|table is) locked/i.test(err.message ?? "");
100
100
  }
@@ -2,6 +2,8 @@
2
2
 
3
3
  import * as monaco from "monaco-editor/editor/editor.api";
4
4
  import { jsonDefaults } from "monaco-editor/languages/features/json/register";
5
+ import "monaco-editor/languages/definitions/typescript/register";
6
+ import "monaco-editor/languages/definitions/javascript/register";
5
7
  import "monaco-editor/languages/definitions/yaml/register";
6
8
  import { isMap, isScalar, isSeq, parseDocument, stringify as stringifyYaml } from "yaml";
7
9
  import {
@@ -49,8 +51,10 @@ type Options = {
49
51
  type RegistryEntry = { kind: RulesKind; uri: string; schema: JsonSchema; modelUri: string };
50
52
  const registry = new Map<RulesKind, RegistryEntry>();
51
53
  let completionRegistered = false;
54
+ let hoverRegistered = false;
52
55
  let themeObserver: MutationObserver | null = null;
53
56
  let themeMedia: MediaQueryList | null = null;
57
+ let previewCount = 0;
54
58
 
55
59
  const scope = globalThis as typeof globalThis & { MonacoEnvironment?: { getWorker?: (workerId: string, label: string) => Worker } };
56
60
  scope.MonacoEnvironment = {
@@ -61,13 +65,28 @@ scope.MonacoEnvironment = {
61
65
 
62
66
  function isDarkTheme(): boolean {
63
67
  const theme = document.documentElement.dataset.theme;
68
+ if (theme === "custom") return document.documentElement.dataset.customDark === "true";
64
69
  if (theme === "dark") return true;
65
70
  return theme !== "light" && theme !== "forest" && theme !== "sand" && matchMedia("(prefers-color-scheme: dark)").matches;
66
71
  }
67
72
 
68
73
  function applyTheme() {
69
- const style = getComputedStyle(document.documentElement);
70
- const read = (name: string, fallback: string) => style.getPropertyValue(name).trim() || fallback;
74
+ const read = (name: string, fallback: string) => {
75
+ // Monaco only accepts hex token colors. Resolve the CSS variable to a
76
+ // concrete color first, then normalize rgb()/color() through a canvas.
77
+ const probe = document.createElement("span");
78
+ probe.style.position = "absolute";
79
+ probe.style.visibility = "hidden";
80
+ probe.style.background = `var(${name})`;
81
+ document.documentElement.append(probe);
82
+ const resolved = getComputedStyle(probe).backgroundColor;
83
+ probe.remove();
84
+ const canvas = document.createElement("canvas").getContext("2d");
85
+ if (!canvas || !resolved) return fallback;
86
+ canvas.fillStyle = "#000000";
87
+ canvas.fillStyle = resolved;
88
+ return /^#[0-9a-f]{6}$/i.test(canvas.fillStyle) ? canvas.fillStyle : fallback;
89
+ };
71
90
  monaco.editor.defineTheme("chatroom-light", {
72
91
  base: "vs",
73
92
  inherit: true,
@@ -77,13 +96,31 @@ function applyTheme() {
77
96
  "editorGutter.background": read("--surface", "#fffefa"),
78
97
  "editor.lineHighlightBackground": read("--surface-2", "#f2f0e8"),
79
98
  "editorLineNumber.foreground": read("--ink-3", "#63716b"),
99
+ "menu.background": read("--surface", "#fffefa"),
100
+ "menu.foreground": read("--ink", "#1e2c29"),
101
+ "menu.selectionBackground": read("--surface-2", "#f2f0e8"),
102
+ "menu.selectionForeground": read("--ink", "#1e2c29"),
103
+ "menu.border": read("--line", "#dcded4"),
104
+ "editorWidget.background": read("--surface", "#fffefa"),
105
+ "editorWidget.foreground": read("--ink", "#1e2c29"),
106
+ "editorWidget.border": read("--line", "#dcded4"),
80
107
  },
81
108
  });
82
109
  monaco.editor.defineTheme("chatroom-dark", {
83
110
  base: "vs-dark",
84
111
  inherit: true,
85
112
  rules: [],
86
- colors: { "editor.background": read("--surface", "#182522") },
113
+ colors: {
114
+ "editor.background": read("--surface", "#182522"),
115
+ "menu.background": read("--surface", "#182522"),
116
+ "menu.foreground": read("--ink", "#e6efe9"),
117
+ "menu.selectionBackground": read("--surface-2", "#22322e"),
118
+ "menu.selectionForeground": read("--ink", "#e6efe9"),
119
+ "menu.border": read("--line", "#31433d"),
120
+ "editorWidget.background": read("--surface", "#182522"),
121
+ "editorWidget.foreground": read("--ink", "#e6efe9"),
122
+ "editorWidget.border": read("--line", "#31433d"),
123
+ },
87
124
  });
88
125
  monaco.editor.setTheme(isDarkTheme() ? "chatroom-dark" : "chatroom-light");
89
126
  }
@@ -92,7 +129,7 @@ function watchTheme() {
92
129
  applyTheme();
93
130
  if (themeObserver) return;
94
131
  themeObserver = new MutationObserver(applyTheme);
95
- themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
132
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "data-custom-dark"] });
96
133
  themeMedia = matchMedia("(prefers-color-scheme: dark)");
97
134
  themeMedia.addEventListener("change", applyTheme);
98
135
  }
@@ -222,6 +259,48 @@ function ensureYamlCompletion() {
222
259
  });
223
260
  }
224
261
 
262
+ function ensureYamlHover() {
263
+ if (hoverRegistered) return;
264
+ hoverRegistered = true;
265
+ monaco.languages.registerHoverProvider("yaml", {
266
+ provideHover(model, position) {
267
+ const entry = [...registry.values()].find((item) => item.modelUri === model.uri.toString());
268
+ if (!entry) return null;
269
+ let doc: any;
270
+ try { doc = parseDocument(model.getValue()); } catch { return null; }
271
+ const root = doc.contents;
272
+ const path = pathAtOffset(root, model.getOffsetAt(position));
273
+ if (!path) return null;
274
+ const line = model.getLineContent(position.lineNumber);
275
+ const match = /^\s*(?:-\s*)?["']?([A-Za-z0-9_.-]+)["']?\s*:/.exec(line);
276
+ let schema: JsonSchema | undefined;
277
+ let label = "";
278
+ if (match) {
279
+ const key = match[1]!;
280
+ const container = path[path.length - 1] === key ? path.slice(0, -1) : path;
281
+ schema = schemaAtPath(entry.schema, container, key);
282
+ label = key;
283
+ } else {
284
+ schema = schemaAtPath(entry.schema, path);
285
+ label = String(path[path.length - 1] ?? "");
286
+ }
287
+ if (!schema?.description) return null;
288
+ const word = model.getWordAtPosition(position);
289
+ const range = word
290
+ ? new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn)
291
+ : undefined;
292
+ const type = schema.type ? ` (${String(schema.type)})` : "";
293
+ return {
294
+ range,
295
+ contents: [
296
+ { value: `**${label}**` },
297
+ { value: `${type.trim()}${type ? " " : ""}${schema.description}` },
298
+ ],
299
+ };
300
+ },
301
+ });
302
+ }
303
+
225
304
  type ParseResult = {
226
305
  value?: unknown;
227
306
  doc?: any;
@@ -312,7 +391,7 @@ function formatLabel(format: RulesFormat): string {
312
391
 
313
392
  export function createIntegrationRulesEditor(options: Options): IntegrationRulesEditor {
314
393
  const kind = options.kind;
315
- let format: RulesFormat = options.format ?? "json";
394
+ let format: RulesFormat = options.format ?? "yaml";
316
395
  let accounts = options.accounts;
317
396
  let schema = kind === "inbound" ? buildInboundSchema(accounts) : buildRulesSchema(accounts);
318
397
  const entry: RegistryEntry = {
@@ -324,6 +403,7 @@ export function createIntegrationRulesEditor(options: Options): IntegrationRules
324
403
  registry.set(kind, entry);
325
404
  publishJsonSchemas();
326
405
  ensureYamlCompletion();
406
+ ensureYamlHover();
327
407
  watchTheme();
328
408
 
329
409
  const text = stringifyValue(options.value ?? [], format);
@@ -352,6 +432,29 @@ export function createIntegrationRulesEditor(options: Options): IntegrationRules
352
432
  suggest: { showWords: false },
353
433
  });
354
434
 
435
+ const onWheel = (event: WheelEvent) => {
436
+ // Modifiers belong to Monaco: Ctrl/Cmd zooms, Shift scrolls horizontally.
437
+ if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
438
+ const max = Math.max(0, editor.getScrollHeight() - editor.getLayoutInfo().height);
439
+ const top = editor.getScrollTop();
440
+ const atTop = event.deltaY < 0 && top <= 0;
441
+ const atBottom = event.deltaY > 0 && top >= max - 1;
442
+ if (!atTop && !atBottom) return;
443
+ // Hand the wheel to the page once the editor cannot scroll further.
444
+ let node = options.container.parentElement;
445
+ while (node) {
446
+ const style = getComputedStyle(node);
447
+ if (/(auto|scroll)/.test(style.overflowY) && node.scrollHeight > node.clientHeight + 1) {
448
+ node.scrollTop += event.deltaY;
449
+ event.preventDefault();
450
+ event.stopPropagation();
451
+ return;
452
+ }
453
+ node = node.parentElement;
454
+ }
455
+ };
456
+ options.container.addEventListener("wheel", onWheel, { capture: true, passive: false });
457
+
355
458
  const validate = (): EditorValidation => {
356
459
  const current = model.getValue();
357
460
  const parsed = format === "yaml" ? parseYaml(current) : parseJson(current);
@@ -429,6 +532,7 @@ export function createIntegrationRulesEditor(options: Options): IntegrationRules
429
532
  setReadOnly: (readOnly) => editor.updateOptions({ readOnly }),
430
533
  focus: () => editor.focus(),
431
534
  dispose: () => {
535
+ options.container.removeEventListener("wheel", onWheel, true);
432
536
  change.dispose();
433
537
  editor.dispose();
434
538
  model.dispose();
@@ -436,4 +540,36 @@ export function createIntegrationRulesEditor(options: Options): IntegrationRules
436
540
  publishJsonSchemas();
437
541
  },
438
542
  };
543
+ }
544
+
545
+ export type CodePreviewOptions = { container: HTMLElement; value: string; language?: string };
546
+
547
+ export function createCodePreviewEditor(options: CodePreviewOptions): { dispose: () => void } {
548
+ watchTheme();
549
+ const language = options.language || "plaintext";
550
+ const model = monaco.editor.createModel(
551
+ options.value,
552
+ language,
553
+ monaco.Uri.parse(`inmemory://chat/code-preview-${++previewCount}.${language}`),
554
+ );
555
+ const editor = monaco.editor.create(options.container, {
556
+ model,
557
+ theme: isDarkTheme() ? "chatroom-dark" : "chatroom-light",
558
+ readOnly: true,
559
+ automaticLayout: true,
560
+ minimap: { enabled: false },
561
+ scrollBeyondLastLine: false,
562
+ fontSize: 12,
563
+ lineNumbers: "on",
564
+ wordWrap: "off",
565
+ renderLineHighlight: "none",
566
+ overviewRulerLanes: 0,
567
+ hideCursorInOverviewRuler: true,
568
+ folding: true,
569
+ padding: { top: 10, bottom: 10 },
570
+ scrollbar: { verticalScrollbarSize: 8, horizontalScrollbarSize: 8, useShadows: false },
571
+ contextmenu: true,
572
+ ariaLabel: "Code preview",
573
+ });
574
+ return { dispose: () => { editor.dispose(); model.dispose(); } };
439
575
  }
@@ -1,5 +1,6 @@
1
1
  // Build entry for the lazy integration rules editor. Keeping Monaco contributions out
2
2
  // of integrations.js means the editor bundle is fetched only when the panel opens.
3
+ import "monaco-editor/basic-languages/monaco.contribution";
3
4
  import "monaco-editor/editor/contrib/bracketMatching/browser/bracketMatching";
4
5
  import "monaco-editor/editor/contrib/clipboard/browser/clipboard";
5
6
  import "monaco-editor/editor/contrib/codeAction/browser/codeActionContributions";
@@ -16,7 +17,10 @@ import "monaco-editor/editor/contrib/snippet/browser/snippetController2";
16
17
  import "monaco-editor/editor/contrib/suggest/browser/suggestController";
17
18
  import "monaco-editor/editor/contrib/wordHighlighter/browser/wordHighlighter";
18
19
  import "monaco-editor/editor/contrib/wordOperations/browser/wordOperations";
20
+ import "monaco-editor/editor/contrib/codelens/browser/codeLensCache";
21
+ import "monaco-editor/editor/contrib/codelens/browser/codelensController";
22
+ import "monaco-editor/editor/common/services/treeViewsDndService";
19
23
  import "monaco-editor/editor/browser/coreCommands";
20
24
 
21
- export { createIntegrationRulesEditor } from "./integration-rules-editor";
22
- export type { IntegrationRulesEditor, EditorValidation, RulesFormat, RulesKind } from "./integration-rules-editor";
25
+ export { createCodePreviewEditor, createIntegrationRulesEditor } from "./integration-rules-editor";
26
+ export type { CodePreviewOptions, IntegrationRulesEditor, EditorValidation, RulesFormat, RulesKind } from "./integration-rules-editor";