@alexsun-top/opencode-chat-room 0.6.5 → 0.6.7

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 (84) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -0
  3. package/README.zh-CN.md +4 -0
  4. package/cli.ts +1 -1
  5. package/docs/administrator-rooms.md +5 -4
  6. package/index.ts +2 -2
  7. package/package.json +5 -2
  8. package/plugin.ts +21 -20
  9. package/server/admin-routes.ts +15 -7
  10. package/server/admin-state.ts +2 -2
  11. package/server/announcement-routes.ts +2 -2
  12. package/server/assets/attachments.css +25 -0
  13. package/server/assets/base.css +42 -30
  14. package/server/assets/chat/admin-badge.js +27 -0
  15. package/server/assets/chat/admin.js +71 -24
  16. package/server/assets/chat/announcements.js +27 -11
  17. package/server/assets/chat/attachments.js +50 -10
  18. package/server/assets/chat/events.js +31 -7
  19. package/server/assets/chat/image-zoom.js +57 -0
  20. package/server/assets/chat/index.js +4 -0
  21. package/server/assets/chat/markdown.js +33 -4
  22. package/server/assets/chat/members.js +14 -6
  23. package/server/assets/chat/message-polling.js +137 -0
  24. package/server/assets/chat/message-window.js +14 -0
  25. package/server/assets/chat/messages.js +6 -128
  26. package/server/assets/chat/panels.js +37 -0
  27. package/server/assets/chat/pwa.js +18 -0
  28. package/server/assets/chat/receipts.js +3 -1
  29. package/server/assets/chat/reminders.js +19 -5
  30. package/server/assets/chat/room-list.js +51 -0
  31. package/server/assets/chat/rooms.js +20 -80
  32. package/server/assets/chat/state.js +28 -14
  33. package/server/assets/chat/system-messages.js +25 -7
  34. package/server/assets/conversation.css +18 -26
  35. package/server/assets/icons/apple-touch-icon.png +0 -0
  36. package/server/assets/icons/icon-192.png +0 -0
  37. package/server/assets/icons/icon-512.png +0 -0
  38. package/server/assets/responsive.css +25 -8
  39. package/server/chat-server.ts +58 -8
  40. package/server/chat.html +108 -68
  41. package/server/history-route.ts +1 -1
  42. package/server/inbox.ts +2 -2
  43. package/server/manifest.webmanifest +15 -0
  44. package/server/member-routes.ts +4 -4
  45. package/server/newrooms.ts +96 -13
  46. package/server/resource-routes.ts +19 -5
  47. package/server/room-owner.ts +89 -0
  48. package/server/room-payload.ts +4 -2
  49. package/server/room-reminders.ts +3 -3
  50. package/server/sw.js +73 -0
  51. package/server/wake.ts +5 -5
  52. package/skills/chatroom/SKILL.md +3 -1
  53. package/src/README.md +20 -0
  54. package/src/{admin-client.ts → agent/admin-client.ts} +15 -9
  55. package/src/{admin-credentials.ts → agent/admin-credentials.ts} +1 -1
  56. package/src/{agent-presence.ts → agent/agent-presence.ts} +2 -2
  57. package/src/{agent-receipts.ts → agent/agent-receipts.ts} +2 -2
  58. package/src/{announcement-tool.ts → agent/announcement-tool.ts} +2 -2
  59. package/src/{chatroom-skill.ts → agent/chatroom-skill.ts} +1 -1
  60. package/src/{center-client.ts → center/center-client.ts} +22 -9
  61. package/src/{center-inbox.ts → center/center-inbox.ts} +9 -9
  62. package/src/{center-wake.ts → center/center-wake.ts} +6 -6
  63. package/src/{mentions.ts → center/mentions.ts} +1 -1
  64. package/src/{queue-transport.ts → center/queue-transport.ts} +3 -3
  65. package/src/{queue.ts → center/queue.ts} +2 -2
  66. package/src/{reminder-client.ts → center/reminder-client.ts} +1 -1
  67. package/src/{session-delivery.ts → center/session-delivery.ts} +1 -1
  68. package/src/{announcements.ts → rooms/announcements.ts} +2 -2
  69. package/src/{resource-upload.ts → rooms/resource-upload.ts} +1 -1
  70. package/src/{resources.ts → rooms/resources.ts} +55 -9
  71. package/src/{room-service.ts → rooms/room-service.ts} +12 -1
  72. package/src/{background.ts → runtime/background.ts} +3 -3
  73. package/src/{plugin-notifications.ts → runtime/plugin-notifications.ts} +8 -8
  74. package/src/{v1-plugin.ts → runtime/v1-plugin.ts} +4 -4
  75. package/src/{v2-plugin.ts → runtime/v2-plugin.ts} +9 -9
  76. package/src/{v2-receiver.ts → runtime/v2-receiver.ts} +7 -7
  77. package/src/{watch.ts → runtime/watch.ts} +12 -12
  78. package/src/{member-state.ts → state/member-state.ts} +2 -2
  79. package/src/{sqlite-state.ts → state/sqlite-state.ts} +35 -15
  80. package/src/{store.ts → state/store.ts} +2 -2
  81. package/src/tests/announcement-board.ts +176 -0
  82. /package/src/{resource-read.ts → rooms/resource-read.ts} +0 -0
  83. /package/src/{receiver-owner.ts → state/receiver-owner.ts} +0 -0
  84. /package/src/{receiver-state.ts → state/receiver-state.ts} +0 -0
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { promises as fs } from "node:fs";
3
3
  import path from "node:path";
