sessionyard 0.7.0__py3-none-any.whl

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 (62) hide show
  1. agent_chat/001_core.sql +172 -0
  2. agent_chat/002_coordination.sql +63 -0
  3. agent_chat/003_harness_admission.sql +10 -0
  4. agent_chat/004_session_titles.sql +3 -0
  5. agent_chat/005_viewer.sql +9 -0
  6. agent_chat/006_quotas.sql +6 -0
  7. agent_chat/007_sender_receipts.sql +20 -0
  8. agent_chat/008_direct_threads.sql +49 -0
  9. agent_chat/009_pm_mark.sql +23 -0
  10. agent_chat/010_quota_backfill.sql +12 -0
  11. agent_chat/011_roles_and_work.sql +31 -0
  12. agent_chat/__init__.py +1 -0
  13. agent_chat/adapter.py +414 -0
  14. agent_chat/admin.py +524 -0
  15. agent_chat/api.py +641 -0
  16. agent_chat/auth.py +226 -0
  17. agent_chat/browser.py +118 -0
  18. agent_chat/browser_verify.py +487 -0
  19. agent_chat/browser_verify_artifacts.py +280 -0
  20. agent_chat/browser_verify_checks.py +236 -0
  21. agent_chat/browser_verify_run.py +523 -0
  22. agent_chat/cli.py +532 -0
  23. agent_chat/client.py +272 -0
  24. agent_chat/deliveries.py +555 -0
  25. agent_chat/events.py +48 -0
  26. agent_chat/feed.py +193 -0
  27. agent_chat/http_boundary.py +154 -0
  28. agent_chat/instance_client.py +349 -0
  29. agent_chat/instance_file.py +207 -0
  30. agent_chat/instance_worker.py +326 -0
  31. agent_chat/mcp/__init__.py +5 -0
  32. agent_chat/mcp/__main__.py +39 -0
  33. agent_chat/mcp/app.py +183 -0
  34. agent_chat/mcp/auth.py +67 -0
  35. agent_chat/mcp/config.py +55 -0
  36. agent_chat/mcp/tools.py +295 -0
  37. agent_chat/metrics.py +60 -0
  38. agent_chat/models.py +430 -0
  39. agent_chat/openapi.py +322 -0
  40. agent_chat/producer.py +208 -0
  41. agent_chat/protocol.py +71 -0
  42. agent_chat/publication.py +252 -0
  43. agent_chat/receipts.py +225 -0
  44. agent_chat/retention.py +154 -0
  45. agent_chat/roles.py +153 -0
  46. agent_chat/rooms.py +179 -0
  47. agent_chat/sessions.py +340 -0
  48. agent_chat/skills/agent-chat/SKILL.md +64 -0
  49. agent_chat/state.py +144 -0
  50. agent_chat/storage.py +110 -0
  51. agent_chat/threads.py +50 -0
  52. agent_chat/web/Manrope-OFL.txt +93 -0
  53. agent_chat/web/Manrope-Variable.ttf +0 -0
  54. agent_chat/web/chat.css +936 -0
  55. agent_chat/web/chat.js +1922 -0
  56. agent_chat/web/i18n.js +340 -0
  57. agent_chat/web/index.html +264 -0
  58. sessionyard-0.7.0.dist-info/METADATA +314 -0
  59. sessionyard-0.7.0.dist-info/RECORD +62 -0
  60. sessionyard-0.7.0.dist-info/WHEEL +4 -0
  61. sessionyard-0.7.0.dist-info/entry_points.txt +3 -0
  62. sessionyard-0.7.0.dist-info/licenses/LICENSE +661 -0
