@songsid/agend 2.4.0-beta.13 → 2.4.0-beta.14

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 (172) hide show
  1. package/dist/agent-endpoint.js +28 -6
  2. package/dist/agent-endpoint.js.map +1 -1
  3. package/dist/backend/claude-code.d.ts +9 -0
  4. package/dist/backend/claude-code.js +60 -4
  5. package/dist/backend/claude-code.js.map +1 -1
  6. package/dist/backend/grok.js +11 -0
  7. package/dist/backend/grok.js.map +1 -1
  8. package/dist/backend/types.d.ts +3 -0
  9. package/dist/backend/types.js.map +1 -1
  10. package/dist/backend-availability.d.ts +1 -16
  11. package/dist/backend-availability.js +2 -91
  12. package/dist/backend-availability.js.map +1 -1
  13. package/dist/backend-version-static.d.ts +15 -0
  14. package/dist/backend-version-static.js +95 -0
  15. package/dist/backend-version-static.js.map +1 -0
  16. package/dist/build-provenance.json +1 -1
  17. package/dist/channel/adapters/telegram.js +3 -1
  18. package/dist/channel/adapters/telegram.js.map +1 -1
  19. package/dist/channel/mcp-server.js +18 -1
  20. package/dist/channel/mcp-server.js.map +1 -1
  21. package/dist/channel/tool-router.d.ts +4 -0
  22. package/dist/channel/tool-router.js +43 -19
  23. package/dist/channel/tool-router.js.map +1 -1
  24. package/dist/classic-channel-manager.d.ts +3 -0
  25. package/dist/classic-channel-manager.js +18 -0
  26. package/dist/classic-channel-manager.js.map +1 -1
  27. package/dist/classic-cli-guard.d.ts +66 -0
  28. package/dist/classic-cli-guard.js +209 -0
  29. package/dist/classic-cli-guard.js.map +1 -0
  30. package/dist/cli-audited.js +7 -5
  31. package/dist/cli-audited.js.map +1 -1
  32. package/dist/config-validator.js +3 -0
  33. package/dist/config-validator.js.map +1 -1
  34. package/dist/contact-auth-api.d.ts +16 -0
  35. package/dist/contact-auth-api.js +78 -0
  36. package/dist/contact-auth-api.js.map +1 -0
  37. package/dist/contact-auth-files.d.ts +6 -0
  38. package/dist/contact-auth-files.js +29 -0
  39. package/dist/contact-auth-files.js.map +1 -0
  40. package/dist/contact-auth-policy.d.ts +75 -0
  41. package/dist/contact-auth-policy.js +23 -0
  42. package/dist/contact-auth-policy.js.map +1 -0
  43. package/dist/contact-auth-service.d.ts +32 -0
  44. package/dist/contact-auth-service.js +99 -0
  45. package/dist/contact-auth-service.js.map +1 -0
  46. package/dist/contact-auth-store.d.ts +75 -0
  47. package/dist/contact-auth-store.js +295 -0
  48. package/dist/contact-auth-store.js.map +1 -0
  49. package/dist/contact-auth-types.d.ts +170 -0
  50. package/dist/contact-auth-types.js +7 -0
  51. package/dist/contact-auth-types.js.map +1 -0
  52. package/dist/daemon.d.ts +8 -0
  53. package/dist/daemon.js +93 -4
  54. package/dist/daemon.js.map +1 -1
  55. package/dist/delivery-outbox.d.ts +6 -0
  56. package/dist/delivery-outbox.js +19 -0
  57. package/dist/delivery-outbox.js.map +1 -1
  58. package/dist/fleet-manager.d.ts +40 -0
  59. package/dist/fleet-manager.js +429 -22
  60. package/dist/fleet-manager.js.map +1 -1
  61. package/dist/general-knowledge/skills/concepts/SKILL.md +18 -0
  62. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +5 -0
  63. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +28 -0
  64. package/dist/general-knowledge/skills/hub/SKILL.md +6 -0
  65. package/dist/hub/audit/index.d.ts +3 -1
  66. package/dist/hub/audit/index.js +35 -3
  67. package/dist/hub/audit/index.js.map +1 -1
  68. package/dist/hub/catalog.d.ts +8 -0
  69. package/dist/hub/catalog.js +39 -4
  70. package/dist/hub/catalog.js.map +1 -1
  71. package/dist/hub/compose/server.d.ts +2 -0
  72. package/dist/hub/compose/server.js +11 -1
  73. package/dist/hub/compose/server.js.map +1 -1
  74. package/dist/hub/directory/directory.js +5 -2
  75. package/dist/hub/directory/directory.js.map +1 -1
  76. package/dist/hub/directory/types.d.ts +5 -1
  77. package/dist/hub/directory/types.js.map +1 -1
  78. package/dist/hub/group-policy/resources.d.ts +1 -1
  79. package/dist/hub/http/compose.d.ts +2 -0
  80. package/dist/hub/http/compose.js +123 -6
  81. package/dist/hub/http/compose.js.map +1 -1
  82. package/dist/hub/http/deps.d.ts +2 -0
  83. package/dist/hub/http/schema.js +6 -1
  84. package/dist/hub/http/schema.js.map +1 -1
  85. package/dist/hub/invitations.js +15 -7
  86. package/dist/hub/invitations.js.map +1 -1
  87. package/dist/hub/roles/cutover-inventory.d.ts +3 -0
  88. package/dist/hub/roles/cutover-inventory.js +20 -4
  89. package/dist/hub/roles/cutover-inventory.js.map +1 -1
  90. package/dist/hub/roles/cutover-marker.d.ts +18 -2
  91. package/dist/hub/roles/cutover-marker.js +6 -2
  92. package/dist/hub/roles/cutover-marker.js.map +1 -1
  93. package/dist/hub/room-agent-discovery-model.d.ts +29 -0
  94. package/dist/hub/room-agent-discovery-model.js +33 -0
  95. package/dist/hub/room-agent-discovery-model.js.map +1 -0
  96. package/dist/hub/room-agent-discovery.d.ts +14 -0
  97. package/dist/hub/room-agent-discovery.js +65 -0
  98. package/dist/hub/room-agent-discovery.js.map +1 -0
  99. package/dist/hub/room-agent-requests.d.ts +71 -0
  100. package/dist/hub/room-agent-requests.js +377 -0
  101. package/dist/hub/room-agent-requests.js.map +1 -0
  102. package/dist/hub/rooms/directory.d.ts +13 -0
  103. package/dist/hub/rooms/directory.js +12 -3
  104. package/dist/hub/rooms/directory.js.map +1 -1
  105. package/dist/hub/rooms/schema.d.ts +5 -0
  106. package/dist/hub/rooms/schema.js +9 -0
  107. package/dist/hub/rooms/schema.js.map +1 -1
  108. package/dist/hub/rooms/service.d.ts +43 -19
  109. package/dist/hub/rooms/service.js +67 -11
  110. package/dist/hub/rooms/service.js.map +1 -1
  111. package/dist/hub/rooms/types.d.ts +1 -1
  112. package/dist/instance-lifecycle.d.ts +3 -1
  113. package/dist/instance-lifecycle.js +4 -1
  114. package/dist/instance-lifecycle.js.map +1 -1
  115. package/dist/locale.js +28 -4
  116. package/dist/locale.js.map +1 -1
  117. package/dist/needs-you-hub.d.ts +1 -0
  118. package/dist/needs-you-hub.js +6 -0
  119. package/dist/needs-you-hub.js.map +1 -1
  120. package/dist/needs-you.d.ts +10 -2
  121. package/dist/needs-you.js.map +1 -1
  122. package/dist/outbound-handlers.d.ts +9 -0
  123. package/dist/outbound-handlers.js +46 -10
  124. package/dist/outbound-handlers.js.map +1 -1
  125. package/dist/runtime-cli-install.js +7 -7
  126. package/dist/runtime-cli-install.js.map +1 -1
  127. package/dist/topic-commands.d.ts +1 -1
  128. package/dist/topic-commands.js +4 -6
  129. package/dist/topic-commands.js.map +1 -1
  130. package/dist/ui/agent-details-settings.js +7 -5
  131. package/dist/ui/contact-auth-client.js +48 -0
  132. package/dist/ui/contact-auth-strings.js +164 -0
  133. package/dist/ui/contact-authorizations.js +125 -0
  134. package/dist/ui/contact-needs.js +84 -0
  135. package/dist/ui/contact-permissions.js +193 -0
  136. package/dist/ui/contact-ticket-badge.js +54 -0
  137. package/dist/ui/hub-client.js +30 -7
  138. package/dist/ui/hub-invitations.js +5 -1
  139. package/dist/ui/hub-room-new.js +10 -3
  140. package/dist/ui/hub-room-owner-requests-strings.js +114 -0
  141. package/dist/ui/hub-room-owner-requests.js +264 -0
  142. package/dist/ui/hub-room-pins.js +43 -0
  143. package/dist/ui/hub-room-settings.js +11 -2
  144. package/dist/ui/hub-room-strings.js +3 -0
  145. package/dist/ui/hub-room-thread.js +47 -5
  146. package/dist/ui/panel-chat.js +2 -0
  147. package/dist/ui/panel-details.js +2 -0
  148. package/dist/ui/panel-fleet.js +3 -2
  149. package/dist/ui/panel-hub.js +7 -1
  150. package/dist/ui/panel-needs.js +5 -1
  151. package/dist/ui/panel-settings.js +3 -0
  152. package/dist/ui/shared/app-route.js +1 -1
  153. package/dist/ui/shared/app-shell.js +2 -0
  154. package/dist/ui/shared/app-stream.js +3 -1
  155. package/dist/ui/shared/app.css +31 -0
  156. package/dist/ui/shared/chat-quote.js +26 -2
  157. package/dist/ui/shared/chat-thread.js +6 -2
  158. package/dist/ui/shared/hub-rooms-u2.css +22 -0
  159. package/dist/ui/shared/text-undo.js +17 -3
  160. package/dist/web-api.d.ts +9 -0
  161. package/dist/web-api.js +55 -3
  162. package/dist/web-api.js.map +1 -1
  163. package/dist/web-chat-history.d.ts +5 -0
  164. package/dist/web-chat-history.js +26 -0
  165. package/dist/web-chat-history.js.map +1 -1
  166. package/dist/web-reply-files.d.ts +1 -0
  167. package/dist/web-reply-files.js +2 -0
  168. package/dist/web-reply-files.js.map +1 -1
  169. package/dist/web-shell-routes.d.ts +1 -1
  170. package/dist/web-shell-routes.js +2 -1
  171. package/dist/web-shell-routes.js.map +1 -1
  172. package/package.json +1 -1
