@alexsun-top/opencode-chat-room 0.6.7 → 0.6.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +6 -3
- package/README.zh-CN.md +7 -3
- package/docs/administrator-rooms.md +7 -2
- package/package.json +4 -1
- package/plugin.ts +38 -8
- package/server/assets/base.css +222 -28
- package/server/assets/chat/admin-badge.js +28 -6
- package/server/assets/chat/admin.js +7 -1
- package/server/assets/chat/announcements.js +1 -1
- package/server/assets/chat/attachment-store.js +106 -0
- package/server/assets/chat/attachments.js +201 -21
- package/server/assets/chat/confirm-dialog.js +28 -0
- package/server/assets/chat/events.js +37 -9
- package/server/assets/chat/image-zoom.js +86 -2
- package/server/assets/chat/index.js +10 -0
- package/server/assets/chat/install-prompt.js +82 -0
- package/server/assets/chat/join-requests.js +355 -0
- package/server/assets/chat/markdown.js +55 -7
- package/server/assets/chat/members.js +5 -3
- package/server/assets/chat/message-polling.js +24 -3
- package/server/assets/chat/messages.js +6 -4
- package/server/assets/chat/questions.js +10 -6
- package/server/assets/chat/recall.js +267 -0
- package/server/assets/chat/reminders.js +53 -9
- package/server/assets/chat/replies.js +1 -1
- package/server/assets/chat/room-list.js +14 -5
- package/server/assets/chat/room-watcher.js +5 -1
- package/server/assets/chat/rooms.js +17 -5
- package/server/assets/chat/shortcuts.js +40 -0
- package/server/assets/chat/state.js +69 -16
- package/server/assets/chat/system-messages.js +4 -0
- package/server/assets/conversation.css +2 -2
- package/server/assets/recall.css +29 -0
- package/server/assets/responsive.css +41 -13
- package/server/chat-server.ts +55 -66
- package/server/chat.html +139 -16
- package/server/inbox.ts +1 -1
- package/server/join-requests.ts +106 -0
- package/server/message-recall-routes.ts +37 -0
- package/server/newrooms.ts +9 -0
- package/server/room-join.ts +59 -0
- package/server/room-owner.ts +3 -20
- package/server/room-payload.ts +2 -0
- package/server/sw.js +1 -0
- package/server/wake.ts +45 -16
- package/skills/chatroom/SKILL.md +32 -0
- package/src/README.md +5 -3
- package/src/agent/admin-client.ts +28 -4
- package/src/center/center-client.ts +81 -4
- package/src/center/center-inbox.ts +35 -10
- package/src/center/center-wake.ts +25 -12
- package/src/center/message-ids.ts +7 -0
- package/src/center/notification-budget.ts +16 -0
- package/src/center/queue.ts +14 -4
- package/src/rooms/room-service.ts +10 -1
- package/src/runtime/plugin-notifications.ts +37 -11
- package/src/runtime/v2-plugin.ts +1 -1
- package/src/state/roles.ts +34 -0
- package/src/state/sqlite-state.ts +197 -27
- package/src/state/store.ts +22 -3
- package/src/tests/announcement-board.ts +12 -2
|
@@ -18,10 +18,32 @@ export function canRemoveMember(app, target, selfIsAgent, sessionID) {
|
|
|
18
18
|
return isAdminAgent(app, sessionID) && !(room.adminIds ?? []).includes(target.name);
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
// One label per member: the owner outranks human administrators, who outrank the
|
|
22
|
+
// designated agent. Names are the stable identity shared by rooms and members.
|
|
23
|
+
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" : "";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
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;
|
|
37
|
+
}
|
|
38
|
+
|
|
21
39
|
export function adminAgentBadge(app) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
40
|
+
return badge("admin-agent-badge", app.t("adminAgentLabel"));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
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;
|
|
49
|
+
}
|
|
@@ -60,6 +60,7 @@ export function initAdmin(app) {
|
|
|
60
60
|
const room = app.state.room; if (!room) return;
|
|
61
61
|
$("#editRoomName").value = room.name;
|
|
62
62
|
$("#editRoomDescription").value = room.description || "";
|
|
63
|
+
$("#editRoomJoinPolicy").checked = room.joinPolicy === "approval";
|
|
63
64
|
$("#editRoomStatus").textContent = "";
|
|
64
65
|
people = []; agentsReady = false; rosterReady = false;
|
|
65
66
|
renderOwnerOptions(room);
|
|
@@ -98,8 +99,11 @@ export function initAdmin(app) {
|
|
|
98
99
|
// Until the registry loads, empty rosters are placeholders, not revocations.
|
|
99
100
|
const owner = isOwner(), nextOwner = $("#editRoomOwner").value;
|
|
100
101
|
const checkedAdmins = [...$("#editRoomAdminIds").querySelectorAll("input:checked")].map((input) => input.value);
|
|
102
|
+
const joinPolicy = $("#editRoomJoinPolicy").checked ? "approval" : "open";
|
|
103
|
+
if (joinPolicy !== (room.joinPolicy ?? "open") && joinPolicy === "open" && !(await app.confirmAction(app.t("joinPolicyOpenConfirm")))) return;
|
|
101
104
|
const body = {
|
|
102
105
|
sessionID: LS.sessionID, name, description: $("#editRoomDescription").value.trim(),
|
|
106
|
+
...(joinPolicy !== (room.joinPolicy ?? "open") ? { joinPolicy } : {}),
|
|
103
107
|
...(owner && agentsReady ? { adminSessionID: $("#editRoomAdmin").value || null } : {}),
|
|
104
108
|
...(owner && nextOwner && nextOwner !== room.ownerId ? { ownerId: nextOwner } : {}),
|
|
105
109
|
...(rosterReady ? { adminIds: checkedAdmins, successorId: $("#editRoomSuccessor").value || null } : {}),
|
|
@@ -107,7 +111,7 @@ export function initAdmin(app) {
|
|
|
107
111
|
const button = event.submitter; if (button) button.disabled = true;
|
|
108
112
|
try {
|
|
109
113
|
const updated = await app.api(`/rooms/${encodeURIComponent(room.id)}`, { method: "PATCH", body: JSON.stringify(body) });
|
|
110
|
-
const meta = { name: updated.name, description: updated.description, adminSessionID: updated.adminSessionID, ownerId: updated.ownerId, adminIds: updated.adminIds ?? [], successorId: updated.successorId ?? null, openQuestions: updated.openQuestions };
|
|
114
|
+
const meta = { name: updated.name, description: updated.description, joinPolicy: updated.joinPolicy ?? "open", adminSessionID: updated.adminSessionID, ownerId: updated.ownerId, adminIds: updated.adminIds ?? [], successorId: updated.successorId ?? null, openQuestions: updated.openQuestions };
|
|
111
115
|
const entry = app.state.rooms.get(room.id);
|
|
112
116
|
if (entry) { Object.assign(entry.room, meta); app.state.room = entry.room; }
|
|
113
117
|
const listed = app.state.availableRooms?.find((item) => item.id === room.id);
|
|
@@ -117,6 +121,8 @@ export function initAdmin(app) {
|
|
|
117
121
|
app.rerenderMessages();
|
|
118
122
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
119
123
|
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
124
|
+
if ((updated.joinPolicy ?? "open") === "approval") void app.refreshJoinRequests?.();
|
|
125
|
+
else app.clearJoinRequests?.();
|
|
120
126
|
app.cacheRoomSoon?.(room.id);
|
|
121
127
|
dialog.close();
|
|
122
128
|
} catch (error) { $("#editRoomStatus").textContent = error.message; }
|
|
@@ -119,7 +119,7 @@ export function initAnnouncements(app) {
|
|
|
119
119
|
$("#btnNewAnnouncement").addEventListener("click", () => openEditor(null));
|
|
120
120
|
$("#btnDeleteAnnouncement").addEventListener("click", async () => {
|
|
121
121
|
const id = roomId(), name = selected;
|
|
122
|
-
if (!id || !name || !
|
|
122
|
+
if (!id || !name || !(await app.confirmAction(app.t("announcementDeleteConfirm", { name })))) return;
|
|
123
123
|
const context = roomGeneration, captured = editorSnapshot();
|
|
124
124
|
try {
|
|
125
125
|
await app.api(`/rooms/${encodeURIComponent(id)}/announcements/${encodeURIComponent(name)}`, { method: "DELETE", body: JSON.stringify({ sessionID: LS.sessionID }) });
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Durable recovery for pasted attachments. Text is written synchronously so it
|
|
2
|
+
// survives the same task that creates the file; other blobs use IndexedDB.
|
|
3
|
+
const DB_NAME = "oc-chat-attachments", STORE = "pending", TEXT_PREFIX = "chat.pendingText:";
|
|
4
|
+
let dbPromise;
|
|
5
|
+
|
|
6
|
+
function database() {
|
|
7
|
+
if (dbPromise) return dbPromise;
|
|
8
|
+
dbPromise = new Promise((resolve) => {
|
|
9
|
+
try {
|
|
10
|
+
const request = indexedDB.open(DB_NAME, 1);
|
|
11
|
+
request.onupgradeneeded = () => request.result.createObjectStore(STORE, { keyPath: "key" });
|
|
12
|
+
request.onsuccess = () => resolve(request.result);
|
|
13
|
+
request.onerror = request.onblocked = () => resolve(null);
|
|
14
|
+
} catch { resolve(null); }
|
|
15
|
+
});
|
|
16
|
+
return dbPromise;
|
|
17
|
+
}
|
|
18
|
+
function done(request) {
|
|
19
|
+
return new Promise((resolve) => { request.onsuccess = () => resolve(request.result); request.onerror = () => resolve(undefined); });
|
|
20
|
+
}
|
|
21
|
+
function committed(tx) {
|
|
22
|
+
return new Promise((resolve) => { tx.oncomplete = () => resolve(true); tx.onerror = tx.onabort = () => resolve(false); });
|
|
23
|
+
}
|
|
24
|
+
async function write(record) {
|
|
25
|
+
const db = await database(); if (!db) return false;
|
|
26
|
+
try {
|
|
27
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
28
|
+
tx.objectStore(STORE).put(record);
|
|
29
|
+
return await committed(tx);
|
|
30
|
+
} catch { return false; }
|
|
31
|
+
}
|
|
32
|
+
async function remove(key) {
|
|
33
|
+
const db = await database(); if (!db) return;
|
|
34
|
+
try {
|
|
35
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
36
|
+
tx.objectStore(STORE).delete(key);
|
|
37
|
+
await committed(tx);
|
|
38
|
+
} catch { /* Best effort; stale blobs are harmless. */ }
|
|
39
|
+
}
|
|
40
|
+
function readTexts() {
|
|
41
|
+
const records = [];
|
|
42
|
+
try {
|
|
43
|
+
for (let index = 0; index < localStorage.length; index++) {
|
|
44
|
+
const key = localStorage.key(index);
|
|
45
|
+
if (!key?.startsWith(TEXT_PREFIX)) continue;
|
|
46
|
+
try { records.push(JSON.parse(localStorage.getItem(key) || "null")); } catch { /* Ignore one damaged record. */ }
|
|
47
|
+
}
|
|
48
|
+
} catch { /* Storage may be blocked. */ }
|
|
49
|
+
return records.filter((record) => record && typeof record.key === "string");
|
|
50
|
+
}
|
|
51
|
+
function writeText(record) {
|
|
52
|
+
try { localStorage.setItem(TEXT_PREFIX + record.key, JSON.stringify(record)); return true; }
|
|
53
|
+
catch { return false; }
|
|
54
|
+
}
|
|
55
|
+
function forgetText(key) {
|
|
56
|
+
try { localStorage.removeItem(TEXT_PREFIX + key); } catch { /* Storage may be blocked. */ }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function persist(item, roomId) {
|
|
60
|
+
const record = {
|
|
61
|
+
key: item.uploadID, roomId, name: item.file.name, textSource: item.textSource,
|
|
62
|
+
type: item.file.type, lastModified: item.file.lastModified, createdAt: Date.now(),
|
|
63
|
+
};
|
|
64
|
+
if (typeof item.textContent === "string" && writeText({ ...record, text: item.textContent })) {
|
|
65
|
+
item.durable = true;
|
|
66
|
+
return Promise.resolve(true);
|
|
67
|
+
}
|
|
68
|
+
item.persist = write({ ...record, blob: item.file }).then((ok) => { item.durable = ok; return ok; });
|
|
69
|
+
return item.persist;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function forget(item) {
|
|
73
|
+
forgetText(item.uploadID);
|
|
74
|
+
void Promise.resolve(item.persist).finally(() => remove(item.uploadID));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function forgetTextSource(roomId, textSource) {
|
|
78
|
+
for (const record of readTexts()) if (record.roomId === roomId && record.textSource === textSource) forgetText(record.key);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function recover(roomId, draft) {
|
|
82
|
+
const texts = readTexts().filter((record) => record.roomId === roomId);
|
|
83
|
+
const files = (await readFiles()).filter((record) => record.roomId === roomId);
|
|
84
|
+
const seen = new Set(), restored = [];
|
|
85
|
+
for (const record of [...texts, ...files]) {
|
|
86
|
+
if (seen.has(record.key)) continue;
|
|
87
|
+
seen.add(record.key);
|
|
88
|
+
if (record.textSource !== undefined && record.textSource === draft) { forgetText(record.key); void remove(record.key); continue; }
|
|
89
|
+
try {
|
|
90
|
+
const content = typeof record.text === "string" ? record.text : record.blob;
|
|
91
|
+
const file = new File([content], record.name, { type: record.type || "text/plain", lastModified: record.lastModified });
|
|
92
|
+
restored.push({ file, uploadID: record.key, textSource: record.textSource, textContent: record.text });
|
|
93
|
+
} catch { /* Skip a damaged record instead of failing the whole restore. */ }
|
|
94
|
+
}
|
|
95
|
+
return restored;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function readFiles() {
|
|
99
|
+
const db = await database(); if (!db) return [];
|
|
100
|
+
try {
|
|
101
|
+
const tx = db.transaction(STORE, "readonly");
|
|
102
|
+
const result = await done(tx.objectStore(STORE).getAll());
|
|
103
|
+
return Array.isArray(result) ? result : [];
|
|
104
|
+
} catch { return []; }
|
|
105
|
+
}
|
|
106
|
+
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
2
|
import { followsBottom } from "./message-window.js";
|
|
3
|
+
import { persist, forget, recover, forgetTextSource } from "./attachment-store.js";
|
|
3
4
|
|
|
4
5
|
const MAX_PARALLEL_UPLOADS = 2;
|
|
5
6
|
const MAX_BUFFERED_BYTES = 32 * 1024 * 1024; // Pasted files are small; larger ones stream to keep the heap bounded.
|
|
6
|
-
const TEXT_LIMIT =
|
|
7
|
+
const TEXT_LIMIT = 5000;
|
|
7
8
|
const previewTypes = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/bmp"]);
|
|
8
9
|
|
|
9
10
|
export function initAttachments(app) {
|
|
@@ -11,7 +12,9 @@ export function initAttachments(app) {
|
|
|
11
12
|
const drafts = new Map();
|
|
12
13
|
const statuses = new Map();
|
|
13
14
|
app.state.sendingRooms ||= new Set();
|
|
14
|
-
let limit = null, configRequest = null, activeUploads = 0;
|
|
15
|
+
let limit = null, configRequest = null, activeUploads = 0, eagerQueued = 0;
|
|
16
|
+
const converting = new Set(), restoring = new Set(), uploadWaiters = new Map();
|
|
17
|
+
let editorLock = null, unloadGuard = false;
|
|
15
18
|
const roomId = () => app.state.room?.id || "";
|
|
16
19
|
const filesFor = (id) => drafts.get(id) || [];
|
|
17
20
|
const markers = (items) => items.filter((item) => item.resource).map((item) => `[[resource:${item.resource.id}]]`);
|
|
@@ -23,6 +26,31 @@ export function initAttachments(app) {
|
|
|
23
26
|
const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
24
27
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
25
28
|
}
|
|
29
|
+
// Pasted files are read at paste time so a handle the browser cannot read fails
|
|
30
|
+
// as a read error, not later as a misleading network error. Eager reads only take
|
|
31
|
+
// the free upload slots; the rest read when they start uploading, so at most
|
|
32
|
+
// MAX_PARALLEL_UPLOADS buffers are held.
|
|
33
|
+
function releaseEager(item) {
|
|
34
|
+
if (item.eagerQueued) { item.eagerQueued = false; eagerQueued--; }
|
|
35
|
+
}
|
|
36
|
+
function releaseBuffer(item) {
|
|
37
|
+
item.buffer = null;
|
|
38
|
+
if (item.readPending) item.released = true;
|
|
39
|
+
else { item.read = null; releaseEager(item); }
|
|
40
|
+
}
|
|
41
|
+
function startRead(item, eager = false) {
|
|
42
|
+
if (!item.pasted || item.file.size > MAX_BUFFERED_BYTES) return null;
|
|
43
|
+
if (eager) {
|
|
44
|
+
if (activeUploads + eagerQueued >= MAX_PARALLEL_UPLOADS) return null;
|
|
45
|
+
item.eagerQueued = true; eagerQueued++;
|
|
46
|
+
}
|
|
47
|
+
const read = Promise.resolve().then(() => item.file.arrayBuffer());
|
|
48
|
+
item.read = read; item.readPending = true; item.released = false;
|
|
49
|
+
// Hold the eager slot until the read settles, even if the item is removed meanwhile.
|
|
50
|
+
const settle = () => { item.readPending = false; if (item.released) { item.read = null; releaseEager(item); } };
|
|
51
|
+
void read.then(settle, settle);
|
|
52
|
+
return read;
|
|
53
|
+
}
|
|
26
54
|
const textFor = (id, caption) => {
|
|
27
55
|
const parts = [String(caption || "").trim(), ...markers(filesFor(id))].filter(Boolean);
|
|
28
56
|
return { text: parts.join("\n\n"), ids: filesFor(id).filter((item) => item.resource).map((item) => item.resource.id) };
|
|
@@ -49,8 +77,67 @@ export function initAttachments(app) {
|
|
|
49
77
|
});
|
|
50
78
|
}
|
|
51
79
|
function prepareMessage(id, caption) {
|
|
52
|
-
const items = filesFor(id), composed = textFor(id, caption);
|
|
53
|
-
|
|
80
|
+
const items = filesFor(id), composed = textFor(id, caption), body = String(caption || "");
|
|
81
|
+
const overLimit = composed.text.length > TEXT_LIMIT, question = Boolean(app.replyTargetFor?.(id)?.isQuestion);
|
|
82
|
+
// A prior attempt can already carry this text; reusing it avoids a second file.
|
|
83
|
+
const conversion = body.length > TEXT_LIMIT ? items.find((item) => item.textSource === body) : undefined;
|
|
84
|
+
const markerText = textFor(id, "").text, effective = conversion ? markerText : composed.text;
|
|
85
|
+
// Converting moves the draft into a file; the message then carries only resource markers.
|
|
86
|
+
const canConvert = overLimit && body.length > TEXT_LIMIT && markerText.length <= TEXT_LIMIT && !question && items.every((item) => item.status !== "failed");
|
|
87
|
+
return { ...composed, overLimit, conversion, canConvert, ready: Boolean(composed.text) && effective.length <= TEXT_LIMIT && items.every((item) => item.status === "uploaded") };
|
|
88
|
+
}
|
|
89
|
+
const pastedTextName = () => `pasted-text-${new Date().toISOString().slice(0, 19).replace(/\D/g, "")}.txt`;
|
|
90
|
+
// Mentions are stored as editor tokens; the file gets the visible text instead.
|
|
91
|
+
const plainText = (text) => String(text).replace(/<at>@([^<]+)<\/at>/g, "@$1");
|
|
92
|
+
const textFile = (text) => new File([text], pastedTextName(), { type: "text/plain" });
|
|
93
|
+
function persistItem(item, id) {
|
|
94
|
+
if (!item.pasted) return;
|
|
95
|
+
void persist(item, id).then((ok) => { if (!ok) persistenceFailed(id); });
|
|
96
|
+
}
|
|
97
|
+
function persistenceFailed(id) {
|
|
98
|
+
updateDurability();
|
|
99
|
+
setStatus("attachmentNotPersisted", true, id);
|
|
100
|
+
}
|
|
101
|
+
function warnUnload(event) { event.preventDefault(); event.returnValue = ""; }
|
|
102
|
+
function updateDurability() {
|
|
103
|
+
const unsafe = [...drafts.values()].flat().some((item) => item.durable === false);
|
|
104
|
+
if (unsafe && !unloadGuard) { window.onbeforeunload = warnUnload; unloadGuard = true; }
|
|
105
|
+
else if (!unsafe && unloadGuard) { window.onbeforeunload = null; unloadGuard = false; }
|
|
106
|
+
const id = roomId(), hint = $("#attachmentVolatile"), volatile = filesFor(id).some((item) => item.durable === false);
|
|
107
|
+
hint.textContent = app.t(volatile ? "attachmentNotPersisted" : "attachmentVolatile");
|
|
108
|
+
hint.classList.toggle("danger-text", volatile);
|
|
109
|
+
}
|
|
110
|
+
async function restoreRoom(id) {
|
|
111
|
+
if (restoring.has(id)) return;
|
|
112
|
+
restoring.add(id);
|
|
113
|
+
try {
|
|
114
|
+
const restored = await recover(id, app.state.drafts.get(id) || "");
|
|
115
|
+
const existing = filesFor(id), keys = new Set(existing.map((item) => item.uploadID)), items = [...existing];
|
|
116
|
+
for (const record of restored) {
|
|
117
|
+
if (keys.has(record.uploadID)) continue;
|
|
118
|
+
keys.add(record.uploadID);
|
|
119
|
+
items.push({ ...record, pasted: true, status: "queued", buffer: undefined, read: undefined, retried: false, loaded: 0, percent: 0, cancelled: false, durable: true });
|
|
120
|
+
}
|
|
121
|
+
if (items.length === existing.length) return;
|
|
122
|
+
drafts.set(id, items);
|
|
123
|
+
if (roomId() === id) { render(); pump(); }
|
|
124
|
+
} finally {
|
|
125
|
+
restoring.delete(id);
|
|
126
|
+
if (roomId() === id) app.updateSendState();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function lockComposer() {
|
|
130
|
+
if (editorLock) return;
|
|
131
|
+
editorLock = { editable: input.contentEditable, disabled: input.getAttribute("aria-disabled"), busy: input.getAttribute("aria-busy"), selection: input.getSelectionOffsets?.() || null };
|
|
132
|
+
input.contentEditable = "false"; input.setAttribute("aria-disabled", "true"); input.setAttribute("aria-busy", "true");
|
|
133
|
+
}
|
|
134
|
+
function unlockComposer() {
|
|
135
|
+
if (!editorLock) return;
|
|
136
|
+
input.contentEditable = "true";
|
|
137
|
+
input.setAttribute("aria-disabled", editorLock.disabled ?? "false");
|
|
138
|
+
if (editorLock.busy === null) input.removeAttribute("aria-busy"); else input.setAttribute("aria-busy", editorLock.busy);
|
|
139
|
+
const selection = editorLock.selection; editorLock = null;
|
|
140
|
+
if (selection) input.setSelectionRange?.(selection[0], selection[1]);
|
|
54
141
|
}
|
|
55
142
|
app.prepareMessage = prepareMessage;
|
|
56
143
|
const baseDraftCount = app.updateDraftCount;
|
|
@@ -62,11 +149,11 @@ export function initAttachments(app) {
|
|
|
62
149
|
};
|
|
63
150
|
app.updateSendState = () => {
|
|
64
151
|
const id = roomId(), message = id && prepareMessage(id, input.value);
|
|
65
|
-
$("#btnSend").disabled = !id || !message?.ready || app.state.sendingRooms.has(id);
|
|
152
|
+
$("#btnSend").disabled = !id || !(message?.ready || message?.canConvert) || app.state.sendingRooms.has(id) || converting.has(id) || restoring.has(id);
|
|
66
153
|
};
|
|
67
154
|
app.completeAttachments = (id, resourceIDs) => {
|
|
68
155
|
const used = new Set(resourceIDs), items = filesFor(id), removed = items.filter((item) => used.has(item.resource?.id));
|
|
69
|
-
for (const item of removed) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
|
|
156
|
+
for (const item of removed) { forget(item); if (item.previewUrl) URL.revokeObjectURL(item.previewUrl); }
|
|
70
157
|
const remaining = items.filter((item) => !used.has(item.resource?.id));
|
|
71
158
|
if (remaining.length) drafts.set(id, remaining); else { drafts.delete(id); statuses.delete(id); }
|
|
72
159
|
if (roomId() === id) render();
|
|
@@ -87,6 +174,7 @@ export function initAttachments(app) {
|
|
|
87
174
|
});
|
|
88
175
|
const status = statuses.get(id); $("#attachmentStatus").textContent = status?.key ? app.t(status.key, status.values) : "";
|
|
89
176
|
if (status?.key) tray.hidden = false;
|
|
177
|
+
updateDurability();
|
|
90
178
|
}
|
|
91
179
|
function render() {
|
|
92
180
|
preserveLayout(() => {
|
|
@@ -95,6 +183,7 @@ export function initAttachments(app) {
|
|
|
95
183
|
$("#attachmentStatus").textContent = savedStatus?.key ? app.t(savedStatus.key, savedStatus.values) : ""; $("#attachmentStatus").classList.toggle("danger-text", Boolean(savedStatus?.error));
|
|
96
184
|
list.replaceChildren();
|
|
97
185
|
items.forEach((item, index) => { const row = renderItem(item); row.dataset.index = String(index); list.append(row); });
|
|
186
|
+
updateDurability();
|
|
98
187
|
app.updateDraftCount(); app.updateSendState();
|
|
99
188
|
});
|
|
100
189
|
}
|
|
@@ -102,7 +191,7 @@ export function initAttachments(app) {
|
|
|
102
191
|
function renderItem(item) {
|
|
103
192
|
const row = document.createElement("li"), preview = document.createElement("span"), info = document.createElement("div"), name = document.createElement("p"), detail = document.createElement("p"), progress = document.createElement("progress"), actions = document.createElement("div");
|
|
104
193
|
row.className = "attachment-item"; preview.className = "attachment-preview";
|
|
105
|
-
if (previewTypes.has(item.file.type)) {
|
|
194
|
+
if (previewTypes.has(item.file.type) && item.errorKey !== "fileUnreadable") {
|
|
106
195
|
item.previewUrl ||= URL.createObjectURL(item.file);
|
|
107
196
|
const image = document.createElement("img"); image.src = item.previewUrl; image.alt = ""; preview.append(image);
|
|
108
197
|
} else preview.textContent = item.file.name.split(".").at(-1)?.slice(0, 4).toUpperCase() || "FILE";
|
|
@@ -120,8 +209,9 @@ export function initAttachments(app) {
|
|
|
120
209
|
function action(kind, label) {
|
|
121
210
|
const button = document.createElement("button"); button.type = "button"; button.dataset.uploadAction = kind; button.textContent = label; button.setAttribute("aria-label", label); return button;
|
|
122
211
|
}
|
|
123
|
-
function removeItem(id, item) {
|
|
124
|
-
item.cancelled = true; item.xhr?.abort();
|
|
212
|
+
function removeItem(id, item, purge = true) {
|
|
213
|
+
item.cancelled = true; item.xhr?.abort(); releaseBuffer(item);
|
|
214
|
+
if (purge) forget(item);
|
|
125
215
|
if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
|
|
126
216
|
const remaining = filesFor(id).filter((entry) => entry !== item);
|
|
127
217
|
if (remaining.length) {
|
|
@@ -129,10 +219,12 @@ export function initAttachments(app) {
|
|
|
129
219
|
if (statuses.get(id)?.error && !remaining.some((entry) => entry.status === "failed")) statuses.delete(id);
|
|
130
220
|
} else { drafts.delete(id); statuses.delete(id); }
|
|
131
221
|
if (roomId() === id) render();
|
|
222
|
+
settleUploads(id);
|
|
132
223
|
}
|
|
133
224
|
function clearRoom(id) {
|
|
134
|
-
for (const item of [...filesFor(id)]) removeItem(id, item);
|
|
225
|
+
for (const item of [...filesFor(id)]) removeItem(id, item, false);
|
|
135
226
|
drafts.delete(id); statuses.delete(id);
|
|
227
|
+
settleUploads(id);
|
|
136
228
|
}
|
|
137
229
|
app.disposeRoomAttachments = clearRoom;
|
|
138
230
|
function getLimit(refresh = false) {
|
|
@@ -152,7 +244,7 @@ export function initAttachments(app) {
|
|
|
152
244
|
while (activeUploads < MAX_PARALLEL_UPLOADS) {
|
|
153
245
|
const next = [...drafts].flatMap(([id, items]) => items.map((item) => ({ id, item }))).find(({ item }) => item.status === "queued");
|
|
154
246
|
if (!next) return;
|
|
155
|
-
activeUploads++; next.item.status = "uploading"; next.item.percent = 0;
|
|
247
|
+
activeUploads++; releaseEager(next.item); next.item.status = "uploading"; next.item.percent = 0;
|
|
156
248
|
if (roomId() === next.id) render();
|
|
157
249
|
void uploadItem(next.id, next.item);
|
|
158
250
|
}
|
|
@@ -163,16 +255,29 @@ export function initAttachments(app) {
|
|
|
163
255
|
try { max = await getLimit(item.refreshLimit); } catch {}
|
|
164
256
|
item.refreshLimit = false;
|
|
165
257
|
if (item.cancelled) return;
|
|
166
|
-
if (max !== null && item.file.size > max) { item.errorKey = "fileTooLarge"; item.status = "failed"; if (roomId() === id) setStatus(item.errorKey, true, id); return; }
|
|
167
|
-
if (item.pasted && item.
|
|
168
|
-
|
|
258
|
+
if (max !== null && item.file.size > max) { releaseBuffer(item); item.errorKey = "fileTooLarge"; item.status = "failed"; if (roomId() === id) setStatus(item.errorKey, true, id); return; }
|
|
259
|
+
if (item.pasted && item.file.size <= MAX_BUFFERED_BYTES) {
|
|
260
|
+
try {
|
|
261
|
+
const buffer = await (item.read ?? startRead(item));
|
|
262
|
+
if (item.cancelled) return;
|
|
263
|
+
item.buffer = buffer;
|
|
264
|
+
} catch {
|
|
265
|
+
releaseBuffer(item);
|
|
266
|
+
if (item.cancelled) return;
|
|
267
|
+
item.errorKey = "fileUnreadable"; item.errorValues = null; item.status = "failed";
|
|
268
|
+
if (roomId() === id) setStatus("fileUnreadable", true, id);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
169
272
|
item.resource = await sendUpload(id, item);
|
|
170
273
|
if (item.cancelled) return;
|
|
171
|
-
item.status = "uploaded"; item.loaded = item.file.size; item.percent = 100; item
|
|
172
|
-
if (roomId() === id && filesFor(id).every((entry) => entry.status === "uploaded")) setStatus("uploadReady");
|
|
274
|
+
item.status = "uploaded"; item.loaded = item.file.size; item.percent = 100; releaseBuffer(item);
|
|
275
|
+
if (roomId() === id && filesFor(id).every((entry) => entry.status === "uploaded")) setStatus(filesFor(id).some((entry) => entry.durable === false) ? "attachmentNotPersisted" : "uploadReady");
|
|
173
276
|
} catch (error) {
|
|
277
|
+
releaseBuffer(item);
|
|
174
278
|
if (item.cancelled) return;
|
|
175
279
|
if (error.status === 413) { limit = null; item.errorKey = "fileTooLarge"; }
|
|
280
|
+
else if (error.unreadable) item.errorKey = "fileUnreadable";
|
|
176
281
|
else { item.errorKey = "uploadFailed"; item.errorValues = { reason: error.status ? `HTTP ${error.status}` : error.timeout ? "timeout" : error.network ? "network" : error.message }; }
|
|
177
282
|
item.status = "failed";
|
|
178
283
|
if (roomId() === id) setStatus(item.errorKey, true, id, item.errorValues || {});
|
|
@@ -180,6 +285,7 @@ export function initAttachments(app) {
|
|
|
180
285
|
activeUploads--;
|
|
181
286
|
if (roomId() === id) render();
|
|
182
287
|
pump();
|
|
288
|
+
settleUploads(id);
|
|
183
289
|
}
|
|
184
290
|
}
|
|
185
291
|
// One fallback after a network failure: a lost response is recovered by ID, and a
|
|
@@ -192,7 +298,10 @@ export function initAttachments(app) {
|
|
|
192
298
|
const existing = await findUploaded(id, item);
|
|
193
299
|
if (item.cancelled) throw error;
|
|
194
300
|
if (existing) return existing;
|
|
195
|
-
if (item.buffer === undefined && item.file.size <= MAX_BUFFERED_BYTES)
|
|
301
|
+
if (item.buffer === undefined && item.file.size <= MAX_BUFFERED_BYTES) {
|
|
302
|
+
try { item.buffer = await item.file.arrayBuffer(); }
|
|
303
|
+
catch { if (item.cancelled) throw error; throw Object.assign(new Error("Upload unreadable"), { unreadable: true }); }
|
|
304
|
+
}
|
|
196
305
|
if (item.cancelled || !item.buffer) throw error;
|
|
197
306
|
return upload(id, item);
|
|
198
307
|
}
|
|
@@ -239,17 +348,79 @@ export function initAttachments(app) {
|
|
|
239
348
|
xhr.send(item.buffer ?? item.file);
|
|
240
349
|
});
|
|
241
350
|
}
|
|
242
|
-
function addFiles(files, pasted = false) {
|
|
351
|
+
function addFiles(files, pasted = false, meta = {}) {
|
|
243
352
|
const id = roomId(); if (!id) return;
|
|
244
353
|
const accepted = [...files].filter((file) => file instanceof File);
|
|
245
354
|
if (!accepted.length) return;
|
|
246
355
|
const items = filesFor(id);
|
|
247
|
-
|
|
356
|
+
accepted.forEach((file, index) => {
|
|
357
|
+
const item = { file, uploadID: newUploadID(), pasted, buffer: undefined, read: undefined, retried: false, status: "queued", loaded: 0, percent: 0, cancelled: false, ...(index ? {} : meta) };
|
|
358
|
+
items.push(item);
|
|
359
|
+
if (pasted) { startRead(item, true); persistItem(item, id); }
|
|
360
|
+
});
|
|
248
361
|
drafts.set(id, items); setStatus(""); render(); pump();
|
|
249
362
|
}
|
|
363
|
+
function settleUploads(id) {
|
|
364
|
+
const waiters = uploadWaiters.get(id);
|
|
365
|
+
if (!waiters) return;
|
|
366
|
+
const items = filesFor(id);
|
|
367
|
+
if (items.some((item) => item.status === "queued" || item.status === "uploading")) return;
|
|
368
|
+
uploadWaiters.delete(id);
|
|
369
|
+
const uploaded = items.length > 0 && items.every((item) => item.status === "uploaded");
|
|
370
|
+
for (const resolve of waiters) resolve(uploaded);
|
|
371
|
+
}
|
|
372
|
+
function waitForUploads(id) {
|
|
373
|
+
return new Promise((resolve) => {
|
|
374
|
+
uploadWaiters.set(id, [...(uploadWaiters.get(id) || []), resolve]);
|
|
375
|
+
settleUploads(id);
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
const baseSend = app.send;
|
|
379
|
+
app.send = async () => {
|
|
380
|
+
const id = roomId();
|
|
381
|
+
if (!id || converting.has(id) || restoring.has(id) || app.state.sendingRooms.has(id)) return false;
|
|
382
|
+
const message = prepareMessage(id, input.value);
|
|
383
|
+
if (!message.canConvert) return baseSend();
|
|
384
|
+
const requested = input.value, revision = app.state.draftRevision.get(id) || 0, replyId = app.replyTargetFor?.(id)?.id;
|
|
385
|
+
converting.add(id);
|
|
386
|
+
lockComposer();
|
|
387
|
+
app.saveDraft(id, input.draftValue);
|
|
388
|
+
let item = message.conversion;
|
|
389
|
+
try {
|
|
390
|
+
if (!item) {
|
|
391
|
+
const content = plainText(requested), attachment = textFile(content);
|
|
392
|
+
addFiles([attachment], true, { textSource: requested, textContent: content });
|
|
393
|
+
item = filesFor(id).find((entry) => entry.file === attachment);
|
|
394
|
+
}
|
|
395
|
+
setStatus("sendAsFile", false, id, { count: requested.length });
|
|
396
|
+
if (!(await waitForUploads(id))) {
|
|
397
|
+
if (roomId() === id) {
|
|
398
|
+
if (item?.status === "failed") setStatus("sendAsFileFailed", true, id);
|
|
399
|
+
else if (!item) setStatus("");
|
|
400
|
+
}
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
if (roomId() !== id) return false;
|
|
404
|
+
const changed = (app.state.draftRevision.get(id) || 0) !== revision || app.replyTargetFor?.(id)?.id !== replyId;
|
|
405
|
+
if (changed) { setStatus("uploadReady"); return false; }
|
|
406
|
+
// The composer stayed locked, so clearing it now cannot drop text typed during the upload.
|
|
407
|
+
unlockComposer();
|
|
408
|
+
input.value = "";
|
|
409
|
+
app.clearDraft(id);
|
|
410
|
+
const sent = await baseSend();
|
|
411
|
+
if (sent) forgetTextSource(id, requested);
|
|
412
|
+
return sent;
|
|
413
|
+
} finally {
|
|
414
|
+
converting.delete(id);
|
|
415
|
+
if (roomId() === id) { unlockComposer(); app.updateDraftCount(); app.updateSendState(); }
|
|
416
|
+
else editorLock = null;
|
|
417
|
+
}
|
|
418
|
+
};
|
|
250
419
|
function retryItem(item) {
|
|
251
420
|
if (item.status !== "failed") return;
|
|
421
|
+
if (item.errorKey === "fileUnreadable") item.read = null;
|
|
252
422
|
item.refreshLimit = item.errorKey === "fileTooLarge"; item.status = "queued"; item.errorKey = ""; item.errorValues = null; item.loaded = 0; item.percent = 0; item.retried = false;
|
|
423
|
+
if (item.pasted && !item.readPending) startRead(item, true);
|
|
253
424
|
if (roomId()) setStatus(""); render(); pump();
|
|
254
425
|
}
|
|
255
426
|
$("#btnAddAttachments").addEventListener("click", () => picker.click());
|
|
@@ -269,15 +440,24 @@ export function initAttachments(app) {
|
|
|
269
440
|
chatView.addEventListener("dragover", (event) => { if (!hasFiles(event)) return; event.preventDefault(); event.dataTransfer.dropEffect = "copy"; showDrop(); });
|
|
270
441
|
chatView.addEventListener("dragleave", (event) => { if (hasFiles(event) && !chatView.contains(event.relatedTarget)) clearDrop(); });
|
|
271
442
|
chatView.addEventListener("drop", (event) => { if (!hasFiles(event)) return; event.preventDefault(); clearDrop(); addFiles(event.dataTransfer.files); });
|
|
443
|
+
// Capture before the editor's paste handler: an oversized paste never enters the DOM.
|
|
272
444
|
input.addEventListener("paste", (event) => {
|
|
445
|
+
const text = event.clipboardData?.getData("text/plain") || "";
|
|
446
|
+
if (text.length > TEXT_LIMIT && roomId() && input.contentEditable === "true") {
|
|
447
|
+
event.preventDefault();
|
|
448
|
+
const files = Array.from(event.clipboardData?.items || []).filter((item) => item.kind === "file").map((item) => item.getAsFile()).filter(Boolean);
|
|
449
|
+
addFiles([textFile(text), ...files], true, { textSource: text, textContent: text });
|
|
450
|
+
setStatus("pasteAsFile", false, roomId(), { count: text.length });
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
273
453
|
const images = Array.from(event.clipboardData?.items || []).filter((item) => item.kind === "file" && item.type.startsWith("image/")).map((item) => item.getAsFile()).filter(Boolean);
|
|
274
454
|
if (!images.length) return;
|
|
275
455
|
if (!event.clipboardData.getData("text/plain")) event.preventDefault();
|
|
276
456
|
addFiles(images, true);
|
|
277
|
-
});
|
|
457
|
+
}, true);
|
|
278
458
|
document.addEventListener("chat-room-activated", (event) => {
|
|
279
459
|
render(); const id = event.detail; $("#btnAddAttachments").disabled = !id;
|
|
280
|
-
void getLimit().catch(() => {});
|
|
460
|
+
void restoreRoom(id); void getLimit().catch(() => {});
|
|
281
461
|
});
|
|
282
462
|
render();
|
|
283
463
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// One shared confirmation dialog replaces the browser's native confirmation
|
|
2
|
+
// window, so a destructive action stays inside the page.
|
|
3
|
+
export function initConfirmDialog(app) {
|
|
4
|
+
const dialog = app.$("#confirmDialog"), message = app.$("#confirmMessage");
|
|
5
|
+
const accept = app.$("#btnAcceptConfirm"), cancel = app.$("#btnCancelConfirm");
|
|
6
|
+
let pending = null;
|
|
7
|
+
const settle = (value) => { const resolve = pending; pending = null; resolve?.(value); };
|
|
8
|
+
function close(value) { settle(value); dialog.close(); }
|
|
9
|
+
|
|
10
|
+
app.confirmAction = (text) => {
|
|
11
|
+
// One dialog at a time: a newer request dismisses the open one as cancelled.
|
|
12
|
+
if (dialog.open) close(false);
|
|
13
|
+
message.textContent = text;
|
|
14
|
+
dialog.showModal();
|
|
15
|
+
cancel.focus();
|
|
16
|
+
return new Promise((resolve) => { pending = resolve; });
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
accept.addEventListener("click", () => close(true));
|
|
20
|
+
cancel.addEventListener("click", () => close(false));
|
|
21
|
+
dialog.addEventListener("cancel", (event) => { event.preventDefault(); close(false); });
|
|
22
|
+
dialog.addEventListener("click", (event) => { if (event.target === dialog) close(false); });
|
|
23
|
+
dialog.addEventListener("close", () => {
|
|
24
|
+
// A close from outside the buttons still settles the promise; a re-open in the
|
|
25
|
+
// same task leaves the dialog open, so the stale event must not clear it.
|
|
26
|
+
if (!dialog.open) { settle(false); message.textContent = ""; }
|
|
27
|
+
});
|
|
28
|
+
}
|