agent_chat/web/chat.js ADDED
@@ -0,0 +1,1922 @@
1
+ "use strict";
2
+
3
+ const t = window.AgentChatI18n.t;
4
+ const UI_LOCALE = window.AgentChatI18n.locale;
5
+
6
+ // Operator publications use an immutable in-memory attempt. No ACK or automatic retry.
7
+ (() => {
8
+ const el = (id) => document.getElementById(id);
9
+ let csrf = null;
10
+ let principal = null;
11
+ let access = null;
12
+ const uuid = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value);
13
+
14
+ function acceptSession(data) {
15
+ if (!uuid(data.principal_id) || typeof data.csrf_token !== "string" || !/^[0-9a-f]{64}$/.test(data.csrf_token)
16
+ || !["operator", "viewer"].includes(data.access)) {
17
+ const error = new Error("INVALID_SESSION");
18
+ error.status = 401;
19
+ throw error;
20
+ }
21
+ if (principal !== data.principal_id || access !== data.access) scopeEpoch += 1;
22
+ principal = data.principal_id;
23
+ csrf = data.csrf_token;
24
+ access = data.access;
25
+ el("viewer").dataset.access = access;
26
+ el("read-only-indicator").hidden = access !== "viewer";
27
+ }
28
+ let generation = 0;
29
+ // Bumped only when the authenticated scope really changes (login/logout, room switch, SSE scope
30
+ // invalidation), never by a harmless live-refresh cycle. Sessions reads and their deferred request
31
+ // fence on this, so a refresh restart cannot discard work the operator already asked for.
32
+ let scopeEpoch = 0;
33
+ let requestController = new AbortController();
34
+ // History pages hold the newest messages below a cursor; a null page start is the newest page.
35
+ let historyCursor = null;
36
+ let historyPageStart = null;
37
+ let participantCursor = null;
38
+ let participantPageStart = null;
39
+ // True while the loaded roster page is not the whole room: a next page exists, or this page is not the first. The
40
+ // server sends a page and a cursor, never a room-wide total, so the roster counts describe the loaded page only.
41
+ let rosterPartial = false;
42
+ let selectedRoom = "";
43
+ let selectedThread = null;
44
+ let selectedRef = null;
45
+ let lastMessages = [];
46
+ const participantNames = new Map();
47
+ // Which roster rows, and whether the PM line, have their details open. A reload rebuilds both from the server's
48
+ // answer, so the reader's choice lives here and not in the nodes.
49
+ const openRows = new Set();
50
+ let pmDetailsOpen = false;
51
+ // Bumped whenever the room view is dropped, so a late expiry timer or state read never paints another room.
52
+ let stateEpoch = 0;
53
+ let stateTimer = null;
54
+ let composerReady = false;
55
+ let controlsReady = false;
56
+ const targets = new Map();
57
+ let replyTarget = null;
58
+ let pending = null;
59
+ let sending = false;
60
+ let controlRequest = null;
61
+ let live = null;
62
+ let view = "chat";
63
+ // The narrow layout scrolls the document and hiding the tall conversation clamps that position, so the
64
+ // reading position is saved when the conversation is hidden and restored once it is visible again.
65
+ let savedChatScroll = null;
66
+ let sessionsPage = null;
67
+ let sessionsLoading = false;
68
+ let sessionsLoadingMore = false;
69
+ // A first visit to Sesje can arrive while a write or a live refresh is in flight; remember the request
70
+ // and satisfy it when that operation settles instead of leaving the view empty.
71
+ let sessionsDeferred = null;
72
+ // A flush asked for while a sessions read is already in flight runs when that read settles.
73
+ let sessionsFlushPending = false;
74
+ // The one value this page keeps in browser storage: a per-browser request to start live events after a load or a
75
+ // login. It carries no credential, draft or scope, and grants nothing; every start still revalidates the binding.
76
+ const LIVE_KEY = "agent-chat.live";
77
+ // The page reads the choice from storage once, when it loads, and acts on this value from then on: only the
78
+ // switch changes it. A refresh, a logout and a new login keep it whether or not storage works, and a change that
79
+ // another tab stores is adopted at the next load, never in the middle of this page.
80
+ let liveWanted = (() => {
81
+ try { return window.localStorage.getItem(LIVE_KEY) === "1"; } catch { return false; }
82
+ })();
83
+ function rememberLive(on) {
84
+ liveWanted = on;
85
+ try {
86
+ if (on) window.localStorage.setItem(LIVE_KEY, "1");
87
+ else window.localStorage.removeItem(LIVE_KEY);
88
+ } catch { /* Storage may be blocked; the choice then lasts for this page only. */ }
89
+ }
90
+ let reads = 0;
91
+ let historyEventCursor = "0";
92
+ let historyFloor = "0";
93
+ const cursorValid = (value) => typeof value === "string" && /^(0|[1-9][0-9]{0,18})$/.test(value) && BigInt(value) <= 9223372036854775807n;
94
+ // The server reads any `before` cursor above the event clock as "now", i.e. the newest page.
95
+ const NEWEST = "9223372036854775807";
96
+ // The same grammar the server enforces on a thread key; the server stays the authority.
97
+ const REF_KEY = /^(pr:[A-Za-z0-9_.-]{1,40}\/[A-Za-z0-9_.-]{1,80}#[1-9][0-9]{0,9}|lane:[A-Za-z0-9_.\/-]{1,80}::[A-Za-z0-9-]{1,40}|resource:[a-z0-9][a-z0-9-]{0,62}:[a-z0-9][a-z0-9-]{0,62})$/;
98
+ const KIND_LABELS = {
99
+ message: t("Wiadomość"), status: t("Status"), question: t("Pytanie"), consultation: t("Konsultacja"), reply: t("Odpowiedź"),
100
+ heads_up: t("Uwaga"), blocked_on: t("Zablokowany przez"), decision_needed: t("Potrzebna decyzja"), intent: t("Zamiar"),
101
+ };
102
+ const QUESTION_KINDS = new Set(["question", "consultation"]);
103
+ // Safe, allowlisted server refusals. An unknown code keeps the generic fallback.
104
+ const REFUSAL_TEXT = {
105
+ ROLE_CONFLICT: t("Ta sesja ma już inną rolę w tym pokoju. Zdejmij obecną rolę i spróbuj ponownie."),
106
+ ROOM_CONFLICT: t("Nie można utworzyć pokoju o tym identyfikatorze."),
107
+ INVALID_REQUEST: t("Serwer odrzucił żądanie. Sprawdź wybrane wartości."),
108
+ INVALID_RECIPIENT: t("Wybrany odbiorca nie jest już dostępny w tym pokoju."),
109
+ MESSAGE_EXPIRED: t("Wiadomość wygasła; nie można wykonać tej operacji."),
110
+ STALE_INSTANCE: t("Ta sesja nie jest już aktywna. Odśwież widok."),
111
+ ROOM_FORBIDDEN: t("Brak dostępu do tego pokoju."),
112
+ SESSION_FORBIDDEN: t("Brak uprawnień do tej zmiany."),
113
+ NOT_FOUND: t("Nie znaleziono obiektu. Odśwież widok."),
114
+ };
115
+ // Only a refusal that cannot mask a revoked scope may keep the loaded view.
116
+ // NOT_FOUND can deliberately mask ROOM_FORBIDDEN for a message-derived room.
117
+ const PRESERVE_ON_REFUSAL = new Set(["ROLE_CONFLICT"]);
118
+ function refusal(error) {
119
+ const detail = REFUSAL_TEXT[error.code];
120
+ return detail ? `${error.code}: ${t(detail)}` : "";
121
+ }
122
+ const TIME_FORMAT = new Intl.DateTimeFormat(UI_LOCALE, { dateStyle: "short", timeStyle: "short" });
123
+
124
+ // Secondary panels are disclosures where they would crowd the conversation: below 821 px the roster and the resource
125
+ // observations stack under the app bar and start collapsed.
126
+ for (const [id, query] of [["participants-details", "(max-width: 820px)"], ["room-state", "(max-width: 820px)"]]) {
127
+ const panel = el(id);
128
+ const media = window.matchMedia(query);
129
+ const sync = () => { if (panel) panel.open = !media.matches; };
130
+ sync();
131
+ media.addEventListener("change", sync);
132
+ }
133
+
134
+ // Writes block the draft fields; a live refresh blocks navigation and controls but never typing.
135
+ function writesBusy() { return pending !== null || sending || controlRequest !== null; }
136
+ function busy() { return writesBusy() || live?.loading === true; }
137
+ // True while `held` is no longer the owner that started the work, or the view moved on.
138
+ function stale(held, expected, current) { return held !== expected || current !== generation; }
139
+
140
+ function composerDraft() { return el("body").value || el("ref-key").value || targets.size || replyTarget; }
141
+
142
+ function syncComposer() {
143
+ const writable = access === "operator";
144
+ el("composer").hidden = !writable || (!composerReady && !composerDraft());
145
+ el("room-admin").hidden = !writable;
146
+ el("draft-fields").disabled = !writable || writesBusy();
147
+ el("send").disabled = !writable || busy() || !composerReady;
148
+ el("room-fields").disabled = !writable || busy() || !controlsReady;
149
+ el("membership-fields").disabled = !writable || busy() || !composerReady;
150
+ el("kind").disabled = !writable || replyTarget !== null;
151
+ // A keyed thread opens only through a new post; a question or consultation (wake-eligible) never names one.
152
+ const question = QUESTION_KINDS.has(el("kind").value);
153
+ el("ref-key").disabled = !writable || writesBusy() || replyTarget !== null || question;
154
+ el("ref-key-hint").textContent = replyTarget
155
+ ? t("Odpowiedź dziedziczy wątek; klucz wątku jest niedostępny.")
156
+ : question
157
+ ? t("Pytanie i konsultacja nie przyjmują klucza wątku.")
158
+ : t("Opcjonalny klucz nowego wątku.");
159
+ el("ref-key-hint").hidden = replyTarget === null && !question;
160
+ el("pending").hidden = pending === null;
161
+ el("retry-write").disabled = el("abandon-write").disabled = !writable || sending;
162
+ for (const id of ["room", "refresh", "more-messages", "more-participants", "latest", "more-sessions"])
163
+ el(id).disabled = busy();
164
+ el("latest").hidden = historyPageStart === null;
165
+ for (const id of ["thread", "apply-thread", "all-history"])
166
+ el(id).disabled = busy() || !composerReady;
167
+ // A live read must not blur a focused message action. The handlers themselves
168
+ // refuse while busy(); only a write or a missing composer disables these controls.
169
+ for (const button of document.querySelectorAll(".reply, .mute-session, .pm-session, .role-session, .resolve-thread, .choose-target")) {
170
+ button.disabled = !writable || writesBusy() || !composerReady;
171
+ button.hidden = !writable;
172
+ }
173
+ for (const button of document.querySelectorAll(".show-thread"))
174
+ button.disabled = writesBusy() || !composerReady;
175
+ el("targets").replaceChildren(...Array.from(targets, ([id, label]) => {
176
+ const item = document.createElement("li");
177
+ item.append(bdi(label), ` · ${id}`);
178
+ return item;
179
+ }));
180
+ for (const row of el("participants").children) row.classList.toggle("is-target", targets.has(row.dataset.sessionId));
181
+ el("reply-target").textContent = replyTarget
182
+ ? t("Odpowiedź na {id} · wątek {thread}", { id: replyTarget.id, thread: replyTarget.thread_id })
183
+ : t("Nowy wątek");
184
+ const roomOption = el("room").selectedOptions[0];
185
+ el("room-title").textContent = selectedRoom && roomOption
186
+ ? (roomOption.dataset.label || roomOption.textContent)
187
+ : t("Wybierz pokój");
188
+ el("live-toggle").hidden = csrf === null || el("viewer").hidden;
189
+ el("live-toggle").disabled = live === null && (busy() || !composerReady);
190
+ scheduleLive(live);
191
+ }
192
+
193
+ function clearDraft() {
194
+ targets.clear();
195
+ replyTarget = null;
196
+ el("body").value = "";
197
+ el("ref-key").value = "";
198
+ el("kind").value = "message";
199
+ syncComposer();
200
+ }
201
+
202
+ function hasDraft() {
203
+ return composerDraft() || el("room-slug").value || el("room-label").value || el("member-session").value;
204
+ }
205
+
206
+ function mayDiscard() {
207
+ if (pending) return window.confirm(t("Zapis mógł już powstać. Usunąć wyłącznie lokalną kopię próby? To nie cofa zapisu na serwerze."));
208
+ if (controlRequest && !window.confirm(t("Zmiana administracyjna może zostać zapisana mimo opuszczenia widoku. Kontynuować?"))) return false;
209
+ return !hasDraft() || window.confirm(t("Usunąć niezapisany szkic?"));
210
+ }
211
+
212
+ function invalidate(abort = true) {
213
+ generation += 1;
214
+ if (abort) requestController.abort();
215
+ requestController = new AbortController();
216
+ return generation;
217
+ }
218
+
219
+ function clearSnapshot() {
220
+ lastMessages = [];
221
+ participantNames.clear();
222
+ el("messages").replaceChildren();
223
+ el("participants").replaceChildren();
224
+ el("pm-mark").hidden = true;
225
+ // The sessions table is scope-sensitive too: clear its page and DOM with the rest of the snapshot.
226
+ sessionsPage = null;
227
+ sessionsDeferred = null;
228
+ // A read already in flight will settle against the old scope; the flush after it must run again.
229
+ if (sessionsLoading) sessionsFlushPending = true;
230
+ el("sessions-table").querySelector("tbody").replaceChildren();
231
+ el("sessions-count").textContent = "";
232
+ el("sessions-note").hidden = true;
233
+ el("more-sessions").hidden = true;
234
+ clearState();
235
+ el("thread-header").hidden = true;
236
+ el("more-messages").hidden = true;
237
+ el("more-participants").hidden = true;
238
+ composerReady = controlsReady = false;
239
+ syncComposer();
240
+ }
241
+
242
+ function clearRoom() {
243
+ scopeEpoch += 1;
244
+ clearSnapshot();
245
+ historyCursor = historyPageStart = participantCursor = participantPageStart = selectedThread = selectedRef = null;
246
+ el("thread").value = "";
247
+ el("thread-scope").textContent = t("Cała historia pokoju");
248
+ composerReady = controlsReady = false;
249
+ syncComposer();
250
+ }
251
+
252
+ function lock() {
253
+ stopLive();
254
+ clearState();
255
+ invalidate();
256
+ clearRoom();
257
+ csrf = principal = access = null;
258
+ delete el("viewer").dataset.access;
259
+ el("read-only-indicator").hidden = true;
260
+ pending = controlRequest = null;
261
+ clearDraft();
262
+ el("write-key").textContent = el("write-status").textContent = "";
263
+ selectedRoom = "";
264
+ el("token").value = "";
265
+ el("room-slug").value = el("room-label").value = el("member-session").value = "";
266
+ el("room").replaceChildren();
267
+ el("viewer").hidden = true;
268
+ el("logout").hidden = el("live-toggle").hidden = true;
269
+ el("app-room").hidden = true;
270
+ el("roster-filter").value = "";
271
+ el("roster-count").textContent = "";
272
+ el("roster-count").removeAttribute("title");
273
+ rosterPartial = false;
274
+ el("login").hidden = false;
275
+ el("login-view").hidden = false;
276
+ view = "chat";
277
+ el("chat-view").hidden = false;
278
+ el("sessions-view").hidden = true;
279
+ el("tab-chat").setAttribute("aria-selected", "true");
280
+ el("tab-sessions").setAttribute("aria-selected", "false");
281
+ el("sessions-filter").value = "";
282
+ }
283
+
284
+ function showSession() {
285
+ el("viewer").hidden = false;
286
+ el("app-room").hidden = false;
287
+ el("logout").hidden = false;
288
+ el("login").hidden = true;
289
+ el("login-view").hidden = true;
290
+ }
291
+
292
+ async function request(path, { method = "GET", body, csrfToken, key, signal = requestController.signal } = {}) {
293
+ const reading = method === "GET";
294
+ if (!reading && access !== "operator" && path !== "/v1/login" && path !== "/v1/logout")
295
+ throw new Error("READ_ONLY");
296
+ if (reading) reads += 1;
297
+ try {
298
+ const response = await fetch(path, {
299
+ method, credentials: "same-origin", cache: "no-store", redirect: "error",
300
+ signal: AbortSignal.any([signal, AbortSignal.timeout(10000)]),
301
+ headers: body === undefined ? {} : {
302
+ "Content-Type": "application/json", "X-CSRF-Token": csrfToken,
303
+ ...(key ? { "Idempotency-Key": key } : {}),
304
+ },
305
+ body: body === undefined ? undefined : JSON.stringify(body),
306
+ });
307
+ if (!response.ok) {
308
+ const error = new Error("REQUEST_FAILED");
309
+ error.status = response.status;
310
+ try {
311
+ const payload = await response.json();
312
+ const code = payload?.error?.code;
313
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code)) error.code = code;
314
+ } catch { /* A non-JSON refusal keeps the generic message. */ }
315
+ throw error;
316
+ }
317
+ return await response.json();
318
+ } finally { if (reading) reads -= 1; scheduleLive(live); }
319
+ }
320
+
321
+ // A failed read discards potentially stale scope-sensitive content, never the operator's draft.
322
+ // `saved` is a confirmed write that this read followed: the failure is appended, not substituted.
323
+ function failed(error, current, { saved = "", denied = t("Sesja wygasła lub dostęp został cofnięty. Zaloguj się ponownie.") } = {}) {
324
+ if (current !== generation || pending || controlRequest) return false;
325
+ invalidate();
326
+ clearRoom();
327
+ const prefix = saved ? `${saved} ` : "";
328
+ if (error.status === 401 || error.status === 403) {
329
+ lock();
330
+ el("notice").textContent = prefix + denied;
331
+ } else if (error.status === 429) {
332
+ el("notice").textContent = prefix + t("Zbyt wiele żądań lub nieudanych prób logowania. Spróbuj ponownie za minutę.");
333
+ } else {
334
+ el("notice").textContent = prefix + t(saved
335
+ ? "Nie udało się odczytać danych. Odśwież widok; nie wysyłaj wiadomości ponownie."
336
+ : "Nie udało się odczytać danych. Odśwież widok lub zaloguj się ponownie.");
337
+ }
338
+ return true;
339
+ }
340
+
341
+ // Runs one read; returns whether it failed and was reported.
342
+ async function read(work, current, options) {
343
+ try { await work(); return false; } catch (error) { return failed(error, current, options); }
344
+ }
345
+
346
+ function text(tag, value, className) {
347
+ const node = document.createElement(tag);
348
+ node.textContent = value == null ? "—" : String(value);
349
+ if (className) node.className = className;
350
+ return node;
351
+ }
352
+
353
+ // Isolates a session-controlled label so bidirectional controls cannot reorder the text around it.
354
+ function bdi(value) { return text("bdi", value); }
355
+
356
+ function roomPath(room = selectedRoom) { return `/v1/rooms/${encodeURIComponent(room)}`; }
357
+
358
+ function sessionIdentity(p) {
359
+ return `${p.harness ?? "Agent"}${p.host ? ` · ${p.host}` : ""} · ${p.session_id.slice(0, 8)}`;
360
+ }
361
+
362
+ function sessionName(p) {
363
+ return p.title || sessionIdentity(p);
364
+ }
365
+
366
+ function senderInfo(m) {
367
+ return participantNames.get(m.sender.session_id) ?? m.sender;
368
+ }
369
+
370
+ function senderName(m) {
371
+ return m.sender.session_id === null ? "Operator" : sessionName(senderInfo(m));
372
+ }
373
+
374
+ function senderInitial(m) {
375
+ return m.sender.session_id === null ? "OP" : (senderInfo(m).harness ?? "A").slice(0, 2).toUpperCase();
376
+ }
377
+
378
+ function displayTimestamp(value) {
379
+ const parsed = new Date(value);
380
+ return Number.isNaN(parsed.getTime()) ? String(value) : TIME_FORMAT.format(parsed);
381
+ }
382
+
383
+ // Desktop scrolls #messages; the narrow layout scrolls the document instead.
384
+ const mobileLayout = () => window.matchMedia("(max-width: 820px)").matches;
385
+ function messageScrollTop() { return mobileLayout() ? window.scrollY : el("messages").scrollTop; }
386
+ function setMessageScrollTop(value) {
387
+ if (mobileLayout()) window.scrollTo({ top: value, behavior: "auto" });
388
+ else el("messages").scrollTop = value;
389
+ }
390
+ function scrollMessagesToBottom() {
391
+ if (mobileLayout()) window.scrollTo({ top: document.documentElement.scrollHeight, behavior: "auto" });
392
+ else el("messages").scrollTop = el("messages").scrollHeight;
393
+ }
394
+ function atBottom() {
395
+ if (mobileLayout())
396
+ return window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 80;
397
+ const list = el("messages");
398
+ return list.scrollHeight - list.scrollTop - list.clientHeight < 80;
399
+ }
400
+
401
+ function identifier(value) {
402
+ return text("code", value == null ? "—" : String(value), "identifier");
403
+ }
404
+
405
+ function definition(term, value) {
406
+ const dt = text("dt", term);
407
+ const dd = document.createElement("dd");
408
+ dd.append(identifier(value));
409
+ return [dt, dd];
410
+ }
411
+
412
+ function receiptState(label, present) {
413
+ return text("span", `${t(label)}: ${present ? t("tak") : "—"}`,
414
+ `receipt-state ${present ? "is-present" : "is-missing"}`);
415
+ }
416
+
417
+ function receiptSummary(receipt) {
418
+ const item = document.createElement("li");
419
+ const peer = participantNames.get(receipt.session_id) ?? receipt;
420
+ item.append(text("bdi", peer.title ? `${peer.title} · ${sessionIdentity(peer)}` : sessionIdentity(peer), "receipt-session"));
421
+ item.append(receiptState(t("zapis"), Boolean(receipt.stored_at)));
422
+ item.append(receiptState(t("przekazanie"), Boolean(receipt.handed_at)));
423
+ item.append(receiptState("ACK", Boolean(receipt.acknowledged_at)));
424
+ item.append(receiptState(t("odpowiedź"), Boolean(receipt.replying_message_id)));
425
+ // Every state renders, absent ones as "—". `browser_verify_checks.py`
426
+ // asserts this exact set against the API row, so hiding the empty ones
427
+ // would break the verifier's receipt contract rather than merely tidy the
428
+ // line. Readability here is the label fix above, not dropping fields.
429
+ item.append(text("span", t("niepewność: {reason}", { reason: receipt.uncertainty_reason ?? "—" }),
430
+ `receipt-state ${receipt.uncertainty_reason ? "is-uncertain" : "is-missing"}`));
431
+ item.append(text("span", t("próba: {outcome}", { outcome: receipt.delivery?.outcome ?? "—" }), "receipt-state"));
432
+ return item;
433
+ }
434
+
435
+ // The room's one PM mark is a coordination label and never authority. It is a room-level line, so it shows
436
+ // even when its holder sits on another roster page; the holder's row also carries a badge.
437
+ function renderPmMark(pm) {
438
+ const line = el("pm-mark");
439
+ line.replaceChildren();
440
+ line.hidden = false;
441
+ line.classList.toggle("is-set", pm !== null && pm !== undefined);
442
+ if (!pm) {
443
+ line.append(t("Znacznik PM: brak."));
444
+ return;
445
+ }
446
+ const holder = participantNames.get(pm.session_id);
447
+ const more = document.createElement("details");
448
+ more.className = "pm-mark-details";
449
+ more.open = pmDetailsOpen;
450
+ more.addEventListener("toggle", () => { pmDetailsOpen = more.open; });
451
+ const times = text("p", t("{session} · ustawiony {set} · ostatnia aktywność {activity} · wygasa {expires}.", {
452
+ session: pm.session_id, set: displayTimestamp(pm.set_at),
453
+ activity: displayTimestamp(pm.last_activity_at), expires: displayTimestamp(pm.expires_at),
454
+ }), "pm-mark-times");
455
+ // The text shows local times; the tooltip keeps the exact server values.
456
+ times.title = t("ustawiony: {set} · ostatnia aktywność: {activity} · wygasa: {expires}", {
457
+ set: pm.set_at, activity: pm.last_activity_at, expires: pm.expires_at,
458
+ });
459
+ more.append(text("summary", t("Znacznik nie nadaje uprawnień.")), times);
460
+ line.append(t("Znacznik PM: "), holder ? bdi(sessionName(holder)) : t("sesja z innej strony listy"), more);
461
+ }
462
+
463
+ // A chip names only what needs attention: a confirmed "off" stays quiet, anything else (on, unknown) shows.
464
+ function attentionChip(label, value) {
465
+ return value === false ? null
466
+ : text("span", value === true ? label : `${label}: ${value ?? "unknown"}`, "chip chip-flag");
467
+ }
468
+
469
+ // The visible word is short; the exact session UUID stays in the accessible name for assistive tools.
470
+ function rosterButton(className, shown, accessibleName, onClick) {
471
+ const button = text("button", shown, className);
472
+ button.type = "button";
473
+ button.setAttribute("aria-label", accessibleName);
474
+ button.addEventListener("click", onClick);
475
+ return button;
476
+ }
477
+
478
+ // Client-side narrowing of the rows already loaded; it never asks the server and never selects a recipient. It
479
+ // owns which rows show and where the group headings sit: CSS draws a heading from the data attributes of the first
480
+ // row of a group that is still shown, so narrowing never leaves a group without one. The count in a heading is the
481
+ // group's size on the loaded page, like #roster-count (and says "na stronie" while the page is partial), not the
482
+ // number of rows the filter lets through.
483
+ function applyRosterFilter() {
484
+ const query = el("roster-filter").value.trim().toLowerCase();
485
+ const rows = [...el("participants").children];
486
+ const sizes = { true: 0, false: 0 };
487
+ for (const row of rows) sizes[row.dataset.online] += 1;
488
+ const headed = new Set();
489
+ for (const row of rows) {
490
+ row.hidden = query !== "" && !(row.dataset.search ?? "").includes(query);
491
+ delete row.dataset.group;
492
+ delete row.dataset.count;
493
+ if (row.hidden || headed.has(row.dataset.online)) continue;
494
+ headed.add(row.dataset.online);
495
+ row.dataset.group = row.dataset.online === "true" ? "Online" : "Offline";
496
+ row.dataset.count = `${sizes[row.dataset.online]}${rosterPartial ? t(" na stronie") : ""}`;
497
+ }
498
+ }
499
+
500
+ function renderParticipants(rows, pm = null, partial = false) {
501
+ rosterPartial = partial;
502
+ participantNames.clear();
503
+ for (const p of rows)
504
+ participantNames.set(p.session_id, p);
505
+ renderPmMark(pm);
506
+ // Online sessions first, the server's order inside each group. The group headings are drawn by CSS from data
507
+ // attributes that applyRosterFilter places, so the list keeps exactly one <li> per participant.
508
+ const ordered = [...rows.filter((p) => p.online), ...rows.filter((p) => !p.online)];
509
+ const onlineCount = rows.length - ordered.filter((p) => !p.online).length;
510
+ // The counts describe the loaded page. While it is the whole room they stand bare; otherwise they say so, and the
511
+ // tooltip explains it, because the server sends no room-wide total.
512
+ el("roster-count").textContent = `${partial ? t("na stronie: ") : ""}${onlineCount} online · ${rows.length}`;
513
+ if (partial) el("roster-count").title = t("Liczby dotyczą załadowanej strony uczestników, nie całego pokoju.");
514
+ else el("roster-count").removeAttribute("title");
515
+ el("participants").replaceChildren(...ordered.map((p) => {
516
+ const label = sessionName(p);
517
+ if (targets.has(p.session_id)) targets.set(p.session_id, label);
518
+ const item = document.createElement("li");
519
+ item.dataset.sessionId = p.session_id;
520
+ item.dataset.online = String(Boolean(p.online));
521
+ item.dataset.search = `${label} ${sessionIdentity(p)} ${p.session_id} ${p.lane ?? ""}`.toLowerCase();
522
+ const holder = pm !== null && pm.session_id === p.session_id;
523
+ item.classList.toggle("is-pm", holder);
524
+ item.classList.toggle("is-target", targets.has(p.session_id));
525
+ const dot = text("span", "", `status-dot ${p.online ? "status-online" : "status-offline"}`);
526
+ dot.setAttribute("role", "img");
527
+ dot.setAttribute("aria-label", p.online ? "online" : "offline");
528
+ dot.title = p.online ? "online" : "offline";
529
+ item.append(dot);
530
+ const top = document.createElement("div");
531
+ top.className = "participant-top";
532
+ top.append(text("bdi", label, p.title ? "session-title" : "session-title participant-identity"));
533
+ if (holder) top.append(text("span", "PM", "status-pill pm-badge"));
534
+ top.append(text("span", p.native_state, "native-state"));
535
+ item.append(top);
536
+ const sub = document.createElement("div");
537
+ sub.className = "participant-sub";
538
+ if (p.title) sub.append(text("bdi", sessionIdentity(p), "participant-identity"));
539
+ for (const [flag, value] of [["mute", p.muted], ["stop", p.stopped], ["Plan Mode", p.plan_mode]]) {
540
+ const chip = attentionChip(flag, value);
541
+ if (chip) sub.append(chip);
542
+ }
543
+ // Advisory only: the declaration is neither an entitlement nor evidence of what the session is doing.
544
+ // The row shows a short chip; the full wording, with the disclaimer, is one disclosure away.
545
+ const laneNote = p.lane
546
+ ? ` · ${t("zadeklarowany {minutes} min temu · deklaracja, nie uprawnienie", { minutes: Math.floor((p.lane_age_seconds ?? 0) / 60) })}`
547
+ : "";
548
+ if (p.lane) {
549
+ const chip = document.createElement("span");
550
+ chip.className = "chip chip-lane";
551
+ chip.title = `lane: ${p.lane}${laneNote}`;
552
+ chip.append("lane: ", bdi(p.lane));
553
+ sub.append(chip);
554
+ }
555
+ if (sub.childElementCount) item.append(sub);
556
+ const actions = document.createElement("div");
557
+ actions.className = "participant-actions";
558
+ actions.append(rosterButton("choose-target", t("Wybierz"), t("Wybierz {id}", { id: p.session_id }), () => {
559
+ if (access !== "operator" || writesBusy() || !composerReady) return;
560
+ if (targets.size === 16 && !targets.has(p.session_id)) {
561
+ el("notice").textContent = t("Można wybrać najwyżej 16 sesji.");
562
+ return;
563
+ }
564
+ targets.set(p.session_id, label);
565
+ syncComposer();
566
+ }));
567
+ if (typeof p.muted === "boolean") {
568
+ const verb = p.muted ? t("Cofnij wyciszenie") : t("Wycisz");
569
+ actions.append(rosterButton("mute-session", verb, `${verb} ${p.session_id}`,
570
+ () => muteSession(p.session_id, !p.muted)));
571
+ }
572
+ const mark = holder ? t("Zdejmij PM") : t("Ustaw PM");
573
+ actions.append(rosterButton("pm-session", mark, `${mark} ${p.session_id}`, () => setPm(p.session_id, !holder)));
574
+ item.append(actions);
575
+ // The exact selector stays on the row, one disclosure away, and is never replaced by the title.
576
+ const details = document.createElement("details");
577
+ details.className = "participant-details";
578
+ details.open = openRows.has(p.session_id);
579
+ details.addEventListener("toggle", () => {
580
+ if (details.open) openRows.add(p.session_id);
581
+ else openRows.delete(p.session_id);
582
+ });
583
+ const selector = document.createElement("div");
584
+ selector.className = "participant-label";
585
+ selector.append(bdi(p.label));
586
+ details.append(text("summary", t("Szczegóły")), text("div", p.session_id, "participant-id"), selector,
587
+ text("div", `${p.online ? "online" : "offline"} · ${p.native_state} · ` +
588
+ `mute: ${p.muted} · stop: ${p.stopped} · Plan Mode: ${p.plan_mode}`, "participant-flags"));
589
+ if (p.lane) {
590
+ const lane = document.createElement("div");
591
+ lane.className = "participant-lane";
592
+ lane.append("lane: ", bdi(p.lane), laneNote);
593
+ details.append(lane);
594
+ }
595
+ item.append(details);
596
+ return item;
597
+ }));
598
+ applyRosterFilter();
599
+ // Participant names make a sender identity readable; repaint the current page once they are known.
600
+ // renderMessages captures and restores open evidence, focus and the reading position.
601
+ if (lastMessages.length) renderMessages(lastMessages, { follow: atBottom() });
602
+ syncComposer();
603
+ }
604
+
605
+ function captureMessageView() {
606
+ const list = el("messages");
607
+ const open = new Set();
608
+ for (const evidence of list.querySelectorAll("details.message-evidence[open]")) {
609
+ const item = evidence.closest("li[data-message-id]");
610
+ if (item) open.add(item.dataset.messageId);
611
+ }
612
+ const focused = document.activeElement;
613
+ let focus = null;
614
+ if (focused && list.contains(focused)) {
615
+ const item = focused.closest("li[data-message-id]");
616
+ if (item) focus = { id: item.dataset.messageId, action: focused.dataset.messageAction || null };
617
+ }
618
+ // The newest page is capped, so a live read can evict the oldest entry above
619
+ // the reader. Anchor to the first visible message, not to a raw scroll offset.
620
+ const listBox = list.getBoundingClientRect();
621
+ const listTop = listBox.top;
622
+ // On a narrow viewport the document scrolls and the list box starts above
623
+ // the viewport; "visible" means the viewport, not the list box.
624
+ const visibleTop = Math.max(listTop, 0);
625
+ const visibleBottom = Math.min(listBox.bottom, window.innerHeight);
626
+ const children = Array.from(list.children);
627
+ // Rows are flat, so a sliver of the row above is usually still in view. If that sliver were
628
+ // the anchor and were evicted with its neighbours, the nearest survivor would land rows too
629
+ // high. Anchor to the first row that starts in view; a row taller than the view keeps itself.
630
+ const inView = children.filter((item) => {
631
+ const box = item.getBoundingClientRect();
632
+ return box.bottom > visibleTop + 1 && box.top < visibleBottom;
633
+ });
634
+ const anchor = inView.find((item) => item.getBoundingClientRect().top >= visibleTop - 1) ?? inView[0];
635
+ return {
636
+ open,
637
+ focus,
638
+ top: messageScrollTop(),
639
+ anchor: anchor ? {
640
+ id: anchor.dataset.messageId,
641
+ index: children.indexOf(anchor),
642
+ offset: anchor.getBoundingClientRect().top - listTop,
643
+ } : null,
644
+ };
645
+ }
646
+
647
+ function restoreMessageView(view, follow) {
648
+ const items = Array.from(el("messages").children);
649
+ for (const item of items) {
650
+ if (view.open.has(item.dataset.messageId)) {
651
+ const evidence = item.querySelector("details.message-evidence");
652
+ if (evidence) evidence.open = true;
653
+ }
654
+ }
655
+ if (view.focus) {
656
+ const item = items.find((node) => node.dataset.messageId === view.focus.id);
657
+ const target = item && view.focus.action
658
+ ? item.querySelector(`[data-message-action="${view.focus.action}"]`)
659
+ : null;
660
+ target?.focus({ preventScroll: true });
661
+ }
662
+ if (follow) {
663
+ scrollMessagesToBottom();
664
+ return;
665
+ }
666
+ const list = el("messages");
667
+ let anchor = null;
668
+ let desiredOffset = 0;
669
+ if (view.anchor) {
670
+ anchor = items.find((node) => node.dataset.messageId === view.anchor.id);
671
+ if (anchor) desiredOffset = view.anchor.offset;
672
+ else if (items.length) {
673
+ // The anchored message itself was evicted. The page is ordered oldest
674
+ // first, so the first surviving entry is the nearest one after the
675
+ // removed front block; anchor there at the same visual offset.
676
+ anchor = items[0];
677
+ desiredOffset = view.anchor.offset;
678
+ }
679
+ }
680
+ if (!anchor) {
681
+ setMessageScrollTop(view.top);
682
+ return;
683
+ }
684
+ const currentOffset = anchor.getBoundingClientRect().top - list.getBoundingClientRect().top;
685
+ setMessageScrollTop(messageScrollTop() + currentOffset - desiredOffset);
686
+ }
687
+
688
+ function renderMessages(rows, { follow = false } = {}) {
689
+ const view = captureMessageView();
690
+ lastMessages = rows;
691
+ el("messages").replaceChildren(...rows.map((m) => {
692
+ const receipts = Array.isArray(m.receipts) ? m.receipts : [];
693
+ const operator = m.sender.session_id === null;
694
+ const item = document.createElement("li");
695
+ item.dataset.messageId = m.id;
696
+ item.className = `${operator ? "message-operator " : ""}msg-${m.kind}`;
697
+ item.dataset.harness = operator ? "operator" : (senderInfo(m).harness ?? "");
698
+ item.append(text("span", senderInitial(m), "message-avatar"));
699
+ const main = document.createElement("div");
700
+ main.className = "message-main";
701
+ const header = document.createElement("header");
702
+ header.className = "message-header";
703
+ header.append(text("bdi", senderName(m), "sender-name"));
704
+ // An untitled session is already named by its identity; repeating it would only add noise.
705
+ if (m.sender.session_id !== null && senderInfo(m).title)
706
+ header.append(text("bdi", sessionIdentity(senderInfo(m)), "sender-identity"));
707
+ // Only an operator publishes without a session; an agent cannot produce this shape.
708
+ if (operator) header.append(text("span", "operator", "operator-label"));
709
+ const time = text("time", displayTimestamp(m.created_at), "timestamp");
710
+ time.dateTime = m.created_at;
711
+ time.title = m.created_at; // the text is the local format; the tooltip is the exact server value
712
+ header.append(time);
713
+ // A plain message or reply carries no badge ("Odpowiedź na ..." already marks a reply): only the kinds that
714
+ // mean something else (question, status, ...) are marked.
715
+ if (m.kind !== "message" && m.kind !== "reply") header.append(text("span", KIND_LABELS[m.kind] ?? m.kind, `kind-badge kind-${m.kind}`));
716
+ if (m.thread_ref_key) header.append(text("bdi", m.thread_ref_key, "thread-key"));
717
+ if (m.thread_resolved_at) header.append(text("span", t("rozwiązany"), "resolved-badge"));
718
+ main.append(header);
719
+ if (m.reply_to) main.append(text("p", t("Odpowiedź na {id}", { id: `${String(m.reply_to).slice(0, 8)}…` }), "reply-context"));
720
+ main.append(text("p", m.body, "body"));
721
+ if (receipts.length) {
722
+ const summary = document.createElement("ul");
723
+ summary.className = "receipt-summary";
724
+ summary.setAttribute("aria-label", t("Potwierdzenia dostarczenia"));
725
+ for (const receipt of receipts) summary.append(receiptSummary(receipt));
726
+ main.append(summary);
727
+ }
728
+ const actions = document.createElement("div");
729
+ actions.className = "message-actions";
730
+ // The identifier belongs in the evidence disclosure, not in the label: a
731
+ // full UUID as button text was the single loudest thing on the page.
732
+ const button = text("button", t("Odpowiedz"), "reply");
733
+ button.type = "button";
734
+ button.dataset.messageAction = "reply";
735
+ button.addEventListener("click", () => {
736
+ if (access !== "operator" || busy() || !composerReady || !mayDiscard()) return;
737
+ clearDraft();
738
+ replyTarget = { id: m.id, thread_id: m.thread_id, senderSession: m.sender.session_id };
739
+ if (m.sender.session_id) targets.set(m.sender.session_id, senderName(m));
740
+ syncComposer();
741
+ el("body").focus();
742
+ });
743
+ actions.append(button);
744
+ const show = text("button", t("Wątek"), "show-thread");
745
+ show.type = "button";
746
+ show.dataset.messageAction = "thread";
747
+ show.addEventListener("click", () => filterThread(m.thread_id));
748
+ actions.append(show);
749
+ main.append(actions);
750
+ const evidence = document.createElement("details");
751
+ evidence.className = "message-evidence";
752
+ const evidenceSummary = text("summary", t("Szczegóły techniczne"));
753
+ evidenceSummary.dataset.messageAction = "evidence";
754
+ evidence.append(evidenceSummary);
755
+ const grid = document.createElement("dl");
756
+ grid.className = "evidence-grid";
757
+ grid.append(...definition(t("ID wiadomości"), m.id));
758
+ grid.append(...definition(t("Wątek"), m.thread_id));
759
+ grid.append(...definition(t("Odpowiedź na"), m.reply_to ?? "—"));
760
+ grid.append(...definition(t("Nadawca"), m.sender.session_id ?? m.sender.principal_id));
761
+ if (m.sender.session_id && senderInfo(m).native_session_id)
762
+ grid.append(...definition(t("Sesja natywna"), senderInfo(m).native_session_id));
763
+ grid.append(...definition(t("Czas"), m.created_at));
764
+ evidence.append(grid);
765
+ if (receipts.length) {
766
+ const full = document.createElement("ul");
767
+ full.className = "evidence-receipts";
768
+ for (const receipt of receipts) full.append(text("li",
769
+ `${receipt.session_id} · ${t("zapis:")} ${receipt.stored_at ?? "—"} · ${t("przekazanie:")} ${receipt.handed_at ?? "—"} · ` +
770
+ `ACK: ${receipt.acknowledged_at ?? "—"} · ${t("odpowiedź:")} ${receipt.replying_message_id ?? "—"} · ` +
771
+ `${t("niepewność:")} ${receipt.uncertainty_reason ?? "—"} · ${t("próba:")} ${receipt.delivery?.outcome ?? "—"}`,
772
+ ));
773
+ evidence.append(full);
774
+ }
775
+ main.append(evidence);
776
+ item.append(main);
777
+ return item;
778
+ }));
779
+ restoreMessageView(view, follow);
780
+ syncComposer();
781
+ }
782
+
783
+ function clearState() {
784
+ stateEpoch += 1;
785
+ clearTimeout(stateTimer);
786
+ stateTimer = null;
787
+ el("state-groups").replaceChildren();
788
+ }
789
+
790
+ // One slot of a validation-lease observation, as text.
791
+ function slotLine(slot, since) {
792
+ const who = [slot.lane ?? slot.owner, slot.branch, slot.profile].filter(Boolean).join(", ");
793
+ const state = {
794
+ free: t("wolny"),
795
+ held: t("zajęty ({who}) od {since}", { who, since }),
796
+ stuck: t("zablokowany (stuck)"),
797
+ }[slot.state];
798
+ return `Slot ${slot.slot ?? "?"}: ${state ?? t("nieznany")}`;
799
+ }
800
+
801
+ function renderStateValue(entry) {
802
+ const box = document.createElement("div");
803
+ const value = entry.value;
804
+ if (entry.stale) {
805
+ box.append(text("p", entry.stale_reason === "revoked"
806
+ ? t("nieznany (producent odwołany)")
807
+ : t("nieznany, ostatnio widziany {seconds} s temu", { seconds: entry.age_seconds })));
808
+ } else if (value.schema === "agent-chat.validation-lease.v1") {
809
+ if (value.scan === "unknown") box.append(text("p", t("nieznany ({reason})", { reason: value.reason ?? "—" })));
810
+ else {
811
+ // Times are local and absolute; the exact ISO value stays in the tooltip.
812
+ for (const slot of (Array.isArray(value.slots) ? value.slots : []).slice(0, 16)) {
813
+ const line = text("p", slotLine(slot && typeof slot === "object" ? slot : {}, displayTimestamp(entry.changed_at)));
814
+ if (slot?.state === "held") line.title = `od: ${entry.changed_at}`;
815
+ box.append(line);
816
+ }
817
+ for (const waiter of (Array.isArray(value.waiters) ? value.waiters : []).slice(0, 16)) {
818
+ const w = waiter && typeof waiter === "object" ? waiter : {};
819
+ const line = text("p", t("Oczekuje: {who} od {since}", {
820
+ who: [w.lane ?? w.owner, w.branch].filter(Boolean).join(", "),
821
+ since: w.waiting_since ? displayTimestamp(w.waiting_since) : "—",
822
+ }));
823
+ if (w.waiting_since) line.title = `od: ${w.waiting_since}`;
824
+ box.append(line);
825
+ }
826
+ }
827
+ } else {
828
+ box.append(text("pre", JSON.stringify(value, null, 1).slice(0, 2000)));
829
+ }
830
+ return box;
831
+ }
832
+
833
+ function renderState(data) {
834
+ clearTimeout(stateTimer);
835
+ stateTimer = null;
836
+ const groups = new Map();
837
+ for (const entry of data.entries) {
838
+ const key = entry.ref_key ?? "";
839
+ if (!groups.has(key)) groups.set(key, []);
840
+ groups.get(key).push(entry);
841
+ }
842
+ if (!data.entries.length) {
843
+ el("state-groups").replaceChildren(text("p", t("Brak obserwacji stanu."), "meta"));
844
+ return;
845
+ }
846
+ el("state-groups").replaceChildren(...Array.from(groups, ([key, entries]) => {
847
+ const group = document.createElement("div");
848
+ group.append(key ? bdi(key) : text("span", t("Bez klucza wątku")));
849
+ if (key) {
850
+ const show = text("button", t("Pokaż wątek"), "show-thread");
851
+ show.type = "button";
852
+ show.setAttribute("aria-label", `Pokaż wątek ${key}`);
853
+ show.addEventListener("click", () => filterThread(key));
854
+ group.append(" ", show);
855
+ }
856
+ const list = document.createElement("ul");
857
+ for (const entry of entries) {
858
+ const item = document.createElement("li");
859
+ // Local, absolute times: a snapshot ages, so "3 min ago" would be wrong. The exact ISO values sit in the tooltip.
860
+ const meta = text("p", `${entry.state_key} · ${entry.producer.producer}@${entry.producer.host} · ` +
861
+ t("zmiana: {changed} · obserwacja: {observed}", {
862
+ changed: displayTimestamp(entry.changed_at), observed: displayTimestamp(entry.observed_at),
863
+ }), "meta");
864
+ meta.title = t("zmiana: {changed} · obserwacja: {observed}", {
865
+ changed: entry.changed_at, observed: entry.observed_at,
866
+ });
867
+ item.append(meta, renderStateValue(entry));
868
+ list.append(item);
869
+ }
870
+ group.append(list);
871
+ return group;
872
+ }));
873
+ if (data.next_key) el("state-groups").append(text("p", t("Wyświetlono pierwsze wpisy; reszta wymaga agent-chat state."), "meta"));
874
+ // Staleness comes from the server's flags; this timer only asks it again just after the soonest fresh entry lapses.
875
+ const lives = data.entries.filter((entry) => !entry.stale).map((entry) => entry.expires_in_seconds);
876
+ if (lives.length) {
877
+ const epoch = stateEpoch;
878
+ const room = selectedRoom;
879
+ stateTimer = setTimeout(async () => {
880
+ stateTimer = null;
881
+ if (epoch !== stateEpoch || room !== selectedRoom) return;
882
+ try {
883
+ const fresh = await request(`${roomPath(room)}/state?limit=100`);
884
+ if (epoch === stateEpoch && room === selectedRoom) renderState(fresh);
885
+ } catch (error) {
886
+ if (epoch !== stateEpoch) return;
887
+ if (error.status === 401 || error.status === 403) failed(error, generation);
888
+ else el("state-groups").replaceChildren(text("p", t("Stan zasobów niedostępny."), "meta"));
889
+ }
890
+ }, Math.min(...lives) * 1000 + 1500);
891
+ }
892
+ }
893
+
894
+ async function roomState(current) {
895
+ const epoch = stateEpoch;
896
+ try {
897
+ const data = await request(`${roomPath()}/state?limit=100`);
898
+ if (current === generation && epoch === stateEpoch) renderState(data);
899
+ } catch (error) {
900
+ // The card is advisory: only a lost session ends the view; any other failure leaves the rest readable.
901
+ if (error.status === 401 || error.status === 403) throw error;
902
+ if (current === generation) el("state-groups").replaceChildren(text("p", t("Stan zasobów niedostępny."), "meta"));
903
+ }
904
+ }
905
+
906
+ async function participants(current, after = null) {
907
+ const query = new URLSearchParams({ limit: "50" });
908
+ if (after !== null) query.set("after_session", after);
909
+ const data = await request(`${roomPath()}/participants?${query}`);
910
+ if (current !== generation) return;
911
+ renderParticipants(data.participants, data.pm ?? null, after !== null || data.next_session_id !== null);
912
+ participantPageStart = after;
913
+ participantCursor = data.next_session_id;
914
+ el("more-participants").hidden = participantCursor === null;
915
+ }
916
+
917
+ async function history(current, before = null) {
918
+ const query = new URLSearchParams({ limit: "50", before: before ?? NEWEST });
919
+ if (selectedThread !== null) query.set("thread_id", selectedThread);
920
+ else if (selectedRef !== null) query.set("ref_key", selectedRef);
921
+ const data = await request(`${roomPath()}/history?${query}`);
922
+ if (current !== generation) return;
923
+ if (![data.next_cursor, data.retained_floor, data.position].every(cursorValid)) throw new Error("INVALID_HISTORY_CURSOR");
924
+ historyEventCursor = data.position;
925
+ historyFloor = data.retained_floor;
926
+ const follow = before === null && atBottom();
927
+ renderMessages(data.messages, { follow });
928
+ renderThreadHeader(data.messages);
929
+ historyPageStart = before;
930
+ historyCursor = data.has_more ? data.next_cursor : null;
931
+ el("more-messages").hidden = historyCursor === null;
932
+ el("latest").hidden = historyPageStart === null;
933
+ }
934
+
935
+ // One thread, shown with its key and resolution state. The button posts the opposite state through `control`.
936
+ function renderThreadHeader(messages) {
937
+ const header = el("thread-header");
938
+ header.replaceChildren();
939
+ header.hidden = selectedThread === null && selectedRef === null;
940
+ if (header.hidden) return;
941
+ const first = messages[0];
942
+ if (!first) {
943
+ header.append(t("Brak wiadomości w tym wątku."));
944
+ return;
945
+ }
946
+ const resolved = Boolean(first.thread_resolved_at);
947
+ const threadState = resolved
948
+ ? t("rozwiązany {time}", { time: first.thread_resolved_at })
949
+ : t("otwarty");
950
+ header.append(`${t("Klucz:")} `, first.thread_ref_key ? bdi(first.thread_ref_key) : t("brak"),
951
+ ` · ${t("stan:")} ${threadState} `);
952
+ const button = text("button", resolved ? t("Otwórz ponownie") : t("Oznacz jako rozwiązany"), "resolve-thread");
953
+ button.type = "button";
954
+ button.disabled = access !== "operator" || busy() || !composerReady;
955
+ button.hidden = access !== "operator";
956
+ button.addEventListener("click", () => control(`/v1/threads/${first.thread_id}/resolution`, { resolved: !resolved }, {
957
+ matches: (data) => data.thread_id === first.thread_id && data.resolved === !resolved,
958
+ success: () => t("Potwierdzono zapis: wątek {state}. Rozwiązanie nie blokuje pisania.", {
959
+ state: resolved ? t("otwarty ponownie") : t("oznaczony jako rozwiązany"),
960
+ }),
961
+ label: "rozwiązania wątku",
962
+ }));
963
+ header.append(button);
964
+ }
965
+
966
+ async function filterThread(thread) {
967
+ if (busy() || !composerReady) return;
968
+ const isRef = thread !== null && !uuid(thread) && REF_KEY.test(thread);
969
+ if (thread !== null && !uuid(thread) && !isRef) {
970
+ el("notice").textContent = t("Podaj poprawny UUID wątku, klucz wątku albo pozostaw puste pole.");
971
+ return;
972
+ }
973
+ const current = invalidate();
974
+ selectedThread = isRef ? null : thread;
975
+ selectedRef = isRef ? thread : null;
976
+ el("thread").value = thread ?? "";
977
+ el("thread-scope").textContent = thread
978
+ ? t("Wątek: {thread}", { thread })
979
+ : t("Cała historia pokoju");
980
+ el("thread-header").hidden = true;
981
+ el("messages").replaceChildren();
982
+ historyCursor = historyPageStart = null;
983
+ el("more-messages").hidden = true;
984
+ el("latest").hidden = true;
985
+ el("notice").textContent = t("Odczyt historii…");
986
+ await read(async () => {
987
+ await history(current);
988
+ if (current === generation) el("notice").textContent = t("Migawka historii. Filtr nie zmienia szkicu ani odbiorców.");
989
+ }, current);
990
+ }
991
+
992
+ async function latestHistory() {
993
+ if (busy() || !composerReady || historyPageStart === null) return;
994
+ const current = invalidate();
995
+ el("latest").disabled = true;
996
+ el("notice").textContent = t("Powrót do najnowszych…");
997
+ await read(async () => {
998
+ await history(current);
999
+ if (current === generation) {
1000
+ scrollMessagesToBottom();
1001
+ el("notice").textContent = t("Migawka historii. Filtr nie zmienia szkicu ani odbiorców.");
1002
+ }
1003
+ }, current);
1004
+ syncComposer();
1005
+ }
1006
+
1007
+ async function control(path, payload, { matches, success, label, updateRooms = false }) {
1008
+ if (access !== "operator" || busy() || !controlsReady) return;
1009
+ const current = invalidate();
1010
+ const attempt = Object.freeze({ csrfToken: csrf });
1011
+ const after = participantPageStart;
1012
+ const historyAfter = historyPageStart;
1013
+ controlRequest = attempt;
1014
+ syncComposer();
1015
+ let confirmed = false;
1016
+ el("notice").textContent = t("Zapisywanie zmiany…");
1017
+ try {
1018
+ const data = await request(path, { method: "POST", body: payload, csrfToken: attempt.csrfToken });
1019
+ if (stale(controlRequest, attempt, current)) return;
1020
+ if (!matches(data)) throw new Error("UNCONFIRMED_CONTROL");
1021
+ confirmed = true;
1022
+ if (updateRooms) await roomOptions(current);
1023
+ if (stale(controlRequest, attempt, current)) return;
1024
+ if (selectedRoom) await Promise.all([participants(current, after), history(current, historyAfter), roomState(current)]);
1025
+ if (stale(controlRequest, attempt, current)) return;
1026
+ controlsReady = true;
1027
+ el("notice").textContent = success(data);
1028
+ return data;
1029
+ } catch (error) {
1030
+ if (stale(controlRequest, attempt, current)) return;
1031
+ controlRequest = null;
1032
+ const result = confirmed
1033
+ ? t("Zapis {label} potwierdzony, ale odczyt stanu niedostępny.", { label: t(label) })
1034
+ : t("Zmiana {label} niepotwierdzona.", { label: t(label) });
1035
+ const detail = !confirmed && error.status !== 401 && error.status !== 403 ? refusal(error) : "";
1036
+ if (error.status === 401 || error.status === 403) {
1037
+ failed(error, current);
1038
+ el("notice").textContent = `${result} ${t("Dostęp wygasł lub został cofnięty. Zaloguj się ponownie.")}`;
1039
+ } else if (detail && PRESERVE_ON_REFUSAL.has(error.code)) {
1040
+ // These refusals cannot mask a revoked room or session scope.
1041
+ el("notice").textContent = `${result} ${detail}`;
1042
+ } else {
1043
+ invalidate();
1044
+ clearRoom();
1045
+ el("notice").textContent = detail
1046
+ ? `${result} ${detail} ${t("Odśwież stan przed następną decyzją.")}`
1047
+ : `${result} ${t("Odśwież stan przed następną decyzją; nie ponawiamy operacji automatycznie.")}`;
1048
+ }
1049
+ } finally {
1050
+ if (controlRequest === attempt) controlRequest = null;
1051
+ flushSessions();
1052
+ syncComposer();
1053
+ }
1054
+ }
1055
+
1056
+ function muteSession(session, muted) {
1057
+ if (access !== "operator" || !composerReady || !uuid(session) || typeof muted !== "boolean") return;
1058
+ return control(`/v1/sessions/${session}/mute`, { muted }, {
1059
+ matches: (data) => data.session_id === session && data.muted === muted,
1060
+ success: () => t("Potwierdzono zapis mute={muted} dla {session}. Lista pokazuje późniejszy odczyt; stop i Plan Mode pozostają niezależne.", { muted, session }),
1061
+ label: "mute",
1062
+ });
1063
+ }
1064
+
1065
+ // Operator only, through the existing login. The route is idempotent per call and carries no authority.
1066
+ function setPm(session, pm) {
1067
+ if (access !== "operator" || !composerReady || !uuid(session) || typeof pm !== "boolean") return;
1068
+ const targetRoom = selectedRoom;
1069
+ return control(`${roomPath(targetRoom)}/pm`, { session_id: session, pm }, {
1070
+ matches: (data) => data.room_id === targetRoom && (pm ? data.pm?.session_id === session : data.pm === null),
1071
+ success: () => pm
1072
+ ? t("Potwierdzono zapis: znacznik PM ma {session}. Znacznik nie nadaje uprawnień.", { session })
1073
+ : t("Potwierdzono zapis: znacznik PM zdjęty z {session}.", { session }),
1074
+ label: "znacznika PM",
1075
+ });
1076
+ }
1077
+
1078
+ const ROLE_LABELS = { pm: "Forgejo PM", github_pm: "GitHub PM", delivery_manager: "Delivery manager" };
1079
+ const ROLE_ORDER = ["pm", "github_pm", "delivery_manager"];
1080
+
1081
+ function formatAge(seconds) {
1082
+ if (!Number.isFinite(seconds) || seconds < 0) return "";
1083
+ if (seconds < 60) return `${seconds} s`;
1084
+ if (seconds < 3600) return `${Math.floor(seconds / 60)} min`;
1085
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)} h`;
1086
+ return `${Math.floor(seconds / 86400)} d`;
1087
+ }
1088
+
1089
+ function showView(next) {
1090
+ if (next !== "chat" && next !== "sessions") return;
1091
+ if (view === "chat" && next === "sessions") savedChatScroll = messageScrollTop();
1092
+ view = next;
1093
+ el("chat-view").hidden = next !== "chat";
1094
+ el("sessions-view").hidden = next !== "sessions";
1095
+ el("tab-chat").setAttribute("aria-selected", String(next === "chat"));
1096
+ el("tab-sessions").setAttribute("aria-selected", String(next === "sessions"));
1097
+ if (next === "chat" && savedChatScroll !== null) {
1098
+ setMessageScrollTop(savedChatScroll);
1099
+ savedChatScroll = null;
1100
+ }
1101
+ if (next === "sessions") requestSessions();
1102
+ }
1103
+
1104
+ function requestSessions() {
1105
+ if (!selectedRoom) return;
1106
+ // The request belongs to the room, not to the read that happened to be in flight when the operator
1107
+ // opened the tab: stopping or retrying a live refresh must not discard it.
1108
+ sessionsDeferred = { room: selectedRoom };
1109
+ flushSessions();
1110
+ }
1111
+
1112
+ async function flushSessions() {
1113
+ if (view !== "sessions" || !selectedRoom) {
1114
+ sessionsDeferred = null;
1115
+ return;
1116
+ }
1117
+ if (sessionsDeferred && sessionsDeferred.room !== selectedRoom) sessionsDeferred = null;
1118
+ if (busy()) return;
1119
+ if (sessionsLoading) {
1120
+ sessionsFlushPending = true;
1121
+ return;
1122
+ }
1123
+ // Nothing is owed when the table still belongs to this scope and no visit asked for a fresh read.
1124
+ if (!sessionsDeferred && sessionsPage !== null) return;
1125
+ const room = selectedRoom;
1126
+ const epoch = scopeEpoch;
1127
+ const painted = await loadSessions(room, epoch);
1128
+ if (painted) sessionsDeferred = null;
1129
+ }
1130
+
1131
+ async function loadSessions(room, epoch) {
1132
+ if (!selectedRoom || room !== selectedRoom || sessionsLoading) return false;
1133
+ sessionsLoading = true;
1134
+ let painted = false;
1135
+ let reported = false;
1136
+ try {
1137
+ reported = await read(async () => {
1138
+ const data = await request(`${roomPath(room)}/participants?limit=100`);
1139
+ // A harmless live-refresh restart bumps the generation; only a real scope change discards this read.
1140
+ if (room !== selectedRoom || epoch !== scopeEpoch) return;
1141
+ sessionsPage = data;
1142
+ renderSessions();
1143
+ painted = true;
1144
+ }, generation);
1145
+ } finally {
1146
+ sessionsLoading = false;
1147
+ if (reported) {
1148
+ // The failure already told the operator to refresh; enqueuing its own replacement here would
1149
+ // loop on the same failing endpoint, so the next attempt needs that explicit refresh.
1150
+ sessionsFlushPending = false;
1151
+ } else if (sessionsFlushPending) {
1152
+ sessionsFlushPending = false;
1153
+ flushSessions();
1154
+ }
1155
+ }
1156
+ return painted;
1157
+ }
1158
+
1159
+ async function loadMoreSessions() {
1160
+ if (!selectedRoom || !sessionsPage?.next_session_id || sessionsLoading || sessionsLoadingMore || busy()) return;
1161
+ const room = selectedRoom;
1162
+ const epoch = scopeEpoch;
1163
+ const basePage = sessionsPage;
1164
+ const after = basePage.next_session_id;
1165
+ sessionsLoadingMore = true;
1166
+ renderSessions();
1167
+ try {
1168
+ const query = new URLSearchParams({ limit: "100", after_session: after });
1169
+ const data = await request(`${roomPath(room)}/participants?${query}`);
1170
+ // Append only to the exact snapshot this request extended. A revisit of
1171
+ // Sessions may have replaced it while the request was in flight.
1172
+ if (room !== selectedRoom || epoch !== scopeEpoch || sessionsPage !== basePage) return;
1173
+ if (!Array.isArray(data.participants)) throw new Error("INVALID_RESPONSE");
1174
+ const seen = new Set(basePage.participants.map((person) => person.session_id));
1175
+ sessionsPage = {
1176
+ ...basePage,
1177
+ participants: [
1178
+ ...basePage.participants,
1179
+ ...data.participants.filter((person) => !seen.has(person.session_id)),
1180
+ ],
1181
+ next_session_id: data.next_session_id,
1182
+ roles: data.roles ?? basePage.roles,
1183
+ pm: data.pm ?? basePage.pm,
1184
+ };
1185
+ renderSessions();
1186
+ } catch (error) {
1187
+ // A failed later page is not a failed snapshot. Ignore it when a newer
1188
+ // snapshot replaced this one; keep access refusals fail-closed.
1189
+ if (room !== selectedRoom || epoch !== scopeEpoch || sessionsPage !== basePage) return;
1190
+ if (error.status === 401 || error.status === 403) {
1191
+ failed(error, generation);
1192
+ return;
1193
+ }
1194
+ el("notice").textContent = t("Nie udało się pobrać kolejnej strony sesji. Spróbuj ponownie.");
1195
+ } finally {
1196
+ sessionsLoadingMore = false;
1197
+ if (sessionsPage) renderSessions();
1198
+ }
1199
+ }
1200
+
1201
+ async function setRole(session, role, assigned) {
1202
+ if (access !== "operator" || busy() || !uuid(session) || !ROLE_ORDER.includes(role)) return;
1203
+ const targetRoom = selectedRoom;
1204
+ const label = ROLE_LABELS[role] ?? role;
1205
+ const result = await control(`${roomPath(targetRoom)}/roles`, { role, session_id: session, assigned }, {
1206
+ matches: (data) => data.room_id === targetRoom
1207
+ && (assigned ? data.roles?.[role]?.session_id === session : data.roles?.[role] === null),
1208
+ success: () => assigned
1209
+ ? t("Potwierdzono: {label} ma {session}. Znacznik nie nadaje uprawnień.", { label, session })
1210
+ : t("Potwierdzono: znacznik {label} zdjęty z {session}.", { label, session }),
1211
+ label: `znacznika ${label}`,
1212
+ });
1213
+ if (result && view === "sessions") requestSessions();
1214
+ }
1215
+
1216
+ function sessionCell(person) {
1217
+ const cell = document.createElement("td");
1218
+ const name = document.createElement("span");
1219
+ name.className = "session-name";
1220
+ name.append(bdi(sessionName(person)));
1221
+ cell.append(name, text("span", person.session_id, "session-id"));
1222
+ if (person.label && person.label !== person.session_id) {
1223
+ cell.append(text("span", person.label, "session-meta"));
1224
+ }
1225
+ return cell;
1226
+ }
1227
+
1228
+ function workCell(person) {
1229
+ const cell = document.createElement("td");
1230
+ const work = person.repositories && typeof person.repositories === "object" ? person.repositories : {};
1231
+ const forges = Object.entries(work).filter(([, repos]) => Array.isArray(repos) && repos.length > 0);
1232
+ if (!forges.length) {
1233
+ cell.append(text("span", "—", "session-meta"));
1234
+ return cell;
1235
+ }
1236
+ for (const [forge, repos] of forges) {
1237
+ cell.append(text("span", forge, "work-forge"));
1238
+ const list = document.createElement("ul");
1239
+ list.className = "work-list";
1240
+ for (const repo of repos.slice(0, 8)) {
1241
+ const item = document.createElement("li");
1242
+ item.append(bdi(repo));
1243
+ list.append(item);
1244
+ }
1245
+ if (repos.length > 8) list.append(text("li", `+${repos.length - 8}`, "session-meta"));
1246
+ cell.append(list);
1247
+ }
1248
+ return cell;
1249
+ }
1250
+
1251
+ function rolesCell(person, roles) {
1252
+ const cell = document.createElement("td");
1253
+ cell.className = "role-cell";
1254
+ for (const role of ROLE_ORDER) {
1255
+ const block = roles?.[role];
1256
+ if (block && block.session_id === person.session_id) {
1257
+ cell.append(text("span", ROLE_LABELS[role], `role-badge${role === "pm" ? " is-pm" : ""}`));
1258
+ }
1259
+ }
1260
+ if (!cell.childNodes.length) cell.append(text("span", "—", "session-meta"));
1261
+ if (access !== "operator") return cell;
1262
+ const details = document.createElement("details");
1263
+ details.className = "role-controls";
1264
+ details.append(text("summary", t("Zmień rolę")));
1265
+ for (const role of ROLE_ORDER) {
1266
+ const held = roles?.[role]?.session_id === person.session_id;
1267
+ const row = document.createElement("div");
1268
+ row.className = "role-row";
1269
+ row.append(text("span", ROLE_LABELS[role]));
1270
+ const button = document.createElement("button");
1271
+ button.type = "button";
1272
+ button.className = "role-session";
1273
+ button.dataset.role = role;
1274
+ button.disabled = busy() || !composerReady;
1275
+ button.textContent = held ? t("Zdejmij") : t("Nadaj");
1276
+ button.setAttribute("aria-label", `${held ? t("Zdejmij") : t("Nadaj")} ${ROLE_LABELS[role]}`);
1277
+ button.addEventListener("click", () => setRole(person.session_id, role, !held));
1278
+ row.append(button);
1279
+ details.append(row);
1280
+ }
1281
+ cell.append(details);
1282
+ return cell;
1283
+ }
1284
+
1285
+ function stateCell(person) {
1286
+ const cell = document.createElement("td");
1287
+ // Liveness and the observed native state are separate facts. A live lease
1288
+ // with `unknown` must not be rendered as a positive idle claim.
1289
+ const state = !person.online
1290
+ ? t("offline")
1291
+ : { busy: t("online, pracuje"), idle: t("online, bezczynna") }[person.native_state] ?? t("online, stan nieznany");
1292
+ cell.append(text("span", state, "state-line"));
1293
+ const flags = [];
1294
+ if (person.stopped) flags.push("stop");
1295
+ if (person.plan_mode) flags.push("Plan Mode");
1296
+ if (person.muted) flags.push(t("wyciszona"));
1297
+ if (flags.length) cell.append(text("span", flags.join(" · "), "state-line"));
1298
+ return cell;
1299
+ }
1300
+
1301
+ function laneCell(person) {
1302
+ const cell = document.createElement("td");
1303
+ if (!person.lane) {
1304
+ cell.append(text("span", "—", "session-meta"));
1305
+ return cell;
1306
+ }
1307
+ cell.append(bdi(person.lane));
1308
+ const age = formatAge(person.lane_age_seconds);
1309
+ if (age) cell.append(text("span", t("od {age}", { age }), "session-meta"));
1310
+ return cell;
1311
+ }
1312
+
1313
+ function activityCell(person) {
1314
+ const cell = document.createElement("td");
1315
+ cell.append(text("span", person.last_published_at ? displayTimestamp(person.last_published_at) : "—", "state-line"));
1316
+ const count = Number(person.messages_24h) || 0;
1317
+ cell.append(text("span", t("{count} w 24 h", { count }), "session-meta"));
1318
+ return cell;
1319
+ }
1320
+
1321
+ function prsCell(person) {
1322
+ const cell = document.createElement("td");
1323
+ const prs = Array.isArray(person.announced_prs) ? person.announced_prs : [];
1324
+ if (!prs.length) {
1325
+ cell.append(text("span", "—", "session-meta"));
1326
+ return cell;
1327
+ }
1328
+ const list = document.createElement("ul");
1329
+ list.className = "pr-list";
1330
+ for (const pr of prs.slice(0, 3)) {
1331
+ const item = document.createElement("li");
1332
+ item.append(text("bdi", `${pr.repository}#${pr.number}`, ""));
1333
+ list.append(item);
1334
+ }
1335
+ if (prs.length > 3) list.append(text("li", `+${prs.length - 3}`, "session-meta"));
1336
+ cell.append(list);
1337
+ return cell;
1338
+ }
1339
+
1340
+ function renderSessions() {
1341
+ if (!sessionsPage) return;
1342
+ const query = el("sessions-filter").value.trim().toLowerCase();
1343
+ const roles = sessionsPage.roles ?? { pm: sessionsPage.pm ?? null, github_pm: null, delivery_manager: null };
1344
+ const rows = Array.isArray(sessionsPage.participants) ? sessionsPage.participants : [];
1345
+ const ordered = [...rows].sort((a, b) => {
1346
+ if (a.online !== b.online) return a.online ? -1 : 1;
1347
+ return sessionName(a).localeCompare(sessionName(b), "pl");
1348
+ });
1349
+ const body = el("sessions-table").querySelector("tbody");
1350
+ body.replaceChildren();
1351
+ let shown = 0;
1352
+ for (const person of ordered) {
1353
+ const repositories = person.repositories && typeof person.repositories === "object" ? person.repositories : {};
1354
+ const search = [
1355
+ sessionName(person), sessionIdentity(person), person.session_id, person.harness ?? "", person.host ?? "",
1356
+ person.lane ?? "", ...Object.values(repositories).flat().filter((repo) => typeof repo === "string"),
1357
+ ].join(" ").toLowerCase();
1358
+ const row = document.createElement("tr");
1359
+ row.dataset.sessionId = person.session_id;
1360
+ if (query && !search.includes(query)) {
1361
+ row.hidden = true;
1362
+ } else {
1363
+ shown += 1;
1364
+ }
1365
+ row.append(
1366
+ sessionCell(person),
1367
+ (() => { const cell = document.createElement("td"); cell.append(text("span", person.harness ?? "—", "chip")); return cell; })(),
1368
+ (() => { const cell = document.createElement("td"); cell.append(text("span", person.host ?? "—", "")); return cell; })(),
1369
+ stateCell(person),
1370
+ laneCell(person),
1371
+ workCell(person),
1372
+ rolesCell(person, roles),
1373
+ activityCell(person),
1374
+ prsCell(person),
1375
+ );
1376
+ body.append(row);
1377
+ }
1378
+ if (!ordered.length) {
1379
+ const row = document.createElement("tr");
1380
+ row.className = "empty-row";
1381
+ const cell = document.createElement("td");
1382
+ cell.colSpan = 9;
1383
+ cell.textContent = t("Brak sesji w tym pokoju.");
1384
+ row.append(cell);
1385
+ body.append(row);
1386
+ }
1387
+ el("sessions-count").textContent = t("{shown} z {total}", { shown, total: rows.length });
1388
+ const note = el("sessions-note");
1389
+ const next = Boolean(sessionsPage.next_session_id);
1390
+ note.hidden = !next;
1391
+ note.textContent = next
1392
+ ? t("Wczytano {count} sesji. Filtr obejmuje wczytane wiersze; pobierz kolejną stronę, aby szukać dalej.", { count: rows.length })
1393
+ : "";
1394
+ const more = el("more-sessions");
1395
+ more.hidden = !next;
1396
+ more.disabled = sessionsLoadingMore || busy();
1397
+ }
1398
+
1399
+ el("create-room").addEventListener("submit", async (event) => {
1400
+ event.preventDefault();
1401
+ if (access !== "operator" || busy() || !controlsReady) return;
1402
+ const slug = el("room-slug").value;
1403
+ const label = el("room-label").value;
1404
+ if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(slug) || !label || [...label].length > 128 || /[\x00-\x1f\x7f]/.test(label)) {
1405
+ el("notice").textContent = t("Niepoprawny identyfikator lub nazwa pokoju.");
1406
+ return;
1407
+ }
1408
+ const result = await control("/v1/rooms", { slug, label }, {
1409
+ matches: (data) => uuid(data.id) && data.slug === slug && data.label === label,
1410
+ success: (data) => t("Pokój zapisany: {id}. Wybierz go na liście pokoi.", { id: data.id }),
1411
+ label: "pokoju",
1412
+ updateRooms: true,
1413
+ });
1414
+ if (result) { el("room-slug").value = el("room-label").value = ""; }
1415
+ });
1416
+
1417
+ el("join-room").addEventListener("submit", async (event) => {
1418
+ event.preventDefault();
1419
+ if (access !== "operator" || busy() || !composerReady) return;
1420
+ const session = el("member-session").value.trim().toLowerCase();
1421
+ const targetRoom = selectedRoom;
1422
+ if (!uuid(session)) { el("notice").textContent = t("Podaj dokładny UUID sesji."); return; }
1423
+ const result = await control(`${roomPath(targetRoom)}/memberships`, { session_id: session }, {
1424
+ matches: (data) => data.room_id === targetRoom && data.session_id === session,
1425
+ success: () => t("Członkostwo zapisane: {session}. Uprawnienia poświadczenia nie zostały rozszerzone.", { session }),
1426
+ label: "członkostwa",
1427
+ });
1428
+ if (result) el("member-session").value = "";
1429
+ });
1430
+
1431
+ // Reads the room chosen in the list. `saved` reports a write that this read follows;
1432
+ // `keep` re-reads the same room without discarding its draft.
1433
+ async function room(saved = "", keep = false) {
1434
+ const current = invalidate();
1435
+ selectedRoom = el("room").value;
1436
+ clearRoom();
1437
+ if (!keep) clearDraft();
1438
+ if (!selectedRoom) {
1439
+ stopLive();
1440
+ controlsReady = true;
1441
+ syncComposer();
1442
+ return;
1443
+ }
1444
+ el("notice").textContent = saved ? `${saved} Odczyt pokoju…` : t("Odczyt pokoju…");
1445
+ await read(async () => {
1446
+ await Promise.all([participants(current), history(current), roomState(current)]);
1447
+ if (current === generation) {
1448
+ el("viewer").hidden = false;
1449
+ composerReady = controlsReady = true;
1450
+ syncComposer();
1451
+ // The composer changes the list height; keep the newest page at its true bottom.
1452
+ if (historyPageStart === null) scrollMessagesToBottom();
1453
+ el("notice").textContent = saved || t("Migawka historii. Odczyt nie potwierdza przetworzenia wiadomości.");
1454
+ if (view === "sessions") requestSessions();
1455
+ resumeLive();
1456
+ }
1457
+ }, current, { saved });
1458
+ }
1459
+
1460
+ async function roomOptions(current) {
1461
+ const data = await request("/v1/rooms");
1462
+ if (current !== generation) return;
1463
+ const empty = text("option", t("Wybierz pokój"));
1464
+ empty.value = "";
1465
+ el("room").replaceChildren(empty, ...data.rooms.map((r) => {
1466
+ const option = text("option", r.label && r.label !== r.slug ? `${r.label} — ${r.slug}` : r.slug);
1467
+ option.value = r.id;
1468
+ option.dataset.slug = r.slug;
1469
+ option.dataset.label = r.label || r.slug;
1470
+ option.title = `${r.label || r.slug} (${r.slug})`;
1471
+ return option;
1472
+ }));
1473
+ if (selectedRoom && !data.rooms.some((r) => r.id === selectedRoom)) {
1474
+ // Never move the operator, or a draft written for that room, into another room unasked.
1475
+ selectedRoom = "";
1476
+ clearRoom();
1477
+ el("notice").textContent = t("Wybrany pokój nie jest już dostępny. Wybierz pokój z listy.") +
1478
+ (composerDraft() ? " Szkic został zachowany." : "");
1479
+ }
1480
+ el("room").value = selectedRoom;
1481
+ return data.rooms;
1482
+ }
1483
+
1484
+ // Initial session loading may choose the first room. A refresh preserves the operator's room;
1485
+ // a room that disappeared from scope is reported and never replaced by another one unasked.
1486
+ async function rooms(current, { initial = false, keepDraft = false } = {}) {
1487
+ const hadSelection = Boolean(selectedRoom);
1488
+ const available = await roomOptions(current);
1489
+ if (current !== generation) return;
1490
+ if (!available.length) {
1491
+ clearRoom();
1492
+ controlsReady = true;
1493
+ syncComposer();
1494
+ el("notice").textContent = access === "operator"
1495
+ ? t("Brak dostępnych pokoi. Możesz utworzyć pokój.") : t("Brak dostępnych pokoi.");
1496
+ return;
1497
+ }
1498
+ if (selectedRoom) {
1499
+ await room("", keepDraft);
1500
+ return;
1501
+ }
1502
+ if (initial) {
1503
+ el("room").value = available[0].id;
1504
+ await room();
1505
+ return;
1506
+ }
1507
+ controlsReady = true;
1508
+ syncComposer();
1509
+ if (!hadSelection)
1510
+ el("notice").textContent = t("Wybierz pokój, aby otworzyć rozmowę. Szkic pozostaje w pamięci tej strony.");
1511
+ }
1512
+
1513
+ function stopLive(message = t("Zdarzenia na żywo wyłączone.")) {
1514
+ const owner = live;
1515
+ live = null;
1516
+ if (owner) {
1517
+ owner.source?.close();
1518
+ clearTimeout(owner.timer);
1519
+ owner.controller.abort();
1520
+ if (owner.loading) invalidate();
1521
+ }
1522
+ el("live-toggle").textContent = t("Włącz zdarzenia na żywo");
1523
+ el("live-status").textContent = message;
1524
+ el("live-count").textContent = "";
1525
+ el("live-indicator").dataset.live = "off";
1526
+ }
1527
+
1528
+ function scheduleLive(owner, delay = 500) {
1529
+ if (!owner || live !== owner || !owner.dirty || owner.loading || owner.timer !== null || reads || writesBusy()) return;
1530
+ owner.timer = setTimeout(() => { owner.timer = null; refreshLive(owner); }, delay);
1531
+ }
1532
+
1533
+ function disconnectLive(owner, resync = false) {
1534
+ if (live !== owner) return;
1535
+ owner.source?.close();
1536
+ owner.source = null;
1537
+ owner.resync ||= resync;
1538
+ owner.dirty = true;
1539
+ // Fence old reads without aborting an outstanding, immutable mutation.
1540
+ invalidate(false);
1541
+ scopeEpoch += 1;
1542
+ clearSnapshot();
1543
+ if (pending) el("viewer").hidden = true;
1544
+ if (controlRequest) el("notice").textContent = t("Zmiana administracyjna niepotwierdzona; wymagany świeży odczyt.");
1545
+ el("live-indicator").dataset.live = "off";
1546
+ el("live-status").textContent = resync ? t("Wymagana resynchronizacja historii i zakresu.") : t("Połączenie przerwane; ponowny odczyt przed połączeniem.");
1547
+ scheduleLive(owner, 1000);
1548
+ }
1549
+
1550
+ // The server ends every stream after a bounded lifetime. Reconnect from the retained cursor, after the
1551
+ // usual binding and scope revalidation, but keep showing the last snapshot until that read replaces it.
1552
+ function reconnectLive(owner) {
1553
+ if (live !== owner) return;
1554
+ owner.source?.close();
1555
+ owner.source = null;
1556
+ owner.dirty = true;
1557
+ el("live-indicator").dataset.live = "off";
1558
+ el("live-status").textContent = t("Strumień zakończony; ponowne łączenie od zapamiętanego kursora.");
1559
+ scheduleLive(owner, 1000);
1560
+ }
1561
+
1562
+ function connectLive(owner) {
1563
+ const source = new EventSource(`/v1/events?after=${owner.cursor}`);
1564
+ owner.source = source;
1565
+ owner.opened = false;
1566
+ source.onopen = () => {
1567
+ if (live === owner && owner.source === source) {
1568
+ owner.opened = true;
1569
+ el("live-indicator").dataset.live = "on";
1570
+ el("live-status").textContent = t("Połączenie zdarzeń aktywne; odczyty nie wysyłają ACK.");
1571
+ }
1572
+ };
1573
+ source.onerror = () => {
1574
+ if (live !== owner || owner.source !== source) return;
1575
+ // A stream that opened and is being re-established ended normally; a refused or never-opened one did not.
1576
+ if (owner.opened && source.readyState === EventSource.CONNECTING) reconnectLive(owner);
1577
+ else disconnectLive(owner);
1578
+ };
1579
+ // `state` and `thread` are invalidations like the rest: the refresh reads the tables, never the event body.
1580
+ for (const kind of ["message", "receipt", "control", "state", "thread"]) source.addEventListener(kind, (event) => {
1581
+ if (live !== owner || owner.source !== source) return;
1582
+ try {
1583
+ const data = JSON.parse(event.data);
1584
+ // ID-less errors can inherit the previous EventSource lastEventId.
1585
+ if (data.error) {
1586
+ disconnectLive(owner, ["ROOM_SCOPE_CHANGED", "CURSOR_EXPIRED"].includes(data.error.code));
1587
+ return;
1588
+ }
1589
+ if (!cursorValid(event.lastEventId) || !uuid(data.room_id)) throw new Error("INVALID_EVENT");
1590
+ if (BigInt(event.lastEventId) <= BigInt(owner.cursor)) return;
1591
+ owner.cursor = event.lastEventId;
1592
+ if (BigInt(event.lastEventId) <= BigInt(owner.seen.get(data.room_id) ?? "0")) return;
1593
+ owner.seen.set(data.room_id, event.lastEventId);
1594
+ owner.received += 1;
1595
+ el("live-count").textContent = t("Odebrane zdarzenia: {received} · kursor: {cursor}", {
1596
+ received: owner.received, cursor: owner.cursor,
1597
+ });
1598
+ if (data.room_id === selectedRoom) { owner.dirty = true; scheduleLive(owner); }
1599
+ } catch {
1600
+ disconnectLive(owner);
1601
+ stopLive(t("Niepoprawna ramka zdarzeń. Odśwież widok ręcznie."));
1602
+ syncComposer();
1603
+ }
1604
+ });
1605
+ }
1606
+
1607
+ async function refreshLive(owner) {
1608
+ if (live !== owner || reads || writesBusy()) { scheduleLive(owner); return; }
1609
+ owner.loading = true;
1610
+ owner.dirty = false;
1611
+ const current = invalidate();
1612
+ syncComposer();
1613
+ let delay = 500;
1614
+ try {
1615
+ const session = await request("/v1/browser/session", { signal: owner.controller.signal });
1616
+ if (stale(live, owner, current)) return;
1617
+ if (session.principal_id !== owner.principal || session.csrf_token !== owner.csrf || session.access !== access)
1618
+ throw Object.assign(new Error("BINDING_CHANGED"), { status: 401 });
1619
+ const available = await roomOptions(current);
1620
+ if (stale(live, owner, current)) return;
1621
+ const scope = available.map((r) => r.id).sort().join(",");
1622
+ if (scope !== owner.rooms) { owner.rooms = scope; owner.resync = true; }
1623
+ if (!selectedRoom) {
1624
+ stopLive(available.length ? t("Nie wybrano pokoju; zdarzenia wyłączone.") : t("Brak dostępnych pokoi; zdarzenia wyłączone."));
1625
+ controlsReady = true;
1626
+ return;
1627
+ }
1628
+ if (owner.resync) historyPageStart = participantPageStart = null;
1629
+ await Promise.all([history(current, historyPageStart), participants(current, participantPageStart), roomState(current)]);
1630
+ if (stale(live, owner, current)) return;
1631
+ if (BigInt(owner.cursor) < BigInt(historyFloor)) owner.resync = true;
1632
+ if (owner.resync) {
1633
+ owner.source?.close();
1634
+ owner.source = null;
1635
+ owner.cursor = historyFloor;
1636
+ owner.resync = false;
1637
+ el("live-status").textContent = t("Odtworzono zachowaną historię; wznawianie zdarzeń.");
1638
+ }
1639
+ // Detect HTTP cursor refusals before EventSource, whose error hides the status.
1640
+ if (!owner.source) await request(`${roomPath()}/history?after=${owner.cursor}&limit=1`);
1641
+ if (stale(live, owner, current)) return;
1642
+ composerReady = controlsReady = true;
1643
+ el("viewer").hidden = false;
1644
+ owner.backoff = 1000;
1645
+ if (!owner.source) connectLive(owner);
1646
+ } catch (error) {
1647
+ if (stale(live, owner, current)) return;
1648
+ if (error.status === 401 || error.status === 403) {
1649
+ stopLive();
1650
+ lock();
1651
+ el("notice").textContent = t("Sesja lub zakres zmieniły się. Zaloguj się ponownie; nie przyjmujemy innego powiązania automatycznie.");
1652
+ } else if (error.status === 422) {
1653
+ disconnectLive(owner);
1654
+ stopLive(t("Niepoprawny kursor. Odśwież widok ręcznie."));
1655
+ } else {
1656
+ if (error.status === 410) owner.resync = true;
1657
+ disconnectLive(owner, owner.resync);
1658
+ delay = owner.backoff;
1659
+ owner.backoff = Math.min(10000, owner.backoff * 2);
1660
+ }
1661
+ } finally {
1662
+ owner.loading = false;
1663
+ flushSessions();
1664
+ scheduleLive(owner, delay);
1665
+ syncComposer();
1666
+ }
1667
+ }
1668
+
1669
+ function startLive() {
1670
+ if (live || busy() || !composerReady) return false;
1671
+ live = {
1672
+ // The history read just rendered is current up to this event position; nothing older is replayed.
1673
+ principal, csrf, cursor: historyEventCursor,
1674
+ rooms: Array.from(el("room").options, (option) => option.value).filter(Boolean).sort().join(","), received: 0,
1675
+ source: null, opened: false, timer: null, controller: new AbortController(), seen: new Map(),
1676
+ loading: false, dirty: true, resync: false, backoff: 1000,
1677
+ };
1678
+ el("live-toggle").textContent = t("Wyłącz zdarzenia na żywo");
1679
+ el("live-status").textContent = t("Sprawdzanie powiązania i zakresu…");
1680
+ scheduleLive(live, 0);
1681
+ return true;
1682
+ }
1683
+
1684
+ // A remembered opt-in starts the same bound, revalidated path as the toggle once a room snapshot is in place.
1685
+ // Only the toggle changes the choice: logout, expiry, a room switch or a stream error never clear it.
1686
+ function resumeLive() {
1687
+ if (!live && csrf !== null && liveWanted) startLive();
1688
+ }
1689
+
1690
+ el("live-toggle").addEventListener("click", () => {
1691
+ if (live) { rememberLive(false); stopLive(); syncComposer(); return; }
1692
+ if (startLive()) rememberLive(true);
1693
+ });
1694
+
1695
+ // Initial load selects the first authorized room. A refresh revalidates the session and scope
1696
+ // without moving the operator to another room or discarding the draft.
1697
+ async function start({ preserve = false } = {}) {
1698
+ if (!preserve) {
1699
+ lock();
1700
+ } else {
1701
+ stopLive();
1702
+ invalidate();
1703
+ clearState();
1704
+ composerReady = controlsReady = false;
1705
+ syncComposer();
1706
+ }
1707
+ el("login").hidden = true;
1708
+ el("login-view").hidden = true;
1709
+ const current = generation;
1710
+ const reported = await read(async () => {
1711
+ const data = await request("/v1/browser/session");
1712
+ if (current !== generation) return;
1713
+ acceptSession(data);
1714
+ showSession();
1715
+ await rooms(current, { initial: !preserve, keepDraft: preserve });
1716
+ }, current, { denied: t("Brak aktywnej sesji. Zaloguj się tokenem operatora lub podglądu.") });
1717
+ if (reported) {
1718
+ el("login").hidden = csrf !== null;
1719
+ el("login-view").hidden = csrf !== null;
1720
+ }
1721
+ }
1722
+
1723
+ el("login").addEventListener("submit", async (event) => {
1724
+ event.preventDefault();
1725
+ const token = el("token").value;
1726
+ el("token").value = ""; // Never retain the entered credential in the DOM or browser storage.
1727
+ const current = invalidate();
1728
+ el("login").hidden = true;
1729
+ el("login-view").hidden = true;
1730
+ el("notice").textContent = t("Logowanie…");
1731
+ const reported = await read(async () => {
1732
+ const challenge = await request("/v1/login");
1733
+ if (current !== generation) return;
1734
+ const data = await request("/v1/login", { method: "POST", body: { token }, csrfToken: challenge.csrf_token });
1735
+ if (current !== generation) return;
1736
+ const session = await request("/v1/browser/session");
1737
+ if (current !== generation) return;
1738
+ if (session.csrf_token !== data.csrf_token || !["operator", "viewer"].includes(data.access)
1739
+ || session.access !== data.access) {
1740
+ const error = new Error("SESSION_CHANGED");
1741
+ error.status = 401;
1742
+ throw error;
1743
+ }
1744
+ acceptSession(session);
1745
+ showSession();
1746
+ await rooms(current, { initial: true });
1747
+ }, current, { denied: t("Logowanie odrzucone. Sprawdź token i spróbuj ponownie.") });
1748
+ if (reported) {
1749
+ el("login").hidden = csrf !== null;
1750
+ el("login-view").hidden = csrf !== null;
1751
+ }
1752
+ });
1753
+
1754
+ el("logout").addEventListener("click", async () => {
1755
+ if (!mayDiscard()) return;
1756
+ const oldCsrf = csrf;
1757
+ lock(); // Hide private data immediately, even if the network is unavailable.
1758
+ const current = generation;
1759
+ el("login").hidden = true;
1760
+ el("notice").textContent = t("Wylogowywanie…");
1761
+ try {
1762
+ await request("/v1/logout", { method: "POST", body: {}, csrfToken: oldCsrf });
1763
+ if (current !== generation) return;
1764
+ el("notice").textContent = t("Wylogowano.");
1765
+ el("login").hidden = false;
1766
+ } catch (error) {
1767
+ if (current !== generation) return;
1768
+ if (error.status === 401) {
1769
+ el("notice").textContent = t("Sesja nie jest już aktywna.");
1770
+ el("login").hidden = false;
1771
+ } else {
1772
+ csrf = oldCsrf;
1773
+ el("logout").hidden = false;
1774
+ el("notice").textContent = t("Wylogowanie niepotwierdzone. Ponów wylogowanie; nie zamykaj tego okna jako potwierdzenia.");
1775
+ }
1776
+ }
1777
+ });
1778
+
1779
+ el("room").addEventListener("change", () => {
1780
+ if (busy() || !mayDiscard()) { el("room").value = selectedRoom; return; }
1781
+ room();
1782
+ });
1783
+ el("refresh").addEventListener("click", async () => {
1784
+ if (busy()) return;
1785
+ // A refresh always revalidates in place. When revocation has already cleared the
1786
+ // selection, the preserving path still keeps the draft and never chooses a room.
1787
+ await start({ preserve: true });
1788
+ if (view === "sessions") requestSessions();
1789
+ });
1790
+ el("tab-chat").addEventListener("click", () => showView("chat"));
1791
+ el("tab-sessions").addEventListener("click", () => showView("sessions"));
1792
+ el("sessions-filter").addEventListener("input", renderSessions);
1793
+ el("more-sessions").addEventListener("click", loadMoreSessions);
1794
+ el("thread-filter").addEventListener("submit", (event) => {
1795
+ event.preventDefault();
1796
+ const value = el("thread").value.trim();
1797
+ filterThread((uuid(value.toLowerCase()) ? value.toLowerCase() : value) || null);
1798
+ });
1799
+ el("all-history").addEventListener("click", () => filterThread(null));
1800
+ el("latest").addEventListener("click", latestHistory);
1801
+ for (const [id, load, cursor] of [
1802
+ ["more-messages", history, () => historyCursor],
1803
+ ["more-participants", participants, () => participantCursor],
1804
+ ]) el(id).addEventListener("click", async () => {
1805
+ const page = cursor();
1806
+ if (page === null || busy()) return;
1807
+ const current = generation;
1808
+ el(id).disabled = true;
1809
+ await read(() => load(current, page), current);
1810
+ if (id === "more-messages") {
1811
+ if (mobileLayout()) el("messages").scrollIntoView({ block: "start" });
1812
+ else el("messages").scrollTop = 0;
1813
+ }
1814
+ syncComposer();
1815
+ });
1816
+
1817
+ async function sendPending() {
1818
+ if (!pending || sending) return;
1819
+ const attempt = pending;
1820
+ sending = true;
1821
+ syncComposer();
1822
+ el("write-status").textContent = t("Wysyłanie…");
1823
+ try {
1824
+ const data = await request(attempt.path, attempt.options);
1825
+ if (pending !== attempt) return;
1826
+ const expected = attempt.options.body;
1827
+ if (!uuid(data.id) || !uuid(data.thread_id) || data.sender?.principal_id !== attempt.principal ||
1828
+ data.sender?.session_id !== null || data.room_id !== attempt.room || data.body !== expected.body || data.kind !== expected.kind ||
1829
+ data.reply_to !== expected.reply_to || !Array.isArray(data.recipients) ||
1830
+ JSON.stringify([...data.recipients].sort()) !== JSON.stringify(expected.recipients) ||
1831
+ (expected.thread_id !== null && data.thread_id !== expected.thread_id) ||
1832
+ (expected.ref_key !== undefined && data.thread_ref_key !== expected.ref_key))
1833
+ throw new Error("UNCONFIRMED_RECEIPT");
1834
+ pending = null;
1835
+ clearDraft();
1836
+ // The message is committed: report it before the read-back, which can only add to that report.
1837
+ const saved = t("Zapisano {id}. To nie jest potwierdzenie wybudzenia ani ACK.", { id: data.id });
1838
+ el("notice").textContent = saved;
1839
+ await room(saved);
1840
+ scrollMessagesToBottom();
1841
+ } catch (error) {
1842
+ if (pending !== attempt) return;
1843
+ // Even a refusal on a retry cannot disprove an earlier committed attempt.
1844
+ el("write-status").textContent = t("Zapis niepotwierdzony. Ponów tę samą próbę lub sprawdź historię w osobnym oknie.");
1845
+ if (error.status === 401 || error.status === 403) {
1846
+ clearRoom();
1847
+ el("viewer").hidden = true;
1848
+ el("body").value = "";
1849
+ el("write-status").textContent += " " + t("Brak dostępu; nie zmieniamy tożsamości ani klucza próby.");
1850
+ }
1851
+ } finally {
1852
+ sending = false;
1853
+ flushSessions();
1854
+ syncComposer();
1855
+ }
1856
+ }
1857
+
1858
+ el("composer").addEventListener("submit", (event) => {
1859
+ event.preventDefault();
1860
+ if (access !== "operator" || busy() || !composerReady) return;
1861
+ const body = el("body").value;
1862
+ const kind = replyTarget ? "reply" : el("kind").value;
1863
+ if (!body || body.includes("\u0000") || new TextEncoder().encode(body).length > 16384) {
1864
+ el("notice").textContent = t("Treść musi zawierać od 1 do 16384 bajtów UTF-8, bez NUL.");
1865
+ return;
1866
+ }
1867
+ // Empty replies otherwise implicitly address the parent sender on the server.
1868
+ if ((["question", "consultation"].includes(kind) || replyTarget?.senderSession) && !targets.size) {
1869
+ el("notice").textContent = t("Wybierz konkretnego odbiorcę.");
1870
+ return;
1871
+ }
1872
+ const refKey = el("ref-key").value.trim();
1873
+ if (refKey && (replyTarget || ["question", "consultation"].includes(kind) || !REF_KEY.test(refKey))) {
1874
+ el("notice").textContent = t("Niepoprawny klucz wątku albo rodzaj wiadomości, który go nie przyjmuje.");
1875
+ return;
1876
+ }
1877
+ const key = crypto.randomUUID();
1878
+ pending = Object.freeze({
1879
+ principal, room: selectedRoom, path: `${roomPath()}/messages`,
1880
+ options: Object.freeze({ method: "POST", key, csrfToken: csrf,
1881
+ body: Object.freeze({ body, kind, recipients: Object.freeze([...targets.keys()].sort()),
1882
+ thread_id: replyTarget?.thread_id ?? null, reply_to: replyTarget?.id ?? null,
1883
+ ...(refKey ? { ref_key: refKey } : {}) }),
1884
+ }),
1885
+ });
1886
+ el("write-key").textContent = t("Klucz: {key} · pokój: {room}", { key, room: selectedRoom });
1887
+ sendPending();
1888
+ });
1889
+ el("kind").addEventListener("change", () => {
1890
+ // A question or consultation cannot carry a thread key. Clear an existing one instead of
1891
+ // leaving a disabled but submitted value that the server would refuse.
1892
+ if (QUESTION_KINDS.has(el("kind").value) && el("ref-key").value) {
1893
+ el("ref-key").value = "";
1894
+ el("notice").textContent = t("Usunięto klucz wątku: pytanie i konsultacja nie przyjmują klucza wątku.");
1895
+ }
1896
+ syncComposer();
1897
+ });
1898
+ el("retry-write").addEventListener("click", sendPending);
1899
+ el("abandon-write").addEventListener("click", () => {
1900
+ if (sending || !mayDiscard()) return;
1901
+ pending = null;
1902
+ start(); // Revalidate scope before allowing another publication.
1903
+ });
1904
+ el("clear-draft").addEventListener("click", () => { if (!writesBusy() && mayDiscard()) clearDraft(); });
1905
+ el("clear-targets").addEventListener("click", () => { if (!writesBusy()) { targets.clear(); syncComposer(); } });
1906
+ el("roster-filter").addEventListener("input", applyRosterFilter);
1907
+ let languageUnload = false;
1908
+ window.agentChatMayDiscardForLanguage = () => {
1909
+ if (!writesBusy() && !hasDraft()) return true;
1910
+ if (!mayDiscard()) return false;
1911
+ languageUnload = true;
1912
+ return true;
1913
+ };
1914
+ window.addEventListener("beforeunload", (event) => {
1915
+ if (!languageUnload && (writesBusy() || hasDraft())) { event.preventDefault(); event.returnValue = ""; }
1916
+ });
1917
+ window.addEventListener("pagehide", lock);
1918
+ // pagehide has already locked the page, so a bfcache restore reloads like a first load: it selects a room
1919
+ // and holds no draft. Only the in-page Refresh control preserves the room and the draft.
1920
+ window.addEventListener("pageshow", (event) => { if (event.persisted) start(); });
1921
+ start();
1922
+ })();