@@ -0,0 +1,54 @@
1
+ // M-3339 (A2): a chat message's contact badge — message.contactTicket = { id, state } (the contract's ContactBadge), on a
2
+ // ClassicBot room's held request or its status line ("聯絡申請 #R12"), and on the worker's inbound copy of an approved one
3
+ // ("已准轉交 #R12"). A link to that request (Fleet → Authorizations, where the server scopes who may read it).
4
+ // Kept current: on the stream's contact-auth frame naming a request a badge shows, that request is read again from its
5
+ // scoped route (installBadgeRefresh) and its badges change in place; later draws use that state too. A reader the route
6
+ // refuses keeps the message's own state.
7
+ // HTML text for chat-thread.js's opts.contactBadge hook (the Fleet chat's only; a Hub room passes none): every value escaped.
8
+ import { appStore } from "/assets/app-store.js";
9
+ import { ca } from "./contact-auth-strings.js";
10
+ import { getTicket, shortTicketId } from "./contact-auth-client.js";
11
+
12
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
13
+ const ID = /^[A-Za-z0-9_-]{1,64}$/;
14
+ const STATES = new Set(["pending", "approved", "delivered", "declined", "expired", "unknown"]);
15
+ /** The latest state read for a request (its scoped route), over the message's own. */
16
+ const fresh = new Map();
17
+ /** Requests a badge has shown on this page (the only ones a contact-auth frame reads again). */
18
+ const shown = new Set();
19
+
20
+ const badgeText = (full, state) => { const id = shortTicketId(full); return state === "delivered" ? `${ca("forwarded")} #${id}`
21
+ : state === "pending" || !STATES.has(state) ? ca("ticket", id) : `${ca("ticket", id)} · ${ca(`state_${state}`)}`; };
22
+
23
+ export function contactBadgeHtml(x) {
24
+ const tk = x && x.contactTicket;
25
+ if (!tk || typeof tk.id !== "string" || !ID.test(tk.id)) return "";
26
+ shown.add(tk.id);
27
+ const state = fresh.get(tk.id) ?? tk.state;
28
+ const ok = state === "delivered" || state === "approved";
29
+ return `<a class="contact-badge${ok ? " ok" : ""}" data-contact-ticket="${esc(tk.id)}" href="/ui/fleet/authorizations?ticket=${encodeURIComponent(tk.id)}">${esc(badgeText(tk.id, state))}</a>`;
30
+ }
31
+
32
+ /** Read one request again and change its badges on the page in place. */
33
+ export async function refreshBadge(id, doc = typeof document !== "undefined" ? document : null) {
34
+ if (!ID.test(String(id || "")) || !shown.has(id)) return;
35
+ const r = await getTicket(id);
36
+ if (!r.ok || !STATES.has(r.data?.state)) return;
37
+ fresh.set(id, r.data.state);
38
+ for (const a of doc ? doc.querySelectorAll("a.contact-badge") : []) {
39
+ if (a.getAttribute("data-contact-ticket") !== id) continue;
40
+ a.textContent = badgeText(id, r.data.state);
41
+ a.classList.toggle("ok", r.data.state === "delivered" || r.data.state === "approved");
42
+ }
43
+ }
44
+
45
+ let installed = null;
46
+ /** Once per page: the stream's contact-auth frames with a ticketId refresh that request's badges. */
47
+ export function installBadgeRefresh() {
48
+ if (installed) return installed;
49
+ const sub = appStore.get().streamOn;
50
+ if (typeof sub !== "function") return () => {};
51
+ const off = sub("contact-auth", (d) => { if (d && typeof d.ticketId === "string") void refreshBadge(d.ticketId); });
52
+ installed = () => { if (typeof off === "function") off(); installed = null; };
53
+ return installed;
54
+ }
@@ -232,7 +232,7 @@ export function createStubClient({ now = () => Date.now(), agents = () => [] } =
232
232
  export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTimeoutMs = 120_000 } = {}) {
233
233
  // The factory override is for owned transports/rehearsals; the page uses the finite default.
234
234
  const readBudget = Number.isInteger(readTimeoutMs) && readTimeoutMs > 0 && readTimeoutMs <= 300_000 ? readTimeoutMs : 120_000;
235
- let csrf = null, codeNotices = false, roomsLive = false, teamsLive = false, generation = 0;
235
+ let csrf = null, codeNotices = false, roomsLive = false, teamsLive = false, ownerRequestsLive = false, roomDiscoveryLive = false, generation = 0;
236
236
  const ended = new Set(), pendingReads = new Map(), waits = new Set(), readControllers = new Set();
237
237
  let readTail = Promise.resolve();
238
238
  const retired = () => ({ ok: false, status: 401, code: "unauthenticated" });
@@ -302,18 +302,24 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
302
302
  let json = null;
303
303
  try { json = await r.json(); } catch { json = null; }
304
304
  if (method === "GET" && signal?.aborted) return unreachable();
305
- if (r.status === 401 && mine === generation) { retireReads(); csrf = null; codeNotices = false; roomsLive = false; teamsLive = false; for (const fn of ended) { try { fn(); } catch { /* a listener's own failure */ } } }
305
+ if (r.status === 401 && mine === generation) { retireReads(); csrf = null; codeNotices = false; roomsLive = false; teamsLive = false; ownerRequestsLive = false; roomDiscoveryLive = false; for (const fn of ended) { try { fn(); } catch { /* a listener's own failure */ } } }
306
306
  if (!r.ok) return { ok: false, status: r.status, code: (json && typeof json.code === "string" && json.code) || "failed", retryAfter: Number(r.headers.get("Retry-After")) || 0,
307
307
  ...(method === "POST" && path === "/hub/v1/admin/enrolment-codes" && r.status === 429 && json?.code === "backpressure"
308
308
  && ["live-code-limit", "hourly-code-limit"].includes(json.reason) ? { reason: json.reason } : {}), ...roomRefusal(json) };
309
309
  return { ok: true, ...(json && typeof json === "object" ? json : {}) };
310
310
  }