4
- import { databasePath, readState } from "./store";
5
- import { getResource, putResource, type StoredResource } from "./sqlite-state";
4
+ import { databasePath, readState } from "../state/store.ts";
5
+ import { getResource, putResource, removeResource, type StoredResource } from "../state/sqlite-state.ts";
6
6
 
7
7
  export type Resource = StoredResource;
8
8
  export class ResourceError extends Error {
@@ -41,17 +41,42 @@ function safeName(value: string): string {
41
41
  return value;
42
42
  }
43
43
 
44
- export async function uploadResource(roomID: string, filename: string, body: ReadableStream<Uint8Array>, limitBytes: number): Promise<Resource> {
44
+ function sameUpload(existing: Resource, name: string, uploader?: { sessionID: string; name: string }): boolean {
45
+ return existing.name === name && (existing.uploaderSessionID ?? undefined) === uploader?.sessionID && (existing.uploaderName ?? undefined) === uploader?.name;
46
+ }
47
+ function replay(existing: Resource, name: string, uploader?: { sessionID: string; name: string }): Resource {
48
+ if (!sameUpload(existing, name, uploader)) throw new ResourceError(409, "resource id conflict");
49
+ return existing;
50
+ }
51
+ async function waitForResource(roomID: string, id: string): Promise<Resource | undefined> {
52
+ // Another attempt linked the file but has not inserted its row yet.
53
+ for (let attempt = 0; attempt < 40; attempt++) {
54
+ const existing = await getResource(databasePath(), roomID, id);
55
+ if (existing) return existing;
56
+ await new Promise((resolve) => setTimeout(resolve, 25));
57
+ }
58
+ return undefined;
59
+ }
60
+
61
+ export async function uploadResource(roomID: string, filename: string, body: ReadableStream<Uint8Array>, limitBytes: number, uploader?: { sessionID: string; name: string }, requestedID?: string): Promise<Resource> {
45
62
  if (!uuid.test(roomID)) throw new ResourceError(404, "room not found");
63
+ if (requestedID !== undefined && !uuid.test(requestedID)) throw new ResourceError(400, "invalid resource id");
46
64
  if (!Number.isSafeInteger(limitBytes) || limitBytes <= 0) throw new Error("limitBytes must be a positive safe integer");
47
65
  if (!await readState((service) => service.listRooms().some((room) => room.id === roomID))) throw new ResourceError(404, "room not found");
48
66
  const name = safeName(filename);
67
+ // A retry after a lost response reuses the client's resource ID; return the committed
68
+ // resource instead of storing the same bytes again.
69
+ if (requestedID) {
70
+ const existing = await getResource(databasePath(), roomID, requestedID);
71
+ if (existing) return replay(existing, name, uploader);
72
+ }
49
73
  const dir = roomDirectory(roomID);
50
74
  await fs.mkdir(dir, { recursive: true, mode: 0o700 });
51
- const id = randomUUID();
52
- const temp = path.join(dir, `${id}.tmp`);
75
+ const id = requestedID ?? randomUUID();
76
+ const temp = path.join(dir, `${id}.${randomUUID()}.tmp`);
53
77
  const dest = resourcePath({ id, roomID } as Resource);
54
78
  let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
79
+ let linked = false;
55
80
  try {
56
81
  handle = await fs.open(temp, "wx", 0o600);
57
82
  const reader = body.getReader();
@@ -77,15 +102,29 @@ export async function uploadResource(roomID: string, filename: string, body: Rea
77
102
  await reader.cancel().catch(() => {});
78
103
  throw error;
79
104
  } finally { reader.releaseLock(); }
80
- const resource: Resource = { id, roomID, name, mimeType: mime(prefix.subarray(0, prefixSize)), size, createdAt: Date.now() };
105
+ const resource: Resource = { id, roomID, name, mimeType: mime(prefix.subarray(0, prefixSize)), size, createdAt: Date.now(), ...(uploader ? { uploaderSessionID: uploader.sessionID, uploaderName: uploader.name } : {}) };
81
106
  await handle.close(); handle = undefined;
82
- await fs.rename(temp, dest);
83
- if (!await putResource(databasePath(), resource)) throw new ResourceError(404, "room not found");
107
+ // link() creates the final name only if absent; rename() would replace another attempt's file.
108
+ try { await fs.link(temp, dest); linked = true; }
109
+ catch (error) {
110
+ await fs.rm(temp, { force: true }).catch(() => {});
111
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
112
+ const existing = requestedID ? await waitForResource(roomID, id) : undefined;
113
+ if (existing) return replay(existing, name, uploader);
114
+ throw new ResourceError(409, "resource id conflict");
115
+ }
116
+ await fs.rm(temp, { force: true }).catch(() => {});
117
+ try { if (!await putResource(databasePath(), resource)) throw new ResourceError(404, "room not found"); }
118
+ catch (error) {
119
+ const existing = requestedID ? await getResource(databasePath(), roomID, id).catch(() => undefined) : undefined;
120
+ if (existing) return replay(existing, name, uploader);
121
+ throw error;
122
+ }
84
123
  return resource;
85
124
  } catch (error) {
86
125
  await handle?.close().catch(() => {});
87
126
  await fs.rm(temp, { force: true }).catch(() => {});
88
- await fs.rm(dest, { force: true }).catch(() => {});
127
+ if (linked) await fs.rm(dest, { force: true }).catch(() => {});
89
128
  throw error;
90
129
  }
91
130
  }
@@ -98,6 +137,13 @@ export async function findResource(roomID: string, id: string): Promise<Resource
98
137
  if (!uuid.test(id)) return undefined;
99
138
  return getResource(databasePath(), roomID, id);
100
139
  }
140
+ export async function deleteResource(roomID: string, id: string): Promise<boolean> {
141
+ const resource = await findResource(roomID, id);
142
+ if (!resource) return false;
143
+ await removeResource(databasePath(), roomID, id);
144
+ await fs.rm(resourcePath(resource), { force: true });
145
+ return true;
146
+ }
101
147
  export async function removeRoomResources(roomID: string): Promise<void> {
102
148
  if (!uuid.test(roomID)) throw new ResourceError(404, "room not found");
103
149
  if (await readState((service) => service.listRooms().some((room) => room.id === roomID))) {
@@ -23,6 +23,16 @@ export type Room = {
23
23
  name: string;
24
24
  description?: string;
25
25
  ownerId: string;
26
+ // Server-issued membership binding for the owner and the explicitly chosen successor.
27
+ // Display names remain the public identity; the membership IDs guard against name reuse.
28
+ ownerMembershipID?: string;
29
+ successorId?: string;
30
+ successorMembershipID?: string;
31
+ // Humans authorized by the owner or another admin; the owner is always an admin.
32
+ adminIds?: string[];
33
+ // Server-issued membership bindings matching adminIds, so a same-name session
34
+ // does not inherit delegation. Missing for legacy rooms; names are the fallback.
35
+ adminMembershipIDs?: string[];
26
36
  participants: Map<string, Participant>;
27
37
  messages: Message[];
28
38
  createdAt: number;
@@ -35,7 +45,8 @@ export type RoomErrorCode =
35
45
  | "ROOM_NOT_FOUND"
36
46
  | "NOT_JOINED"
37
47
  | "EMPTY_MESSAGE"
38
- | "DIRECT_ROOM_FULL";
48
+ | "DIRECT_ROOM_FULL"
49
+ | "NOT_OWNER";
39
50
 
40
51
  export class RoomError extends Error {
41
52
  readonly code: RoomErrorCode;
@@ -1,6 +1,6 @@
1
- import { receiverOwnerID } from "./receiver-owner";
2
- import { assertDeliveryLease } from "./session-delivery";
3
- import type { BackgroundResult } from "./queue-transport";
1
+ import { receiverOwnerID } from "../state/receiver-owner.ts";
2
+ import { assertDeliveryLease } from "../center/session-delivery.ts";
3
+ import type { BackgroundResult } from "../center/queue-transport.ts";
4
4
 
5
5
  type BackgroundHost = NonNullable<Awaited<ReturnType<typeof discoverVerifiedHost>>> & { pid: number; version: string };
6
6
  type HostLookup = { host?: BackgroundHost; result?: BackgroundResult };
@@ -1,6 +1,6 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
- import type { Message } from "./room-service";
3
+ import type { Message } from "../rooms/room-service.ts";
4
4
  import {
5
5
  formatNotificationLines,
6
6
  loadRegistry,
@@ -8,12 +8,12 @@ import {
8
8
  readQuestionExcerpt,
9
9
  statePath,
10
10
  timeOf,
11
- } from "./store";
12
- import { backgroundResult, backgroundServiceKey, sendAsyncNotification, sendQueue, type BackgroundResult, type QueueTransport } from "./queue-transport";
13
- import { explicitlyAddresses } from "./mentions";
14
- import { claimBackgroundAttempt } from "./receiver-state";
15
- import { serializeSessionPush } from "./center-inbox";
16
- import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
11
+ } from "../state/store.ts";
12
+ import { backgroundResult, backgroundServiceKey, sendAsyncNotification, sendQueue, type BackgroundResult, type QueueTransport } from "../center/queue-transport.ts";
13
+ import { explicitlyAddresses } from "../center/mentions.ts";
14
+ import { claimBackgroundAttempt } from "../state/receiver-state.ts";
15
+ import { serializeSessionPush } from "../center/center-inbox.ts";
16
+ import { prepareReceiptCandidate, receiptDestination } from "../agent/agent-receipts.ts";
17
17
  import {
18
18
  getOrCreatePendingAdmission,
19
19
  clearPendingAdmission,
@@ -22,7 +22,7 @@ import {
22
22
  rejectPendingAdmission,
23
23
  prunePendingAdmission,
24
24
  type QueueItem,
25
- } from "./queue";
25
+ } from "../center/queue.ts";
26
26
 
27
27
  type NotifyBatch = { roomId: string; roomName: string; roomKind?: "group" | "direct"; messages: Message[] };
28
28
  type NotifyAttempt = { url: string; status: number };
@@ -1,10 +1,10 @@
1
1
  import type { Config, Plugin, PluginInput, ToolDefinition } from "@opencode-ai/plugin";
2
- import type { V2Runtime } from "./v2-plugin";
3
- import type { QueueTransport } from "./queue-transport";
2
+ import type { V2Runtime } from "./v2-plugin.ts";
3
+ import type { QueueTransport } from "../center/queue-transport.ts";
4
4
  import { fileURLToPath } from "node:url";
5
- import { request } from "./center-client";
5
+ import { request } from "../center/center-client.ts";
6
6
 
7
- const bundledSkillsPath = fileURLToPath(new URL("../skills", import.meta.url));
7
+ const bundledSkillsPath = fileURLToPath(new URL("../../skills", import.meta.url));
8
8
 
9
9
  export function createV1Server(deps: {
10
10
  runtime(input: PluginInput, transport: QueueTransport): V2Runtime;
@@ -1,12 +1,12 @@
1
1
  import type { Skill, Plugin } from "@opencode/plugin";
2
2
  import { z } from "zod";
3
- import type { QueueTransport } from "./center-client";
4
- import { backgroundOwnSession, discoverVerifiedHost, verifyHostSession } from "./background";
5
- import { receiverOwnerID } from "./receiver-owner";
6
- import { attachV2Receiver } from "./v2-receiver";
7
- import { observeReceiptContext, receiptDestination } from "./agent-receipts";
8
- import { chatroomSkill } from "./chatroom-skill";
9
- import { adminToolDescription, adminToolSchema } from "./admin-client";
3
+ import type { QueueTransport } from "../center/center-client.ts";
4
+ import { backgroundOwnSession, discoverVerifiedHost, verifyHostSession } from "./background.ts";
5
+ import { receiverOwnerID } from "../state/receiver-owner.ts";
6
+ import { attachV2Receiver } from "./v2-receiver.ts";
7
+ import { observeReceiptContext, receiptDestination } from "../agent/agent-receipts.ts";
8
+ import { chatroomSkill } from "../agent/chatroom-skill.ts";
9
+ import { adminToolDescription, adminToolSchema } from "../agent/admin-client.ts";
10
10
 
11
11
  type CenterOptions = { center: string; token: string; directory?: string };
12
12
  export type V2Runtime = {
@@ -81,7 +81,7 @@ export function createV2Setup(deps: {
81
81
  });
82
82
  toolRegistration = await context.tool.transform((editor) => editor.add({
83
83
  name: "room",
84
- description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; manage reminders. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup.",
84
+ description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; manage reminders. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads.",
85
85
  options: { codemode: false },
86
86
  input: roomSchema(),
87
87
  execute: async (args, toolContext) => {
@@ -169,7 +169,7 @@ export function createV2Setup(deps: {
169
169
 
170
170
  export function roomSchema() {
171
171
  return z.object({
172
- action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
172
+ action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
173
173
  name: z.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
174
174
  roomId: z.string().optional(),
175
175
  resourceId: z.string().optional(),
@@ -1,11 +1,11 @@
1
- import { backgroundOwnSession, discoverVerifiedHost } from "./background";
1
+ import { backgroundOwnSession, discoverVerifiedHost } from "./background.ts";
2
2
  import { createHash } from "node:crypto";
3
- import { receiverOwnerID } from "./receiver-owner";
4
- import { loadRegistry } from "./store";
5
- import { request, type CenterOpts } from "./center-client";
6
- import type { QueueTransport } from "./queue-transport";
7
- import { locallyOwnedSessions, reportAgentPresence } from "./agent-presence";
8
- import { flushReceiptCandidates, receiptDestination } from "./agent-receipts";
3
+ import { receiverOwnerID } from "../state/receiver-owner.ts";
4
+ import { loadRegistry } from "../state/store.ts";
5
+ import { request, type CenterOpts } from "../center/center-client.ts";
6
+ import type { QueueTransport } from "../center/queue-transport.ts";
7
+ import { locallyOwnedSessions, reportAgentPresence } from "../agent/agent-presence.ts";
8
+ import { flushReceiptCandidates, receiptDestination } from "../agent/agent-receipts.ts";
9
9
 
10
10
  export type Attachment = {
11
11
  sessions: ReadonlySet<string>;
@@ -5,17 +5,17 @@ import { spawn } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
- import { backgroundAtCompatibleRegisteredHost, discoverCompatibleRegisteredHost } from "./background";
9
- import { receiverOwnerID } from "./receiver-owner";
10
- import { claimWatcher, closeReceiverState, releaseWatcherClaim, receiverStateDirectory, watcherProcessMayExist } from "./receiver-state";
11
- import { databasePath, loadRegistry } from "./store";
12
- import { request, type CenterOpts } from "./center-client";
13
- import { assertDeliveryLease } from "./session-delivery";
14
- import type { QueueTransport } from "./queue-transport";
15
- import { pollOwnedSessions } from "./v2-receiver";
16
- import { pollKnownSessions } from "../plugin";
17
- import { locallyOwnedSessions, reportAgentPresence } from "./agent-presence";
18
- import { flushReceiptCandidates, receiptDestination } from "./agent-receipts";
8
+ import { backgroundAtCompatibleRegisteredHost, discoverCompatibleRegisteredHost } from "./background.ts";
9
+ import { receiverOwnerID } from "../state/receiver-owner.ts";
10
+ import { claimWatcher, closeReceiverState, releaseWatcherClaim, receiverStateDirectory, watcherProcessMayExist } from "../state/receiver-state.ts";
11
+ import { databasePath, loadRegistry } from "../state/store.ts";
12
+ import { request, type CenterOpts } from "../center/center-client.ts";
13
+ import { assertDeliveryLease } from "../center/session-delivery.ts";
14
+ import type { QueueTransport } from "../center/queue-transport.ts";
15
+ import { pollOwnedSessions } from "./v2-receiver.ts";
16
+ import { pollKnownSessions } from "../../plugin";
17
+ import { locallyOwnedSessions, reportAgentPresence } from "../agent/agent-presence.ts";
18
+ import { flushReceiptCandidates, receiptDestination } from "../agent/agent-receipts.ts";
19
19
 
20
20
  type WatchRecord = { phase: "starting" | "running"; token: string; nonce: string; instanceID: string; pid: number; port?: number; createdAt?: number };
21
21
  function canonicalPath(value: string): string {
@@ -236,7 +236,7 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
236
236
  }
237
237
  throw new Error("watcher state exists or is starting; no process was signaled");
238
238
  }
239
- const cli = fileURLToPath(new URL("../cli.ts", import.meta.url));
239
+ const cli = fileURLToPath(new URL("../../cli.ts", import.meta.url));
240
240
  let childError: Error | undefined;
241
241
  const child = spawn(process.execPath, [path.resolve(cli), "watch", "run"], {
242
242
  detached: true, stdio: "ignore",
@@ -1,6 +1,6 @@
1
- import type { RegistryEntry, WorkState } from "./store";
1
+ import type { RegistryEntry, WorkState } from "./store.ts";
2
2
 
3
- export type { WorkState } from "./store";
3
+ export type { WorkState } from "./store.ts";
4
4
  export type ActivityState = WorkState | "offline";
5
5
  export const PRESENCE_TTL_MS = 60_000;
6
6
 
@@ -2,9 +2,9 @@ import { Database } from "bun:sqlite";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import path from "node:path";
5
- import RoomService, { type Message, type Room, type Participant } from "./room-service";
6
- import type { MessageReceipt, PresenceReport, ReceiptEvidence, ReceiptIdentity, ReceiptWriteResult, Registry, RegistryEntry } from "./store";
7
- import { presenceOwnerMatches, receiptOwnerMatches } from "./member-state";
5
+ import RoomService, { type Message, type Room, type Participant } from "../rooms/room-service.ts";
6
+ import type { MessageReceipt, PresenceReport, ReceiptEvidence, ReceiptIdentity, ReceiptWriteResult, Registry, RegistryEntry } from "./store.ts";
7
+ import { presenceOwnerMatches, receiptOwnerMatches } from "./member-state.ts";
8
8
 
9
9
  type State = { rooms: Room[]; registry: Registry };
10
10
  type Page<T> = { items: T[]; hasMore: boolean };
@@ -84,7 +84,7 @@ async function initialize(file: string): Promise<Database> {
84
84
  CREATE INDEX IF NOT EXISTS messages_room_time ON messages(room_id,created_at,seq);
85
85
  CREATE TABLE IF NOT EXISTS registry(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,session_id TEXT NOT NULL,server_url TEXT NOT NULL,api_prefix TEXT NOT NULL,protocol TEXT,name TEXT NOT NULL,last_read_ts INTEGER,last_queued_ts INTEGER,directory TEXT,host TEXT,receiver_owner_id TEXT,membership_id TEXT,work_state TEXT,last_seen_at INTEGER,PRIMARY KEY(room_id,session_id));`);
86
86
  db.exec("CREATE TABLE IF NOT EXISTS announcements(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,name TEXT NOT NULL,content TEXT NOT NULL,updated_at INTEGER NOT NULL,PRIMARY KEY(room_id,name))");
87
- db.exec("CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,name TEXT NOT NULL,mime_type TEXT NOT NULL,size INTEGER NOT NULL,created_at INTEGER NOT NULL)");
87
+ db.exec("CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,name TEXT NOT NULL,mime_type TEXT NOT NULL,size INTEGER NOT NULL,created_at INTEGER NOT NULL,uploader_session_id TEXT,uploader_name TEXT)");
88
88
  await ensureRoomColumns(db);
89
89
  await migrate(db, file);
90
90
  db.exec("PRAGMA busy_timeout=50;");
@@ -120,21 +120,27 @@ export async function deleteAnnouncement(file: string, roomID: string, name: str
120
120
  return immediate(db, () => db.query("DELETE FROM announcements WHERE room_id=? AND name=?").run(roomID, name).changes > 0);
121
121
  }
122
122
 
123
- export type StoredResource = { id: string; roomID: string; name: string; mimeType: string; size: number; createdAt: number };
123
+ export type StoredResource = { id: string; roomID: string; name: string; mimeType: string; size: number; createdAt: number; uploaderSessionID?: string | null; uploaderName?: string | null };
124
124
  export async function putResource(file: string, resource: StoredResource): Promise<boolean> {
125
125
  const db = await openStateDatabase(file);
126
126
  return immediate(db, () => {
127
127
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(resource.roomID)) return false;
128
- db.query("INSERT INTO resources(id,room_id,name,mime_type,size,created_at) VALUES(?,?,?,?,?,?)")
129
- .run(resource.id, resource.roomID, resource.name, resource.mimeType, resource.size, resource.createdAt);
128
+ db.query("INSERT INTO resources(id,room_id,name,mime_type,size,created_at,uploader_session_id,uploader_name) VALUES(?,?,?,?,?,?,?,?)")
129
+ .run(resource.id, resource.roomID, resource.name, resource.mimeType, resource.size, resource.createdAt, resource.uploaderSessionID ?? null, resource.uploaderName ?? null);
130
130
  return true;
131
131
  });
132
132
  }
133
133
  export async function getResource(file: string, roomID: string, id: string): Promise<StoredResource | undefined> {
134
134
  const db = await openStateDatabase(file);
135
- const row = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt FROM resources WHERE room_id=? AND id=?")
136
- .get(roomID, id) as StoredResource | null;
137
- return row ?? undefined;
135
+ const row = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? AND id=?")
136
+ .get(roomID, id) as (StoredResource & { uploaderSessionID: string | null; uploaderName: string | null }) | null;
137
+ if (!row) return undefined;
138
+ const { uploaderSessionID, uploaderName, ...rest } = row;
139
+ return { ...rest, ...(uploaderSessionID ? { uploaderSessionID } : {}), ...(uploaderName ? { uploaderName } : {}) };
140
+ }
141
+ export async function removeResource(file: string, roomID: string, id: string): Promise<boolean> {
142
+ const db = await openStateDatabase(file);
143
+ return immediate(db, () => db.query("DELETE FROM resources WHERE room_id=? AND id=?").run(roomID, id).changes > 0);
138
144
  }
139
145
  async function ensureRoomColumns(db: Database): Promise<void> {
140
146
  await immediate(db, () => {
@@ -148,6 +154,14 @@ async function ensureRoomColumns(db: Database): Promise<void> {
148
154
  if (!columns.some((column) => column.name === "direct_sessions")) db.exec("ALTER TABLE rooms ADD COLUMN direct_sessions TEXT");
149
155
  if (!columns.some((column) => column.name === "direct_pair")) db.exec("ALTER TABLE rooms ADD COLUMN direct_pair TEXT");
150
156
  if (!columns.some((column) => column.name === "description")) db.exec("ALTER TABLE rooms ADD COLUMN description TEXT");
157
+ if (!columns.some((column) => column.name === "admin_names")) db.exec("ALTER TABLE rooms ADD COLUMN admin_names TEXT");
158
+ if (!columns.some((column) => column.name === "admin_membership_ids")) db.exec("ALTER TABLE rooms ADD COLUMN admin_membership_ids TEXT");
159
+ if (!columns.some((column) => column.name === "owner_membership_id")) db.exec("ALTER TABLE rooms ADD COLUMN owner_membership_id TEXT");
160
+ if (!columns.some((column) => column.name === "successor_name")) db.exec("ALTER TABLE rooms ADD COLUMN successor_name TEXT");
161
+ if (!columns.some((column) => column.name === "successor_membership_id")) db.exec("ALTER TABLE rooms ADD COLUMN successor_membership_id TEXT");
162
+ const resourceColumns = db.query("PRAGMA table_info(resources)").all() as Array<{ name: string }>;
163
+ if (!resourceColumns.some((column) => column.name === "uploader_session_id")) db.exec("ALTER TABLE resources ADD COLUMN uploader_session_id TEXT");
164
+ if (!resourceColumns.some((column) => column.name === "uploader_name")) db.exec("ALTER TABLE resources ADD COLUMN uploader_name TEXT");
151
165
  const registry = db.query("PRAGMA table_info(registry)").all() as Array<{ name: string }>;
152
166
  if (!registry.some((column) => column.name === "membership_id")) db.exec("ALTER TABLE registry ADD COLUMN membership_id TEXT");
153
167
  if (!registry.some((column) => column.name === "work_state")) db.exec("ALTER TABLE registry ADD COLUMN work_state TEXT");
@@ -261,8 +275,14 @@ function validateRegistry(value: unknown): Registry {
261
275
  return result;
262
276
  }
263
277
 
278
+ function roomColumns(room: Room): string | null {
279
+ return room.adminIds?.length ? JSON.stringify([...new Set(room.adminIds)]) : null;
280
+ }
281
+ const adminBindings = (room: Room) => room.adminMembershipIDs?.length ? JSON.stringify([...new Set(room.adminMembershipIDs)]) : null;
282
+ const roomBindings = (room: Room) => [room.ownerMembershipID ?? null, room.successorId ?? null, room.successorMembershipID ?? null];
283
+
264
284
  function insertRoom(db: Database, room: Room): void {
265
- db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description) 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);
285
+ 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) 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));
266
286
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
267
287
  for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
268
288
  const message = db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by) VALUES(?,?,?,?,?,?,?,?,?)");
@@ -281,7 +301,7 @@ function replaceRegistry(db: Database, registry: Registry): void {
281
301
  }
282
302
 
283
303
  function persistState(db: Database, rooms: Room[], registry: Registry): void {
284
- const roomRow = db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description) 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");
304
+ 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) 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");
285
305
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
286
306
  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) VALUES(?,?,?,?,?,?,?,?,?)");
287
307
  const removeParticipants = db.query("DELETE FROM participants WHERE room_id=?");
@@ -290,7 +310,7 @@ function persistState(db: Database, rooms: Room[], registry: Registry): void {
290
310
  const deleteRoom = db.query("DELETE FROM rooms WHERE id=?");
291
311
  for (const row of existing) if (!keep.has(row.id)) deleteRoom.run(row.id);
292
312
  for (const room of rooms) {
293
- 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);
313
+ 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));
294
314
  removeParticipants.run(room.id);
295
315
  for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
296
316
  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);
@@ -299,14 +319,14 @@ function persistState(db: Database, rooms: Room[], registry: Registry): void {
299
319
  }
300
320
 
301
321
  function readState(db: Database): State {
302
- const roomRows = db.query("SELECT id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description FROM rooms ORDER BY created_at,id").all() as Array<Record<string, string | number | null>>;
322
+ const roomRows = db.query("SELECT 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 FROM rooms ORDER BY created_at,id").all() as Array<Record<string, string | number | null>>;
303
323
  const rooms = roomRows.map((r): Room => {
304
324
  const participants = new Map<string, Participant>();
305
325
  for (const p of db.query("SELECT id,name,joined_at FROM participants WHERE room_id=?").all(String(r.id)) as Array<Record<string, string | number>>) {
306
326
  participants.set(String(p.id), { id: String(p.id), name: String(p.name), joinedAt: Number(p.joined_at) });
307
327
  }
308
328
  const messages = db.query("SELECT id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 500").all(String(r.id)) as Array<Record<string, string | number | null>>;
309
- return { id: String(r.id), name: String(r.name), ownerId: String(r.owner_id), createdAt: Number(r.created_at), kind: r.kind === "direct" ? "direct" : "group", ...(r.description ? { description: String(r.description) } : {}), ...(r.direct_sessions ? { directSessionIDs: JSON.parse(String(r.direct_sessions)) as string[] } : {}), ...(r.direct_pair ? { directPair: String(r.direct_pair) } : {}), participants,
329
+ return { id: String(r.id), name: String(r.name), ownerId: String(r.owner_id), createdAt: Number(r.created_at), kind: r.kind === "direct" ? "direct" : "group", ...(r.description ? { description: String(r.description) } : {}), ...(r.admin_names ? { adminIds: JSON.parse(String(r.admin_names)) as string[] } : {}), ...(r.admin_membership_ids ? { adminMembershipIDs: JSON.parse(String(r.admin_membership_ids)) as string[] } : {}), ...(r.owner_membership_id ? { ownerMembershipID: String(r.owner_membership_id) } : {}), ...(r.successor_name ? { successorId: String(r.successor_name) } : {}), ...(r.successor_membership_id ? { successorMembershipID: String(r.successor_membership_id) } : {}), ...(r.direct_sessions ? { directSessionIDs: JSON.parse(String(r.direct_sessions)) as string[] } : {}), ...(r.direct_pair ? { directPair: String(r.direct_pair) } : {}), participants,
310
330
  messages: messages.reverse().map((m) => ({ id: String(m.id), roomId: String(m.room_id), senderId: String(m.sender_id),
311
331
  text: String(m.text), createdAt: Number(m.created_at), ...(m.sender_session_id ? { senderSessionID: String(m.sender_session_id) } : {}), ...(m.is_question ? { isQuestion: true } : {}), ...(m.answer_to ? { answerToMessageID: String(m.answer_to) } : {}), ...(m.answered_by ? { answeredByMessageID: String(m.answered_by) } : {}) })) };
312
332
  });
@@ -3,8 +3,8 @@
3
3
  // mode) and server/chat-server.ts (central mode).
4
4
  import path from "node:path";
5
5
  import os from "node:os";
6
- import RoomService, { type Message, type Room } from "./room-service";
7
- import { acknowledgeQueued as sqliteAcknowledgeQueued, acknowledgeRead as sqliteAcknowledgeRead, answerQuestion as sqliteAnswerQuestion, appendRoomMessage as sqliteAppendRoomMessage, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, countOpenQuestions as sqliteCountOpenQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
6
+ import RoomService, { type Message, type Room } from "../rooms/room-service.ts";
7
+ import { acknowledgeQueued as sqliteAcknowledgeQueued, acknowledgeRead as sqliteAcknowledgeRead, answerQuestion as sqliteAnswerQuestion, appendRoomMessage as sqliteAppendRoomMessage, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, countOpenQuestions as sqliteCountOpenQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state.ts";
8
8
 
9
9
  export function statePath(): string {
10
10
  // JSON path remains the migration source; SQLite lives beside it.