311
311
  const id = (v) => encodeURIComponent(String(v));
312
+ const ownerRequestCall = async (scope, method, path, body) => {
313
+ if (!scope || scope !== csrf) return retired();
314
+ const mine = generation, result = await call(method, path, body);
315
+ return mine === generation && scope === csrf ? result : retired();
316
+ };
312
317
  // Track U2: a refused room write says what the person is told — 409 people-limit the room's would-be head count (the
313
318
  // deduplicated union, the creator and current members included) and the limit; 503 group-unavailable which group.
314
319
  const roomRefusal = (json) => json?.code === "people-limit" && Number.isSafeInteger(json.people)
315
320
  ? { people: json.people, limit: Number.isSafeInteger(json.limit) ? json.limit : 100 }
316
- : json?.code === "group-unavailable" && typeof json.group === "string" ? { group: json.group } : {};
321
+ : json?.code === "group-unavailable" && typeof json.group === "string" ? { group: json.group }
322
+ : json?.code === "request-limit" && Number.isSafeInteger(json.resetsAt) && json.resetsAt > 0 && json.resetsAt <= 8.64e15 ? { resetsAt: json.resetsAt } : {};
317
323
  // One stream per tab (#1580): every live subscription shares one EventSource. A Hub with rooms carries the notices on
318
324
  // its rooms stream too (`notices` = the notice version); before that the notices have their own. Listeners are kept
319
325
  // per event name; the stream closes with its last listener, and a refused (CLOSED) stream tells every subscriber once.
@@ -361,10 +367,22 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
361
367
  stub: false, web: true,
362
368
  /** Hear the session end (a 401 anywhere). @returns {() => void} */
363
369
  onSignedOut(fn) { ended.add(fn); return () => ended.delete(fn); },
364
- async session() { const r = await call("GET", "/hub/v1/session"); if (r.ok) { csrf = r.signedIn ? r.csrf || null : null; codeNotices = r.signedIn === true && r.features?.includes("enrolment-code-v1") === true; roomsLive = r.signedIn === true && r.features?.includes(ROOMS_FEATURE) === true; teamsLive = r.signedIn === true && r.features?.includes(TEAMS_FEATURE) === true; } return r; },
365
- async signIn(login, password) { retireReads(); teamsLive = false; const r = await call("POST", "/hub/v1/session", { login, password }); if (r.ok) { csrf = r.csrf || null; codeNotices = r.features?.includes("enrolment-code-v1") === true; roomsLive = r.features?.includes(ROOMS_FEATURE) === true; teamsLive = r.features?.includes(TEAMS_FEATURE) === true; } return r; },
366
- async signOut() { retireReads(); const r = await call("DELETE", "/hub/v1/session"); csrf = null; codeNotices = false; roomsLive = false; teamsLive = false; return r; },
370
+ async session() { const r = await call("GET", "/hub/v1/session"); if (r.ok) { csrf = r.signedIn ? r.csrf || null : null; codeNotices = r.signedIn === true && r.features?.includes("enrolment-code-v1") === true; roomsLive = r.signedIn === true && r.features?.includes(ROOMS_FEATURE) === true; teamsLive = r.signedIn === true && r.features?.includes(TEAMS_FEATURE) === true; ownerRequestsLive = r.signedIn === true && r.features?.includes("room-owner-requests-v1") === true; roomDiscoveryLive = r.signedIn === true && r.features?.includes("room-agent-discovery-v1") === true; } return r; },
371
+ async signIn(login, password) { retireReads(); teamsLive = false; ownerRequestsLive = false; roomDiscoveryLive = false; const r = await call("POST", "/hub/v1/session", { login, password }); if (r.ok) { csrf = r.csrf || null; codeNotices = r.features?.includes("enrolment-code-v1") === true; roomsLive = r.features?.includes(ROOMS_FEATURE) === true; teamsLive = r.features?.includes(TEAMS_FEATURE) === true; ownerRequestsLive = r.features?.includes("room-owner-requests-v1") === true; roomDiscoveryLive = r.features?.includes("room-agent-discovery-v1") === true; } return r; },
372
+ async signOut() { retireReads(); const r = await call("DELETE", "/hub/v1/session"); csrf = null; codeNotices = false; roomsLive = false; teamsLive = false; ownerRequestsLive = false; roomDiscoveryLive = false; return r; },
367
373
  aiAppsScope() { return csrf; },
374
+ roomAgentRequestScope() { return csrf; },
375
+ requestRoomAgent(scope, roomId, input) { return ownerRequestCall(scope, "POST", "/hub/v1/rooms/" + id(roomId) + "/agent-requests", input); },
376
+ roomAgentRequests(scope, roomId, after) { return ownerRequestCall(scope, "GET", "/hub/v1/rooms/" + id(roomId) + "/agent-requests" + (after ? "?after=" + id(after) : "")); },
377
+ cancelRoomAgentRequest(scope, roomId, requestId) { return ownerRequestCall(scope, "DELETE", "/hub/v1/rooms/" + id(roomId) + "/agent-requests/" + id(requestId)); },
378
+ ownerRequestsLive() { return ownerRequestsLive; },
379
+ roomDiscoveryLive() { return roomDiscoveryLive; },
380
+ agentRoomDiscovery(scope, exposureId, input) { return ownerRequestCall(scope, input === undefined ? "GET" : "PUT", "/hub/v1/exposures/" + id(exposureId) + "/room-discovery", input); },
381
+ ownerAgentRequest(scope, requestId) { return ownerRequestCall(scope, "GET", "/hub/v1/agent-requests/" + id(requestId)); },
382
+ acceptOwnerAgentRequest(scope, requestId, input) { return ownerRequestCall(scope, "POST", "/hub/v1/agent-requests/" + id(requestId) + "/accept", input); },
383
+ declineOwnerAgentRequest(scope, requestId) { return ownerRequestCall(scope, "POST", "/hub/v1/agent-requests/" + id(requestId) + "/decline", {}); },
384
+ ownerAgentRequests(scope, after) { return ownerRequestCall(scope, "GET", "/hub/v1/agent-requests" + (after ? "?after=" + id(after) : "")); },
385
+ agentRequestSettings(scope, input) { return ownerRequestCall(scope, input === undefined ? "GET" : "PUT", "/hub/v1/me/agent-request-settings", input); },
368
386
  aiApps(scope) { return scope && scope === csrf ? call("GET", "/hub/v1/me/ai-apps") : Promise.resolve(retired()); },
369
387
  disconnectAiApp(scope, appId) { return scope && scope === csrf ? call("DELETE", `/hub/v1/me/ai-apps/${id(appId)}`) : Promise.resolve(retired()); },
370
388
  appConsent(scope, request) { return scope && scope === csrf ? call("GET", `/hub/v1/mcp/consent?${new URLSearchParams({request})}`) : Promise.resolve(retired()); },
@@ -443,7 +461,7 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
443
461
  * server without rooms ignores the parameter (its answer is then normalised here).
444
462
  */
445
463
  async roomList() {
446
- const r = await call("GET", "/hub/v1/rooms?v=2");
464
+ const r = await call("GET", "/hub/v1/rooms?v=2" + (ownerRequestsLive ? "&ownerRequests=1" : ""));
447
465
  if (!r.ok || roomsLive) return r;
448
466
  return { ...r, rooms: (Array.isArray(r.rooms) ? r.rooms : []).map(legacyRoom).filter(Boolean) };
449
467
  },
@@ -479,6 +497,10 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
479
497
  },
480
498
  /** M-3127: add (`on`) or take back my reaction `emoji` on a group-room message → { reactions }. */
481
499
  reactRoomMessage(roomId, messageId, emoji, on) { return call("POST", `/hub/v1/rooms/${id(roomId)}/messages/${id(messageId)}/reactions`, { emoji: String(emoji), on: on === true }); },
500
+ /** M-3340: my own pins in a group room (nobody else's) → { pins: [{ messageId, pinnedAt, message }] }, newest first. */
501
+ roomPins(roomId) { return call("GET", `/hub/v1/rooms/${id(roomId)}/pins`); },
502
+ /** M-3340: pin (`on`) or unpin a group-room message for me only → { pins }. Past 50: the Hub refuses (pins-full). */
503
+ pinRoomMessage(roomId, messageId, on) { return call(on ? "PUT" : "DELETE", `/hub/v1/rooms/${id(roomId)}/pins/${id(messageId)}`); },
482
504
  markRoomRead(roomId, upTo) { return call("POST", `/hub/v1/rooms/${id(roomId)}/read`, { upTo }); },
483
505
  /**
484
506
  * The one live stream of everything this person may see (seam 1): `handlers[name](data)` for each of ROOM_EVENTS,
@@ -531,6 +553,7 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
531
553
  roomCandidates(q, kind, signal) {
532
554
  const s = new URLSearchParams({ q: String(q ?? "") });
533
555
  if (kind) s.set("kind", kind);
556
+ if (kind === "agent" && roomDiscoveryLive) s.set("discovery", "1");
534
557
  return call("GET", `/hub/v1/rooms/candidates?${s}`, undefined, signal);
535
558
  },
536
559
  /**
@@ -8,6 +8,7 @@ import { hubClient } from "./hub-client.js";
8
8
  import { hi } from "./hub-invitations-strings.js";
9
9
  import { hroom } from "./hub-room-strings.js";
10
10
  import { linkRoomsU2Css } from "./hub-room-new-strings.js";
11
+ import { OwnerAgentRequestsList } from "./hub-room-owner-requests.js";
11
12
 
12
13
  linkRoomsU2Css();
13
14
 
@@ -42,7 +43,10 @@ const valid = (x) => x && typeof x.id === "string" && x.room && typeof x.room.na
42
43
  * The invitations themselves, each with 同意 / 不要. Nothing when there are none (My shared agents shows no empty box).
43
44
  * heading: the list's own 「邀請」 title — false where the page already says it (the invitations page's header).
44
45
  */
45
- export function InvitationsList({ client = hubClient(), heading = true } = {}) { // onOpenRoom: not used — the owner is not a member of the inviting room
46
+ export function InvitationsList({ client = hubClient(), heading = true } = {}) {
47
+ return html`<${OwnerAgentRequestsList} client=${client} heading=${heading} /><${LegacyInvitationsList} client=${client} heading=${heading} />`;
48
+ }
49
+ function LegacyInvitationsList({ client, heading }) { // onOpenRoom: not used — the owner is not a member of the inviting room
46
50
  const { list, error, reload, answer } = useInvitations(client);
47
51
  const [busy, setBusy] = useState(null), [note, setNote] = useState(null), inflight = useRef(false);
48
52
  if (error && !list) return html`<p class="note hub-invitations-error" role="alert">${hi("loadFailed")} <button type="button" class="btn btn-link" onClick=${() => { void reload(); }}>${hi("retry")}</button></p>`;
@@ -8,6 +8,7 @@ import {RoomPurposeField,purposeCount} from "./hub-room-purpose.js";
8
8
  import { html, useEffect, useRef, useState } from "/assets/app-html.js";
9
9
  import { Dialog } from "/assets/ui-dialog.js";
10
10
  import { hubClient } from "./hub-client.js";
11
+ import { hrq } from "./hub-room-owner-requests-strings.js";
11
12
  import { hroom } from "./hub-room-strings.js";
12
13
  import { hn, linkRoomsU2Css } from "./hub-room-new-strings.js";
13
14
 
@@ -33,12 +34,17 @@ const keyOf = (item) => `${item.kind}:${item.id}`;
33
34
  * A picked AD group is read first (client.roomGroup): its tag shows its head count, and a group the directory cannot
34
35
  * read whole is not added — the other picks stay.
35
36
  */
36
- export function RoomPicker({ client, kinds, picked, onChange, placeholder, label, id, exclude = [], fixed = null, note = "" } = {}) {
37
+ export function RoomPicker({ client, kinds, picked, onChange, placeholder, label, id, exclude = [], fixed = null, note = "", searchHelp = null } = {}) {
37
38
  const [q, setQ] = useState(""), [results, setResults] = useState(null), [failed, setFailed] = useState(false), [groupNote, setGroupNote] = useState("");
38
39
  const asked = useRef(0), timer = useRef(null), latest = useRef(picked), live = useRef(true);
39
40
  latest.current = picked;
40
41
  const agents = kinds.includes("agent");
41
42
  useEffect(() => { live.current = true; return () => { live.current = false; clearTimeout(timer.current); }; }, []);
43
+ const leave = (event) => {
44
+ // Null is ambiguous on touch/Safari; retain in-field pointer selection.
45
+ if (!event.relatedTarget || event.currentTarget.contains(event.relatedTarget)) return;
46
+ clearTimeout(timer.current); ++asked.current; setResults(null);
47
+ };
42
48
  const search = (text) => {
43
49
  setQ(text); clearTimeout(timer.current);
44
50
  const mine = ++asked.current;
@@ -63,7 +69,7 @@ export function RoomPicker({ client, kinds, picked, onChange, placeholder, label
63
69
  if (!r?.ok) { setGroupNote(hn("groupUnavailable", item.name)); return; }
64
70
  onChange([...latest.current, { ...item, ...(typeof r.name === "string" && r.name ? { name: r.name } : {}), ...(Number.isSafeInteger(r.people) ? { people: r.people } : {}) }]);
65
71
  };
66
- return html`<div class="field hub-room-picker">
72
+ return html`<div class="field hub-room-picker" onFocusOut=${leave}>
67
73
  <label for=${id}><span>${label}</span></label>
68
74
  <ul class="hub-room-tags">
69
75
  ${fixed}
@@ -74,8 +80,9 @@ export function RoomPicker({ client, kinds, picked, onChange, placeholder, label
74
80
  ${failed ? html`<p class="note" role="alert">${hn("searchFailed")}</p>` : null}
75
81
  ${groupNote || note ? html`<p class="note hub-room-picker-note" role="alert">${groupNote || note}</p>` : null}
76
82
  ${results && !failed ? offer.length ? html`<ul class="hub-room-results" role="listbox" aria-label=${label}>${offer.map(c => html`<li key=${keyOf(c)}>
77
- <button type="button" role="option" class="hub-room-result" onClick=${() => { void pick(c); }}>${pickLabel(c)}${c.intro?html` <small class="note">${c.intro}</small>`:null}${c.owner?.name && c.kind === "agent" ? html` <small class="note">${c.owner.name}</small>` : null}${c.kind === "agent" && !c.mine ? html` <small class="note">${hroom("invitePending")}</small>` : null}</button></li>`)}</ul>`
83
+ <button type="button" role="option" class=${`hub-room-result${c.kind === "agent" ? " hub-room-result-agent" : ""}`} aria-label=${c.kind === "person" ? `${c.name}${c.detail ? `, ${c.detail}` : ""}` : c.kind === "agent" && !c.mine ? hrq("askOwnerLabel", c.owner?.name || "", c.name) : undefined} onClick=${() => { void pick(c); }}>${c.kind === "person" ? html`<span class="hub-room-person-label"><span class="hub-room-person-name" title=${c.name}>${c.name}</span>${c.detail ? html`<small class="note hub-room-person-detail" title=${c.detail}>${c.detail}</small>` : null}</span>` : c.kind === "agent" ? html`<span class="hub-room-agent-label"><span class="hub-room-agent-title">${c.name}${c.owner?.name ? html` <small class="note">${c.owner.name}</small>` : null}</span>${c.intro ? html`<small class="note hub-room-agent-intro" title=${c.intro}>${c.intro}</small>` : null}</span> ${!c.mine ? html`<span class="btn btn-sm hub-room-agent-action">${hrq("askOwner", c.owner?.name || "")}</span>` : null}` : pickLabel(c)}${c.kind !== "agent" && c.intro ? html` <small class="note">${c.intro}</small>` : null}</button></li>`)}</ul>`
78
84
  : html`<p class="note">${hn("noMatch")}</p>` : null}
85
+ ${q.trim() ? searchHelp : null}
79
86
  </div>`;
80
87
  }
81
88
 
@@ -0,0 +1,114 @@
1
+ import { register, t } from "/assets/app-i18n.js";
2
+ register("hubOwnerRequests", {
3
+ en: {
4
+ missing: "Can't find someone's agent? It may not be shared with you.",
5
+ ask: "Ask its owner",
6
+ chooseTitle: "Ask an agent's owner",
7
+ choose: "Who owns it?",
8
+ owner: "Owner",
9
+ search: "Search for a person",
10
+ title: 'Ask {0} to add an agent to "{1}"',
11
+ lead: "{0} will see who is asking and which room. You will only learn about an agent if {0} adds one.",
12
+ note: "Which agent, if you know (optional)",
13
+ send: "Send request",
14
+ cancel: "Cancel",
15
+ waiting: "Asked {0} for an agent · waiting",
16
+ cancelRequest: "Cancel request",
17
+ declined: "{0} didn't add an agent.",
18
+ expired: "{0} didn't answer.",
19
+ accepted: "{0} added an agent.",
20
+ ownerOff: "{0} isn't taking requests for agents.",
21
+ already: "A request to {0} is already open for this room.",
22
+ limit: "You have sent 5 requests today. You can send more after {0}.",
23
+ failed: "That was not sent. Try again.",
24
+ more: "Load more",
25
+ requestsTitle: "Requests for agents",
26
+ requestLead: '{0} asks you to add one of your agents to the room "{1}"',
27
+ requestBody: "People in the room can @ it there, and everyone in the room sees its answers. When @-ed, it reads the room's recent messages. They cannot ask it one-to-one. {0} people are in the room now; the room's managers can add more.",
28
+ requestBodyOne: "People in the room can @ it there, and everyone in the room sees its answers. When @-ed, it reads the room's recent messages. They cannot ask it one-to-one. 1 person is in the room now; the room's managers can add more.",
29
+ which: "Which agent",
30
+ chooseAgent: "Choose an agent",
31
+ quotedNote: '"{0}"',
32
+ notShared: "Not shared yet. Share it first on My agents.",
33
+ paused: "Sharing is paused. Resume it on My agents.",
34
+ unavailable: "This agent can't be added right now. Check My agents.",
35
+ inRoom: "Already in this room.",
36
+ myAgents: "My agents",
37
+ noAgents: "You have no shared agent to add. Share one on My agents first, or decline this request.",
38
+ add: "Add to this room",
39
+ decline: "Decline",
40
+ gone: "This request is no longer open.",
41
+ loadFailed: "Requests could not be loaded.",
42
+ retry: "Try again",
43
+ actionFailed: "That did not go through. Try again.",
44
+ added: 'Agent added to "{0}".',
45
+ declinedNotice: "Request declined.",
46
+ stopRequests: "Don't let room managers ask me for agents",
47
+ stopHint: "Requests already waiting stay open. You can still add an agent or decline them.",
48
+ saved: "Saved.",
49
+ discoveryLabel: "Room managers can find this agent",
50
+ discoveryHint: "Managers of any room can find it by name and ask you to add it to their room. They see its name, its introduction and your name. You still decide each time, and this lets nobody ask it one-to-one.",
51
+ discoveryPaused: "Hidden while sharing is paused.",
52
+ discoveryUnshared: "Share this agent first.",
53
+ discoveryOptOut: "Off while \"Don't let room managers ask me for agents\" is on.",
54
+ askOwner: "Ask {0}",
55
+ askOwnerLabel: "Ask {0} to add {1} to this room",
56
+ classic: "ClassicBot room",
57
+ },
58
+ "zh-TW": {
59
+ missing: "找不到某位同仁的 Agent 嗎?它可能沒有分享給你。",
60
+ ask: "請擁有者加入",
61
+ chooseTitle: "請擁有者加入 Agent",
62
+ choose: "擁有者是誰?",
63
+ owner: "擁有者",
64
+ search: "搜尋同仁",
65
+ title: "請 {0} 把 Agent 加入「{1}」",
66
+ lead: "{0} 會看到是誰提出、是哪個房間。只有在 {0} 加入之後,你才會知道是哪個 Agent。",
67
+ note: "如果知道是哪個 Agent,可以寫在這裡(選填)",
68
+ send: "送出請求",
69
+ cancel: "取消",
70
+ waiting: "已請 {0} 加入 Agent · 等待中",
71
+ cancelRequest: "取消請求",
72
+ declined: "{0} 沒有加入 Agent。",
73
+ expired: "{0} 沒有回應。",
74
+ accepted: "{0} 已加入 Agent。",
75
+ ownerOff: "{0} 目前不接受加入 Agent 的請求。",
76
+ already: "這個房間已經向 {0} 送出請求,仍在等待回應。",
77
+ limit: "你今天已送出 5 個請求,{0} 之後可以再送。",
78
+ failed: "沒有送出,請再試一次。",
79
+ more: "載入更多",
80
+ requestsTitle: "加入 Agent 的請求",
81
+ requestLead: "{0} 請你把一個 Agent 加入房間「{1}」",
82
+ requestBody: "房間裡的人可以在房間裡 @ 它,所有人都看得到它的回答。被 @ 時,它會讀到房間最近的訊息。他們不能一對一問它。房間現在有 {0} 個人,房間管理員之後可以再加人。",
83
+ requestBodyOne: "房間裡的人可以在房間裡 @ 它,所有人都看得到它的回答。被 @ 時,它會讀到房間最近的訊息。他們不能一對一問它。房間現在有 1 個人,房間管理員之後可以再加人。",
84
+ which: "要加入哪一個",
85
+ chooseAgent: "選擇要加入的 Agent",
86
+ quotedNote: "「{0}」",
87
+ notShared: "還沒有分享。請先到「我的 Agent」分享。",
88
+ paused: "已暫停分享。請到「我的 Agent」恢復分享。",
89
+ unavailable: "目前無法加入這個 Agent,請到「我的 Agent」確認。",
90
+ inRoom: "已經在這個房間。",
91
+ myAgents: "我的 Agent",
92
+ noAgents: "目前沒有可以加入的已分享 Agent。請先到「我的 Agent」分享,或選擇不加入。",
93
+ add: "加入這個房間",
94
+ decline: "不加入",
95
+ gone: "這個請求已經結束。",
96
+ loadFailed: "無法載入請求。",
97
+ retry: "再試一次",
98
+ actionFailed: "沒有送出,請再試一次。",
99
+ added: "已把 Agent 加入「{0}」。",
100
+ declinedNotice: "已選擇不加入。",
101
+ stopRequests: "不要讓房間管理員請我加入 Agent",
102
+ stopHint: "已經收到的請求仍然有效,你還是可以加入 Agent 或選擇不加入。",
103
+ saved: "已儲存。",
104
+ discoveryLabel: "房間管理員可以找到這個 Agent",
105
+ discoveryHint: "任何房間的管理員都能用名稱找到它,並請你把它加入他們的房間。他們會看到它的名稱、介紹和你的名字。每次仍由你決定,而且這不會讓任何人可以一對一問它。",
106
+ discoveryPaused: "暫停分享期間不會顯示。",
107
+ discoveryUnshared: "請先分享這個 Agent。",
108
+ discoveryOptOut: "已開啟「不要讓房間管理員請我加入 Agent」,所以目前無法使用。",
109
+ askOwner: "請 {0} 加入",
110
+ askOwnerLabel: "請 {0} 把 {1} 加入這個房間",
111
+ classic: "ClassicBot 房間",
112
+ },
113
+ });
114
+ export const hrq = (key, ...args) => t("hubOwnerRequests." + key, ...args);
@@ -0,0 +1,264 @@
1
+ import { html, useEffect, useLayoutEffect, useRef, useState } from "/assets/app-html.js";
2
+ import { Dialog } from "/assets/ui-dialog.js";
3
+ import { RoomPicker } from "./hub-room-new.js";
4
+ import { hrq } from "./hub-room-owner-requests-strings.js";
5
+ import { hn } from "./hub-room-new-strings.js";
6
+
7
+ export function ownerRequestError(result, owner) {
8
+ if (result?.code === "owner-not-taking-requests") return hrq("ownerOff", owner);
9
+ if (result?.code === "request-open") return hrq("already", owner);
10
+ if (result?.code === "request-limit" && Number.isSafeInteger(result.resetsAt) && result.resetsAt > 0 && result.resetsAt <= 8.64e15) {
11
+ const time = new Date(result.resetsAt).toLocaleString(undefined, { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" });
12
+ return hrq("limit", time);
13
+ }
14
+ return hrq("failed");
15
+ }
16
+
17
+ /** The selection is a person, never evidence that the person owns any agent. */
18
+ export function OwnerAgentRequestDialog({ client, roomId, roomName, onClose, onSent } = {}) {
19
+ const [picked, setPicked] = useState([]), [note, setNote] = useState(""), [busy, setBusy] = useState(false), [error, setError] = useState("");
20
+ const [scope] = useState(() => client.roomAgentRequestScope?.());
21
+ const live = useRef(true), sending = useRef(false), attempt = useRef(null);
22
+ useEffect(() => { live.current = true; return () => { live.current = false; }; }, []);
23
+ const owner = picked[0] ?? null;
24
+ const send = async event => {
25
+ event?.preventDefault?.();
26
+ if (sending.current || !owner || note.length > 100) return;
27
+ const frozen = { owner: owner.id, note: note.trim() };
28
+ if (!attempt.current || attempt.current.owner !== frozen.owner || attempt.current.note !== frozen.note)
29
+ attempt.current = { ...frozen, idempotencyKey: crypto.randomUUID() };
30
+ sending.current = true; setBusy(true); setError("");
31
+ let result;
32
+ try { result = await client.requestRoomAgent(scope, roomId, { ...attempt.current }); }
33
+ catch { result = null; }
34
+ if (!live.current) return;
35
+ sending.current = false; setBusy(false);
36
+ if (result?.ok) { onSent?.(result.request); onClose?.(); }
37
+ else setError(ownerRequestError(result, owner.name));
38
+ };
39
+ const actions = html`
40
+ <button type="button" class="btn btn-ghost" disabled=${busy} onClick=${onClose}>${hrq("cancel")}</button>
41
+ ${owner ? html`<button type="submit" form="hubOwnerAgentRequestForm" class="btn btn-primary" disabled=${busy}>${hrq("send")}</button>` : null}`;
42
+ return html`<${Dialog} cls="hub-owner-request" title=${owner ? hrq("title", owner.name, roomName) : hrq("chooseTitle")}
43
+ onClose=${onClose} busy=${busy} actions=${actions}>
44
+ <form id="hubOwnerAgentRequestForm" class="form" onSubmit=${send}>
45
+ <fieldset disabled=${busy}>
46
+ ${owner ? html`<div class="field"><span id="hubRequestOwnerLabel">${hrq("owner")}</span>
47
+ <ul class="hub-room-tags" aria-labelledby="hubRequestOwnerLabel"><li class="tag">${owner.name}
48
+ <button type="button" class="chip-btn" aria-label=${hn("remove", owner.name)} onClick=${() => { setPicked([]); setError(""); }}>×</button>
49
+ </li></ul></div>`
50
+ : html`<${RoomPicker} client=${client} id="hubRequestOwner" kinds=${["person"]} label=${hrq("choose")} placeholder=${hrq("search")}
51
+ picked=${picked} onChange=${next => { setPicked(next.slice(-1)); setError(""); }} />`}
52
+ ${owner ? html`<p class="note">${hrq("lead", owner.name)}</p>
53
+ <label class="field" for="hubOwnerAgentNote"><span>${hrq("note")}</span>
54
+ <input id="hubOwnerAgentNote" type="text" maxlength="100" value=${note} onInput=${event => setNote(event.target.value.slice(0, 100))} />
55
+ <small class="note">${note.length} / 100</small>
56
+ </label>` : null}
57
+ </fieldset>
58
+ ${error ? html`<p class="note" role="alert">${error}</p>` : null}
59
+ </form>
60
+ </${Dialog}>`;
61
+ }
62
+
63
+ const valid = row => row && typeof row.id === "string" && typeof row.owner?.name === "string"
64
+ && ["pending", "declined", "expired", "accepted"].includes(row.state);
65
+ export function OwnerAgentRequestRows({ client, roomId, page, onChanged, busy = false } = {}) {
66
+ const [scope] = useState(() => client.roomAgentRequestScope?.());
67
+ const [extra, setExtra] = useState([]), [next, setNext] = useState(page?.next ?? null), [error, setError] = useState(""), [working, setWorking] = useState(false);
68
+ const live = useRef(true), pending = useRef(false);
69
+ const view = useRef({ page, roomId });
70
+ // Retire old responses at render, before the reset effect or a later operation can run.
71
+ if (view.current.page !== page || view.current.roomId !== roomId) view.current = { page, roomId };
72
+ useEffect(() => { live.current = true; return () => { live.current = false; }; }, []);
73
+ useLayoutEffect(() => {
74
+ setExtra([]); setNext(page?.next ?? null); setError(""); setWorking(false); pending.current = false;
75
+ }, [page, roomId]);
76
+ useEffect(() => client.subscribeRooms?.({ "invitation.changed": () => onChanged?.() }) ?? (() => {}), [client, roomId, onChanged]);
77
+ const rows = [...(Array.isArray(page?.requests) ? page.requests : []), ...extra].filter(valid);
78
+ const act = async (id, more = false) => {
79
+ if (pending.current) return;
80
+ const mine = view.current;
81
+ pending.current = true; setWorking(true); setError("");
82
+ let result;
83
+ try { result = await (more ? client.roomAgentRequests(scope, roomId, next) : client.cancelRoomAgentRequest(scope, roomId, id)); }
84
+ catch { result = null; }
85
+ if (!live.current || mine !== view.current) return;
86
+ pending.current = false; setWorking(false);
87
+ if (result?.ok) {
88
+ if (more) { setExtra(old => [...old, ...(Array.isArray(result.requests) ? result.requests : [])]); setNext(result.next ?? null); }
89
+ else onChanged?.();
90
+ } else setError(hrq("failed"));
91
+ };
92
+ return html`<div class="hub-room-owner-requests">
93
+ ${rows.length ? html`<ul class="hub-settings-invited">${rows.map(row => html`<li class="hub-settings-row" key=${row.id} data-owner-request=${row.id}>
94
+ <span>${hrq(row.state === "pending" ? "waiting" : row.state, row.owner.name)}</span>
95
+ ${row.state === "pending" ? html`<button type="button" class="btn btn-link" disabled=${busy || working} onClick=${() => { void act(row.id); }}>${hrq("cancelRequest")}</button>` : null}
96
+ </li>`)}</ul>` : null}
97
+ ${next ? html`<button type="button" class="btn btn-ghost" disabled=${busy || working} onClick=${() => { void act(null, true); }}>${hrq("more")}</button>` : null}
98
+ ${error ? html`<p class="note" role="alert">${error}</p>` : null}
99
+ </div>`;
100
+ }
101
+
102
+ const validOwnerRequest = row => row && row.kind === "owner-request" && typeof row.id === "string"
103
+ && typeof row.room?.name === "string" && typeof row.by?.name === "string";
104
+ const choiceReason = row => hrq(({ "not-shared": "notShared", paused: "paused", "already-in-room": "inRoom" })[row.reason] || "unavailable");
105
+ function myAgentsHint(text) {
106
+ const label = hrq("myAgents"), at = text.indexOf(label);
107
+ return at < 0 ? text : html`${text.slice(0, at)}<a href="/ui/hub/exposures">${label}</a>${text.slice(at + label.length)}`;
108
+ }
109
+
110
+ /** Feature-gated separately from legacy invitations, so cached readers keep their original API shape. */
111
+ export function OwnerAgentRequestsList({ client, heading = true } = {}) {
112
+ if (client.ownerRequestsLive?.() !== true) return null;
113
+ return html`<${OwnerRequestList} key=${client.roomAgentRequestScope?.()} client=${client} heading=${heading} />`;
114
+ }
115
+ function OwnerRequestList({ client, heading }) {
116
+ const [scope] = useState(() => client.roomAgentRequestScope());
117
+ const [page, setPage] = useState(null), [error, setError] = useState(false), [loading, setLoading] = useState(false);
118
+ const [busy, setBusy] = useState(false), [notice, setNotice] = useState("");
119
+ const live = useRef(true), generation = useRef(0), readingMore = useRef(false), writing = useRef(false);
120
+ const reload = async () => {
121
+ const mine = ++generation.current; readingMore.current = false; setLoading(false);
122
+ let result; try { result = await client.ownerAgentRequests(scope); } catch { result = null; }
123
+ if (!live.current || mine !== generation.current) return;
124
+ if (result?.ok && Array.isArray(result.requests)) { setPage({ requests: result.requests.filter(validOwnerRequest), next: result.next || null }); setError(false); }
125
+ else setError(true);
126
+ };
127
+ useEffect(() => {
128
+ live.current = true; void reload();
129
+ const off = client.subscribeRooms?.({ "invitation.changed": () => { void reload(); } }) ?? (() => {});
130
+ return () => { live.current = false; generation.current++; off(); };
131
+ }, [client, scope]);
132
+ const more = async () => {
133
+ if (readingMore.current || !page?.next) return;
134
+ const mine = generation.current; readingMore.current = true; setLoading(true); setError(false);
135
+ let result; try { result = await client.ownerAgentRequests(scope, page.next); } catch { result = null; }
136
+ if (!live.current || mine !== generation.current) return;
137
+ readingMore.current = false; setLoading(false);
138
+ if (result?.ok && Array.isArray(result.requests)) setPage(old => ({ requests: [...new Map([...old.requests, ...result.requests.filter(validOwnerRequest)].map(row => [row.id, row])).values()], next: result.next || null }));
139
+ else setError(true);
140
+ };
141
+ const answer = async (item, choice) => {
142
+ if (writing.current) return { ok: false, ignored: true };
143
+ writing.current = true; setBusy(true); setNotice("");
144
+ let result;
145
+ try { result = await (choice ? client.acceptOwnerAgentRequest(scope, item.id, { exposureId: choice.exposureId, revision: choice.revision })
146
+ : client.declineOwnerAgentRequest(scope, item.id)); } catch { result = null; }
147
+ if (!live.current) return result;
148
+ writing.current = false; setBusy(false);
149
+ if (result?.ok || result?.status === 404) {
150
+ generation.current++; readingMore.current = false; setLoading(false);
151
+ setPage(old => old ? { ...old, requests: old.requests.filter(row => row.id !== item.id) } : old);
152
+ setNotice(result?.ok ? hrq(choice ? "added" : "declinedNotice", item.room.name) : hrq("gone"));
153
+ void reload();
154
+ }
155
+ return result;
156
+ };
157
+ return html`<section class="hub-owner-agent-requests" aria-label=${hrq("requestsTitle")}>
158
+ ${page?.requests.length && heading ? html`<h3>${hrq("requestsTitle")}</h3>` : null}
159
+ ${page?.requests.map(item => html`<${OwnerRequestCard} key=${item.id} client=${client} scope=${scope} item=${item} busy=${busy} onAnswer=${answer} />`)}
160
+ ${page?.next ? html`<button class="btn btn-ghost" disabled=${loading || busy} onClick=${() => { void more(); }}>${hrq("more")}</button>` : null}
161
+ ${error ? html`<p class="note" role="alert">${hrq("loadFailed")} <button class="btn btn-link" onClick=${() => { void reload(); }}>${hrq("retry")}</button></p>` : null}
162
+ ${notice ? html`<p class="note" role="status">${notice}</p>` : null}
163
+ </section>`;
164
+ }
165
+ function OwnerRequestCard({ client, scope, item, busy, onAnswer }) {
166
+ const [view, setView] = useState(null), [selected, setSelected] = useState(null), [error, setError] = useState("");
167
+ const live = useRef(true), generation = useRef(0);
168
+ const load = async () => {
169
+ const mine = ++generation.current;
170
+ let result; try { result = await client.ownerAgentRequest(scope, item.id); } catch { result = null; }
171
+ if (!live.current || mine !== generation.current) return;
172
+ if (result?.ok && Array.isArray(result.choices)) {
173
+ const choices = result.choices.filter(row => row && typeof row.key === "string" && typeof row.name === "string")
174
+ .sort((a, b) => Number(b.canAdd === true) - Number(a.canAdd === true));
175
+ setView({ request: result.request, choices });
176
+ const available = choices.filter(row => row.canAdd === true && typeof row.exposureId === "string" && Number.isSafeInteger(row.revision));
177
+ setSelected(old => available.some(row => row.key === old) ? old : available.length === 1 ? available[0].key : null);
178
+ } else setError(hrq(result?.status === 404 ? "gone" : "loadFailed"));
179
+ };
180
+ useEffect(() => { live.current = true; void load(); return () => { live.current = false; generation.current++; }; }, [client, scope, item.id]);
181
+ const chosen = view?.choices.find(row => row.key === selected && row.canAdd === true);
182
+ const available = view?.choices.filter(row => row.canAdd === true) || [];
183
+ const act = async choice => {
184
+ setError(""); const result = await onAnswer(item, choice);
185
+ if (!live.current || result?.ignored || result?.ok || result?.status === 404) return;
186
+ setError(hrq("actionFailed")); if (result?.status === 409) void load();
187
+ };
188
+ const request = view?.request || item;
189
+ return html`<article class="hub-invitation" data-owner-request-card=${item.id}>
190
+ <p class="hub-owner-request-title">${hrq("requestLead", request.by?.name || "", request.room.name)}</p>
191
+ ${request.note ? html`<blockquote>${hrq("quotedNote", request.note)}</blockquote>` : null}
192
+ <p class="note">${hrq(request.room.people === 1 ? "requestBodyOne" : "requestBody", Number(request.room.people) || 0)}</p>
193
+ ${view && !available.length ? html`<p class="note">${myAgentsHint(hrq("noAgents"))}</p>` : null}
194
+ ${view ? html`<fieldset class="hub-owner-agent-choices" disabled=${busy}><legend>${hrq(available.length > 1 && !chosen ? "chooseAgent" : "which")}</legend>
195
+ ${view.choices.length ? view.choices.map(row => html`<label class="check" key=${row.key}>
196
+ <input type="radio" name=${"owner-request-" + item.id} value=${row.key} disabled=${!row.canAdd} checked=${selected === row.key} onChange=${() => setSelected(row.key)} />
197
+ <span><strong>${row.name}</strong>${row.kind === "classic-room" ? html` <small class="tag">${hrq("classic")}</small>` : null}
198
+ ${row.intro ? html`<small class="note">${row.intro}</small>` : null}
199
+ ${!row.canAdd ? html`<small class="note">${myAgentsHint(choiceReason(row))}</small>` : null}</span>
200
+ </label>`) : null}
201
+ </fieldset>` : null}
202
+ ${error ? html`<p class="note" role="alert">${error} <button class="btn btn-link" onClick=${() => { void load(); }}>${hrq("retry")}</button></p>` : null}
203
+ <div class="field-row">${available.length ? html`<button type="button" class="btn btn-primary" disabled=${busy || !chosen} onClick=${() => { void act(chosen); }}>${hrq("add")}</button>` : null}
204
+ <button type="button" class="btn" disabled=${busy} onClick=${() => { void act(null); }}>${hrq("decline")}</button></div>
205
+ </article>`;
206
+ }
207
+
208
+ export function OwnerAgentRequestSetting({ client, scope } = {}) {
209
+ if (typeof client?.agentRequestSettings !== "function" || !scope) return null;
210
+ return html`<${OwnerRequestSetting} key=${scope} client=${client} scope=${scope} />`;
211
+ }
212
+ function OwnerRequestSetting({ client, scope }) {
213
+ const [accepting, setAccepting] = useState(null), [busy, setBusy] = useState(false), [message, setMessage] = useState("");
214
+ const live = useRef(true), writing = useRef(false);
215
+ useEffect(() => {
216
+ live.current = true;
217
+ void client.agentRequestSettings(scope).then(result => { if (live.current) { if (result?.ok && typeof result.accepting === "boolean") setAccepting(result.accepting); else setMessage(hrq("loadFailed")); } }, () => { if (live.current) setMessage(hrq("loadFailed")); });
218
+ return () => { live.current = false; };
219
+ }, [client, scope]);
220
+ const change = async event => {
221
+ if (writing.current || typeof accepting !== "boolean") return;
222
+ const value = !event.target.checked; writing.current = true; setBusy(true); setMessage("");
223
+ let result; try { result = await client.agentRequestSettings(scope, { accepting: value }); } catch { result = null; }
224
+ if (!live.current) return;
225
+ writing.current = false; setBusy(false);
226
+ if (result?.ok) { setAccepting(result.accepting); setMessage(hrq("saved")); } else setMessage(hrq("actionFailed"));
227
+ };
228
+ return html`<section class="card hub-owner-request-setting"><label class="check">
229
+ <input type="checkbox" checked=${accepting === false} disabled=${busy || accepting === null} onChange=${change} />
230
+ <span>${hrq("stopRequests")}</span></label><p class="note">${hrq("stopHint")}</p>
231
+ ${message ? html`<p class="note" role="status">${message}</p>` : null}</section>`;
232
+ }
233
+
234
+ export function OwnerAgentDiscoverySetting({ client, scope, exposure } = {}) {
235
+ if (!scope || !exposure?.id || typeof client?.agentRoomDiscovery !== "function") return null;
236
+ return html`<${AgentDiscoverySetting} key=${scope + ":" + exposure.id + ":" + exposure.revision + ":" + (exposure.sharingEpoch || 0)} client=${client} scope=${scope} exposure=${exposure} />`;
237
+ }
238
+ function AgentDiscoverySetting({ client, scope, exposure }) {
239
+ const [view, setView] = useState(null), [busy, setBusy] = useState(false), [error, setError] = useState("");
240
+ const live = useRef(true), writing = useRef(false), generation = useRef(0);
241
+ const load = async () => {
242
+ if (writing.current) return;
243
+ const mine = ++generation.current;
244
+ let r; try { r = await client.agentRoomDiscovery(scope, exposure.id); } catch { r = null; }
245
+ if (!live.current || mine !== generation.current) return;
246
+ if (r?.ok && typeof r.findable === "boolean" && typeof r.available === "boolean") { setView(r); setError(""); }
247
+ else setError(hrq("loadFailed"));
248
+ };
249
+ useEffect(() => { live.current = true; writing.current = false; setBusy(false); setView(null); void load(); return () => { live.current = false; generation.current++; }; }, [client, scope, exposure.id]);
250
+ const change = async event => {
251
+ if (writing.current || !view?.available) return;
252
+ const findable = event.target.checked; writing.current = true; setBusy(true); setError("");
253
+ const mine = ++generation.current;
254
+ let r; try { r = await client.agentRoomDiscovery(scope, exposure.id, { findable, ifRevision: view.revision, exposureRevision: view.exposureRevision }); } catch { r = null; }
255
+ if (!live.current || mine !== generation.current) return;
256
+ writing.current = false; setBusy(false);
257
+ if (r?.ok) setView(r); else { setError(hrq("actionFailed")); if (r?.status === 403 || r?.status === 409) void load(); }
258
+ };
259
+ return html`<section class="card hub-room-discovery-setting"><label class="check"><input type="checkbox" checked=${view?.findable === true} disabled=${busy || !view?.available} onChange=${change} /><span>${hrq("discoveryLabel")}</span></label>
260
+ <p class="note">${hrq("discoveryHint")}</p>
261
+ ${view?.reason ? html`<p class="note">${hrq(view.reason === "owner-disabled" ? "discoveryOptOut" : view.reason === "paused" ? "discoveryPaused" : "discoveryUnshared")}</p>` : null}
262
+ ${error ? html`<p class="note" role="alert">${error} <button class="btn btn-link" onClick=${() => { void load(); }}>${hrq("retry")}</button></p>` : null}
263
+ </section>`;
264
+ }