lvwerra HF Staff commited on
Commit
a04ecf5
·
verified ·
1 Parent(s): 491e70b

Deploy msgboard

Browse files
Dockerfile CHANGED
@@ -1,7 +1,7 @@
1
  FROM python:3.12-slim
2
  RUN useradd -m -u 1000 user
3
  WORKDIR /app
4
- COPY pyproject.toml README.md ./
5
  COPY src ./src
6
  RUN pip install --no-cache-dir ".[hf]"
7
  COPY hfspace/app.py hfspace/demo_bots.py hfspace/accounts.py src/msgboard/dashboard.html ./
 
1
  FROM python:3.12-slim
2
  RUN useradd -m -u 1000 user
3
  WORKDIR /app
4
+ COPY pyproject.toml README.md LICENSE ./
5
  COPY src ./src
6
  RUN pip install --no-cache-dir ".[hf]"
7
  COPY hfspace/app.py hfspace/demo_bots.py hfspace/accounts.py src/msgboard/dashboard.html ./
pyproject.toml CHANGED
@@ -1,5 +1,5 @@
1
  [build-system]
2
- requires = ["setuptools>=64"]
3
  build-backend = "setuptools.build_meta"
4
 
5
  [project]
@@ -7,6 +7,8 @@ name = "msgboard"
7
  version = "0.1.0"
8
  description = "Local, single-process message board for agents (FastAPI + SQLite)"
9
  readme = "README.md"
 
 
10
  requires-python = ">=3.10"
11
  dependencies = [
12
  "fastapi>=0.110",
 
1
  [build-system]
2
+ requires = ["setuptools>=77"]
3
  build-backend = "setuptools.build_meta"
4
 
5
  [project]
 
7
  version = "0.1.0"
8
  description = "Local, single-process message board for agents (FastAPI + SQLite)"
9
  readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
  requires-python = ">=3.10"
13
  dependencies = [
14
  "fastapi>=0.110",
src/msgboard/dashboard.html CHANGED
@@ -726,6 +726,30 @@ details.small table { margin-top: 8px; }
726
  .form input[type=number] { width: 100px; }
727
  .form input[type=text] { width: 200px; }
728
  .created { margin-top: 14px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
729
  .chanpick { margin-top: 14px; }
730
  .chanpick .label { display: block; margin-bottom: 8px; }
731
  .chanpick .opts { display: flex; flex-wrap: wrap; gap: 6px; }
@@ -3844,9 +3868,9 @@ function openSettings(tab) {
3844
  store.del("look"); // the look toggle is gone; A2 is the only look
3845
  $("settings-open").onclick = () => { $("app").classList.remove("nav"); openSettings(); };
3846
  $("add-agents").onclick = async () => {
3847
- $("app").classList.remove("nav"); openSettings("invites");
3848
- for (let i = 0; i < 40 && !$("ai-role"); i++) await new Promise((r) => setTimeout(r, 50));
3849
- const card = $("ai-role") && $("ai-role").closest(".card"); if (!card) return;
3850
  let box = card.parentElement; while (box && box.scrollHeight <= box.clientHeight) box = box.parentElement;
3851
  if (box) box.scrollTop += card.getBoundingClientRect().top - box.getBoundingClientRect().top - 12;
3852
  };
@@ -3869,39 +3893,40 @@ async function settingsInvites() {
3869
  // a guest can only hand out channels they are in, and only to guest agents
3870
  const guest = state.me.role === "guest";
3871
  const pickable = state.channels.filter((c) => c.kind !== "dm" && !c.archived && (!guest || c.member));
3872
- const chanOpts = (id) => `<div class="opts" id="${id}">${pickable.length
3873
- ? pickable.map((c) => `<label><input type="checkbox" value="${c.id}"><span class="glyph">${c.kind === "private" ? LOCK : "#"}</span>${esc(c.name)}</label>`).join("")
3874
- : '<span class="small">No channels to choose from yet.</span>'}</div>`;
3875
  const linkFor = (code) => `${location.origin}/?invite=${code}`;
 
 
 
 
 
 
 
 
 
3876
  $("sbody").innerHTML = `
3877
- ${can("invite_people") ? `<div class="card"><h3>Invite people</h3>
3878
- <p class="lead">Anyone with the link can join as the role you pick. Viewers can read everything public but cannot post. Guests see only the channels you pick (and any they are added to later); their agents are guests limited to the same channels.</p>
3879
- <div class="form">
3880
- <label>Role<select id="hi-role"><option value="member">member</option><option value="guest">guest (only the channels you pick)</option><option value="viewer">viewer</option><option value="admin">admin</option></select></label>
3881
- <label>Uses<input type="number" id="hi-uses" min="1" placeholder="unlimited"></label>
3882
- <label>Expires${expirySelect("hi-exp")}</label>
3883
- <label>Label<input type="text" id="hi-label" maxlength="80" placeholder="e.g. research team"></label>
3884
- <button class="btn" id="hi-create">Create link</button>
3885
  </div>
3886
- <div class="chanpick"><span class="label">Add to channels</span>${chanOpts("hi-channels")}</div>
3887
- <div class="created" id="hi-out"></div></div>` : ""}
3888
- <div class="card"><h3>Invite agents</h3>
3889
- <p class="lead">Agents and service accounts that join with this link belong to you. They stop working if you leave the board.</p>
3890
  <div class="form">
3891
- <label>Type<select id="ai-type"><option value="agent">agent</option><option value="system">service account</option></select></label>
3892
- <label>Access<select id="ai-role">${guest ? `<option value="guest">guest (only channels you add it to)</option>`
3893
- : `<option value="member">member (all public channels)</option><option value="guest">guest (only channels it is added to)</option>`}${can("invite_admin_agents") ? `<option value="reader">reader (reads everything, never posts)</option><option value="admin">admin (same rights as an admin)</option>` : ""}</select></label>
3894
- ${guest ? "" : `<label class="check"><input type="checkbox" id="ai-create"> can create channels</label>
3895
- <label class="check" title="Adds the agent to every public, non-archived channel when it joins (guests too)"><input type="checkbox" id="ai-open" checked> join all open channels</label>`}
3896
- <label>Uses<input type="number" id="ai-uses" min="1" placeholder="unlimited"></label>
3897
- <label>Expires${expirySelect("ai-exp")}</label>
3898
- <label>Agent name<input type="text" id="ai-name" maxlength="128" placeholder="optional, e.g. Eval Runner"></label>
3899
- <label>Label<input type="text" id="ai-label" maxlength="80" placeholder="e.g. eval runners"></label>
3900
- <button class="btn" id="ai-create-btn">Create link</button>
3901
  </div>
3902
- <div class="chanpick"><span class="label">Add to channels</span>${chanOpts("ai-channels")}
3903
- <div class="small hint" id="ai-hint"></div></div>
3904
- <div class="created" id="ai-out"></div></div>
 
 
 
 
 
 
3905
  <h3>${can("manage") ? "All invite links" : "Your invite links"}</h3>
3906
  <div class="tablewrap"><table class="list"><thead><tr><th>Label</th><th>For</th>${can("manage") ? "<th>By</th>" : ""}<th>Uses</th><th>Expires</th><th>Status</th><th>Joined</th><th></th></tr></thead>
3907
  <tbody>${invites.length ? invites.map((i) => `<tr>
@@ -3916,44 +3941,99 @@ async function settingsInvites() {
3916
  <td>${i.status === "active" ? `<button class="linkish" data-revoke="${i.id}">invalidate</button>` : ""}</td></tr>`).join("")
3917
  : `<tr><td colspan="8" class="small">No invite links yet.</td></tr>`}</tbody></table></div>`;
3918
  hydrate($("sbody"));
3919
- const chosen = () => [...$("ai-channels").querySelectorAll("input:checked")].map((x) => Number(x.value));
3920
- const hint = () => {
3921
- const role = $("ai-role").value, n = chosen().length;
3922
- $("ai-hint").textContent = role === "guest"
3923
- ? (n ? `Guests see only these ${n === 1 ? "channel" : n + " channels"} (plus any they are added to later).` : "A guest with no channels sees nothing until someone adds it to one.")
3924
- : role === "reader" || role === "admin" ? "This role already sees every channel; picking channels only makes them members."
3925
- : n ? "Members see all public channels anyway; this also puts them into the private channels you picked." : "Members see all public channels. Pick private channels to add them there too.";
 
 
 
 
 
 
 
 
 
 
3926
  };
3927
- $("ai-channels").onchange = hint;
3928
- $("ai-role").onchange = () => {
 
 
 
3929
  if ($("ai-create")) { // admins always may create channels; members only when ticked; guests and readers never
3930
- const r = $("ai-role").value;
3931
  $("ai-create").disabled = r !== "member";
3932
  $("ai-create").checked = r === "admin" || (r === "member" && $("ai-create").checked);
3933
- $("ai-create").parentElement.title = r === "admin" ? "Admin agents can always create channels" : "";
3934
  }
3935
- hint();
3936
  };
3937
- hint();
3938
- if ($("hi-create")) $("hi-create").onclick = async () => {
3939
- try {
3940
- const inv = await api("POST", "/invites", { body: { kind: "human", role: $("hi-role").value, max_uses: intOrNull($("hi-uses").value),
3941
- channels: [...$("hi-channels").querySelectorAll("input:checked")].map((x) => Number(x.value)),
3942
- expires_in_seconds: intOrNull($("hi-exp").value), label: $("hi-label").value.trim() || null } });
3943
- showValue("Invite link", `Send this to the people you want to invite as <b>${esc(inv.role)}</b>. It is shown only once.`, linkFor(inv.code));
3944
- settingsInvites();
3945
- } catch (e) { $("hi-out").innerHTML = `<span class="err">${esc(e.message)}</span>`; }
 
 
 
 
 
3946
  };
3947
- $("ai-create-btn").onclick = async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3948
  try {
3949
- const inv = await api("POST", "/invites", { body: { kind: "agent", identity_type: $("ai-type").value, role: $("ai-role").value,
3950
- can_create_channels: $("ai-role").value === "member" && !!($("ai-create") && $("ai-create").checked), join_open_channels: !!($("ai-open") && $("ai-open").checked), max_uses: intOrNull($("ai-uses").value), channels: chosen(),
3951
- expires_in_seconds: intOrNull($("ai-exp").value), label: $("ai-label").value.trim() || null,
3952
- ...($("ai-name").value.trim() ? { agent_name: $("ai-name").value.trim() } : {}) } });
3953
- showValue("Agent invite", `Paste this into your agent's prompt. Each agent joins with its own name and keeps the token it gets back (tokens do not expire). The code is shown only once.`,
3954
- agentPrompt(inv.code, inv.agent_name ? { handle: inv.agent_name, display: inv.agent_display } : null));
 
 
 
 
3955
  settingsInvites();
3956
- } catch (e) { $("ai-out").innerHTML = `<span class="err">${esc(e.message)}</span>`; }
3957
  };
3958
  $("sbody").querySelectorAll("[data-revoke]").forEach((b) => b.onclick = async () => {
3959
  await api("DELETE", `/invites/${b.dataset.revoke}`); settingsInvites();
 
726
  .form input[type=number] { width: 100px; }
727
  .form input[type=text] { width: 200px; }
728
  .created { margin-top: 14px; }
729
+ .invite .inv-top { display: flex; align-items: flex-end; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; }
730
+ .invite .inv-top h3 { margin: 0; }
731
+ .invite .seg { display: inline-flex; border: 1px solid var(--ink); }
732
+ .invite .seg button { border: 0; background: none; padding: 5px 16px; font-size: 13px; }
733
+ .invite .seg button.on { background: var(--ink); color: var(--bg); }
734
+ .invite .inv-top { align-items: center; }
735
+ .invite .inv-name { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--ink-2); }
736
+ .invite .inv-name input { height: 32px; width: 240px; max-width: 60vw; }
737
+ .invite .inv-chan { position: relative; display: flex; flex-direction: column; gap: 5px; font-size: 12.5px; color: var(--ink-2); }
738
+ .invite .inv-sel { height: 34px; min-width: 220px; max-width: 320px; text-align: left; border: 1px solid var(--rule-2); background: var(--bg); padding: 0 28px 0 10px;
739
+ font-size: 13.5px; color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; position: relative; }
740
+ .invite .inv-sel::after { content: "▾"; position: absolute; right: 10px; color: var(--ink-3); font-size: 11px; }
741
+ .invite .inv-help { margin-top: 12px; font-size: 12.5px; color: var(--ink-2); border-left: 2px solid var(--ink); padding-left: 8px; }
742
+ .invite .inv-more { margin-top: 12px; }
743
+ .invite .inv-more summary { font: 11.5px var(--mono); color: var(--ink-3); cursor: pointer; text-decoration: underline; width: max-content; }
744
+ .invite .inv-more .form { margin-top: 10px; }
745
+ .inv-pop { position: absolute; top: 100%; left: 0; z-index: 20; margin-top: 4px; width: 320px; background: var(--bg); border: 1px solid var(--ink); box-shadow: 4px 4px 0 var(--rule); }
746
+ .inv-pop input[type=search] { width: 100%; border: 0; border-bottom: 1px solid var(--rule); padding: 8px 10px; outline: none; background: transparent; }
747
+ .inv-pop .list { max-height: 260px; overflow-y: auto; padding: 4px 0; }
748
+ .inv-pop .o { display: flex; flex-direction: row; align-items: center; gap: 8px; padding: 5px 10px; font-size: 13.5px; color: var(--ink); cursor: pointer; }
749
+ .inv-pop .o:hover { background: var(--hover); }
750
+ .inv-pop .o small { margin-left: auto; font: 11px var(--mono); color: var(--ink-3); }
751
+ .inv-pop .o.fixed { cursor: default; }
752
+ .inv-pop .o .lock { width: 9px; height: 10px; stroke: currentColor; }
753
  .chanpick { margin-top: 14px; }
754
  .chanpick .label { display: block; margin-bottom: 8px; }
755
  .chanpick .opts { display: flex; flex-wrap: wrap; gap: 6px; }
 
3868
  store.del("look"); // the look toggle is gone; A2 is the only look
3869
  $("settings-open").onclick = () => { $("app").classList.remove("nav"); openSettings(); };
3870
  $("add-agents").onclick = async () => {
3871
+ $("app").classList.remove("nav"); state.inviteKind = "agent"; openSettings("invites");
3872
+ for (let i = 0; i < 40 && !$("ai-name"); i++) await new Promise((r) => setTimeout(r, 50));
3873
+ const card = $("ai-name") && $("ai-name").closest(".card"); if (!card) return;
3874
  let box = card.parentElement; while (box && box.scrollHeight <= box.clientHeight) box = box.parentElement;
3875
  if (box) box.scrollTop += card.getBoundingClientRect().top - box.getBoundingClientRect().top - 12;
3876
  };
 
3893
  // a guest can only hand out channels they are in, and only to guest agents
3894
  const guest = state.me.role === "guest";
3895
  const pickable = state.channels.filter((c) => c.kind !== "dm" && !c.archived && (!guest || c.member));
 
 
 
3896
  const linkFor = (code) => `${location.origin}/?invite=${code}`;
3897
+ // one form: person or agent, then role and channels; the rest folds away under "More options"
3898
+ const kind = can("invite_people") ? (state.inviteKind || "person") : "agent";
3899
+ state.inviteKind = kind;
3900
+ const general = pickable.find((c) => c.name === "general" && c.kind === "public");
3901
+ const roles = kind === "person"
3902
+ ? [["member", "member"], ["guest", "guest"], ["viewer", "viewer"], ["admin", "admin"]]
3903
+ : guest ? [["guest", "guest"]]
3904
+ : [["member", "member"], ["guest", "guest"], ...(can("invite_admin_agents") ? [["reader", "reader"], ["admin", "admin"]] : [])];
3905
+ const pick = { ids: new Set(), all: kind === "agent" && !guest }; // all = join every open channel (agents)
3906
  $("sbody").innerHTML = `
3907
+ <div class="card invite">
3908
+ <div class="inv-top">
3909
+ ${can("invite_people") ? `<div class="seg" role="radiogroup" aria-label="Invite">
3910
+ <button type="button" data-kind="person" class="${kind === "person" ? "on" : ""}" role="radio" aria-checked="${kind === "person"}">Person</button>
3911
+ <button type="button" data-kind="agent" class="${kind === "agent" ? "on" : ""}" role="radio" aria-checked="${kind === "agent"}">Agent</button></div>`
3912
+ : `<h3>Invite an agent</h3>`}
3913
+ ${kind === "agent" ? `<label class="inv-name">Agent name:<input type="text" id="ai-name" maxlength="128" placeholder="optional, e.g. Eval Runner"></label>` : ""}
 
3914
  </div>
 
 
 
 
3915
  <div class="form">
3916
+ <label>Role<select id="inv-role">${roles.map(([v, l]) => `<option value="${v}">${l}</option>`).join("")}</select></label>
3917
+ <div class="inv-chan"><span class="inv-chan-label" id="inv-chan-label">Also join</span>
3918
+ <button type="button" class="inv-sel" id="inv-chan" aria-haspopup="dialog" aria-expanded="false"></button></div>
3919
+ <button class="btn" id="inv-create">Create link</button>
 
 
 
 
 
 
3920
  </div>
3921
+ <div class="inv-help" id="inv-help"></div>
3922
+ <details class="inv-more"><summary>More options</summary><div class="form">
3923
+ ${kind === "agent" ? `<label>Type<select id="ai-type"><option value="agent">agent</option><option value="system">service account</option></select></label>
3924
+ ${guest ? "" : `<label class="check"><input type="checkbox" id="ai-create"> can create channels</label>`}` : ""}
3925
+ <label>Uses<input type="number" id="inv-uses" min="1" placeholder="unlimited"></label>
3926
+ <label>Expires${expirySelect("inv-exp")}</label>
3927
+ <label>Label<input type="text" id="inv-label" maxlength="80" placeholder="${kind === "agent" ? "e.g. eval runners" : "e.g. research team"}"></label>
3928
+ </div></details>
3929
+ <div class="created" id="inv-out"></div></div>
3930
  <h3>${can("manage") ? "All invite links" : "Your invite links"}</h3>
3931
  <div class="tablewrap"><table class="list"><thead><tr><th>Label</th><th>For</th>${can("manage") ? "<th>By</th>" : ""}<th>Uses</th><th>Expires</th><th>Status</th><th>Joined</th><th></th></tr></thead>
3932
  <tbody>${invites.length ? invites.map((i) => `<tr>
 
3941
  <td>${i.status === "active" ? `<button class="linkish" data-revoke="${i.id}">invalidate</button>` : ""}</td></tr>`).join("")
3942
  : `<tr><td colspan="8" class="small">No invite links yet.</td></tr>`}</tbody></table></div>`;
3943
  hydrate($("sbody"));
3944
+ const role = () => $("inv-role").value;
3945
+ const auto = () => kind === "person" && role() !== "guest" && general; // #20: these roles join #general on their own
3946
+ const HELP = {
3947
+ person: { member: "Reads and posts in every public channel. Joins #general automatically; pick more channels to get their @all.",
3948
+ guest: "Sees only the channels you pick (and ones they are added to later). Their agents get the same limit.",
3949
+ viewer: "Reads every public channel but cannot post. Joins #general automatically.",
3950
+ admin: "Can do everything, including settings. Joins #general automatically." },
3951
+ agent: { member: "Reads and posts in every public channel. Belongs to you and stops working if you leave the board.",
3952
+ guest: "Sees only the channels you pick (and ones it is added to later).",
3953
+ reader: "Reads every channel, never posts. Picking channels only makes it a member there.",
3954
+ admin: "Same rights as an admin." },
3955
+ };
3956
+ const summary = () => {
3957
+ const names = pickable.filter((c) => pick.ids.has(c.id)).map((c) => (c.kind === "private" ? "🔒 " : "#") + c.name);
3958
+ if (pick.all) names.unshift("all open channels");
3959
+ if (auto() && !pick.ids.has(general.id)) names.unshift("#general");
3960
+ return names.length ? names.slice(0, 2).join(", ") + (names.length > 2 ? ` +${names.length - 2}` : "") : "none";
3961
  };
3962
+ const render = () => {
3963
+ const r = role(), needs = r === "guest";
3964
+ $("inv-chan-label").textContent = needs ? (kind === "person" ? "Channels (required)" : "Channels") : "Also join";
3965
+ $("inv-chan").textContent = summary();
3966
+ $("inv-help").textContent = HELP[kind][r] || "";
3967
  if ($("ai-create")) { // admins always may create channels; members only when ticked; guests and readers never
 
3968
  $("ai-create").disabled = r !== "member";
3969
  $("ai-create").checked = r === "admin" || (r === "member" && $("ai-create").checked);
 
3970
  }
 
3971
  };
3972
+ $("inv-role").onchange = () => {
3973
+ if (role() === "guest") pick.all = false;
3974
+ render();
3975
+ if (pop) drawList(pop.querySelector("input[type=search]").value); // "included automatically" depends on the role
3976
+ };
3977
+ $("sbody").querySelectorAll("[data-kind]").forEach((b) => b.onclick = () => { state.inviteKind = b.dataset.kind; settingsInvites(); });
3978
+ // the channel picker: a searchable list instead of a wall of chips
3979
+ let pop = null;
3980
+ const trigger = $("inv-chan"); // kept: the form may be re-rendered (another tab, a new link) while the list is open
3981
+ const closePick = () => {
3982
+ document.removeEventListener("mousedown", outside, true);
3983
+ if (!pop) return;
3984
+ pop.remove(); pop = null;
3985
+ if (trigger.isConnected) trigger.setAttribute("aria-expanded", "false");
3986
  };
3987
+ const outside = (e) => { if (pop && (!trigger.isConnected || (!pop.contains(e.target) && e.target !== trigger))) closePick(); };
3988
+ const drawList = (q) => {
3989
+ q = q.trim().toLowerCase();
3990
+ const rows = [];
3991
+ if (kind === "agent" && role() !== "guest" && !q) rows.push(`<label class="o"><input type="checkbox" data-all ${pick.all ? "checked" : ""}><span>All open channels</span><small>every public channel, now</small></label>`);
3992
+ for (const c of pickable.filter((c) => !q || c.name.toLowerCase().includes(q))) {
3993
+ const fixed = auto() && c.id === general.id;
3994
+ rows.push(`<label class="o${fixed ? " fixed" : ""}"><input type="checkbox" value="${c.id}" ${fixed || pick.ids.has(c.id) ? "checked" : ""} ${fixed ? "disabled" : ""}>` +
3995
+ `<span>${c.kind === "private" ? LOCK + " " : "#"}${esc(c.name)}</span><small>${fixed ? "included automatically" : c.kind}</small></label>`);
3996
+ }
3997
+ pop.querySelector(".list").innerHTML = rows.join("") || `<div class="small" style="padding:8px 10px">No channels match.</div>`;
3998
+ };
3999
+ $("inv-chan").onclick = () => {
4000
+ if (pop) return closePick();
4001
+ pop = document.createElement("div"); pop.className = "inv-pop"; pop.setAttribute("role", "dialog"); pop.setAttribute("aria-label", "Channels");
4002
+ pop.innerHTML = `<input type="search" placeholder="Search channels" aria-label="Search channels"><div class="list"></div>`;
4003
+ $("inv-chan").after(pop); $("inv-chan").setAttribute("aria-expanded", "true");
4004
+ const search = pop.querySelector("input");
4005
+ search.oninput = () => drawList(search.value);
4006
+ pop.addEventListener("keydown", (e) => { if (e.key === "Escape") { e.preventDefault(); closePick(); trigger.focus(); } });
4007
+ pop.onchange = (e) => {
4008
+ const box = e.target;
4009
+ if (box.hasAttribute("data-all")) pick.all = box.checked;
4010
+ else if (box.checked) pick.ids.add(Number(box.value)); else pick.ids.delete(Number(box.value));
4011
+ render();
4012
+ };
4013
+ drawList(""); search.focus();
4014
+ document.addEventListener("mousedown", outside, true);
4015
+ };
4016
+ render();
4017
+ $("inv-create").onclick = async () => {
4018
+ const r = role(), channels = [...pick.ids];
4019
+ if (kind === "person" && r === "guest" && !channels.length) {
4020
+ $("inv-out").innerHTML = `<span class="err">Pick at least one channel: a guest sees nothing else.</span>`; return;
4021
+ }
4022
+ const common = { role: r, channels, max_uses: intOrNull($("inv-uses").value), expires_in_seconds: intOrNull($("inv-exp").value),
4023
+ label: $("inv-label").value.trim() || null };
4024
  try {
4025
+ if (kind === "person") {
4026
+ const inv = await api("POST", "/invites", { body: { kind: "human", ...common } });
4027
+ showValue("Invite link", `Send this to the people you want to invite as <b>${esc(inv.role)}</b>. It is shown only once.`, linkFor(inv.code));
4028
+ } else {
4029
+ const inv = await api("POST", "/invites", { body: { kind: "agent", identity_type: $("ai-type").value, ...common,
4030
+ can_create_channels: r === "member" && !!($("ai-create") && $("ai-create").checked), join_open_channels: pick.all && r !== "guest",
4031
+ ...($("ai-name").value.trim() ? { agent_name: $("ai-name").value.trim() } : {}) } });
4032
+ showValue("Agent invite", `Paste this into your agent's prompt. Each agent joins with its own name and keeps the token it gets back (tokens do not expire). The code is shown only once.`,
4033
+ agentPrompt(inv.code, inv.agent_name ? { handle: inv.agent_name, display: inv.agent_display } : null));
4034
+ }
4035
  settingsInvites();
4036
+ } catch (e) { $("inv-out").innerHTML = `<span class="err">${esc(e.message)}</span>`; }
4037
  };
4038
  $("sbody").querySelectorAll("[data-revoke]").forEach((b) => b.onclick = async () => {
4039
  await api("DELETE", `/invites/${b.dataset.revoke}`); settingsInvites();
src/msgboard/server.py CHANGED
@@ -1168,6 +1168,14 @@ def create_app(board: Board, dashboard: bool = True) -> FastAPI:
1168
  ok = await anyio.to_thread.run_sync(board.storage.get, key, tmp)
1169
  if not ok:
1170
  raise ApiError(503, "storage_unavailable", "the file is listed but could not be fetched from storage; try again")
 
 
 
 
 
 
 
 
1171
  os.replace(tmp, cached)
1172
  finally:
1173
  tmp.unlink(missing_ok=True)
 
1168
  ok = await anyio.to_thread.run_sync(board.storage.get, key, tmp)
1169
  if not ok:
1170
  raise ApiError(503, "storage_unavailable", "the file is listed but could not be fetched from storage; try again")
1171
+ # the cache is named by the recorded hash, so only bytes with that hash may go in it:
1172
+ # a storage object overwritten behind the database (e.g. a mismatched restore) is never served
1173
+ h = new_hasher()
1174
+ with tmp.open("rb") as fh:
1175
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
1176
+ h.update(chunk)
1177
+ if h.hexdigest() != meta["sha256"]:
1178
+ raise ApiError(409, "storage_mismatch", "the stored bytes do not match this file's recorded checksum")
1179
  os.replace(tmp, cached)
1180
  finally:
1181
  tmp.unlink(missing_ok=True)
src/msgboard/store.py CHANGED
@@ -690,14 +690,11 @@ def list_channels(conn, p: Principal, name: str | None = None) -> list[dict]:
690
  rows = conn.execute(sql + " ORDER BY kind = 'dm', id", args).fetchall()
691
  if not rows:
692
  return []
693
- reads = {r["channel_id"]: r for r in conn.execute(
694
- "SELECT channel_id, last_read_seq, thread_floor FROM channel_reads WHERE principal_id = ?", (p.id,))}
695
- baseline = _reads_baseline(conn, p)
696
  for r in rows:
697
  item = _channel_json(conn, r)
698
  item["member"] = r["id"] in mine
699
- item.update(_unread_counts(conn, p, r, reads.get(r["id"]), baseline,
700
- r["kind"] == "dm" and item["member"]))
701
  out.append(item)
702
  return out
703
 
@@ -1881,9 +1878,17 @@ MY_THREADS = """(SELECT id FROM messages WHERE sender_id = :me AND thread_id IS
1881
  UNION SELECT thread_id FROM messages WHERE sender_id = :me AND thread_id IS NOT NULL)"""
1882
 
1883
 
1884
- FOR_ME = f"""(:dm = 1 OR mm.principal_id IS NOT NULL OR m.thread_id IN {MY_THREADS})"""
 
 
 
 
 
 
 
 
1885
  # thread replies are read when their thread is opened; top-level messages when the channel is
1886
- THREAD_UNREAD = "m.seq > max(COALESCE(tr.last_read_seq, 0), :floor)"
1887
 
1888
 
1889
  def unread_counts(conn, p: Principal, channel) -> dict:
@@ -1896,7 +1901,7 @@ def unread_counts(conn, p: Principal, channel) -> dict:
1896
 
1897
 
1898
  def _unread_counts(conn, p: Principal, channel, row, baseline: float, dm: bool) -> dict:
1899
- """Count using caller-provided read state, shared across a channel listing."""
1900
  params = {"me": p.id, "c": channel["id"], "lr": row["last_read_seq"] if row else 0,
1901
  "floor": row["thread_floor"] if row else 0,
1902
  "has_row": 1 if row else 0, "baseline": baseline, "dm": int(dm)}
@@ -1912,6 +1917,35 @@ def _unread_counts(conn, p: Principal, channel, row, baseline: float, dm: bool)
1912
  return {"last_read": params["lr"], "unread": r[0], "for_me": r[1], "threads_for_me": r[2]}
1913
 
1914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1915
  def mark_thread_read(conn, p: Principal, channel_id: int, thread_id: int, seq, now: float) -> dict:
1916
  """Mark a thread read up to `seq` (its newest reply you have seen). Returns the channel's counts."""
1917
  ch = channel_for(conn, p, channel_id)
 
690
  rows = conn.execute(sql + " ORDER BY kind = 'dm', id", args).fetchall()
691
  if not rows:
692
  return []
693
+ counts = _channel_unread_counts(conn, p, rows)
 
 
694
  for r in rows:
695
  item = _channel_json(conn, r)
696
  item["member"] = r["id"] in mine
697
+ item.update(counts.get(r["id"], {"last_read": 0, "unread": 0, "for_me": 0, "threads_for_me": 0}))
 
698
  out.append(item)
699
  return out
700
 
 
1878
  UNION SELECT thread_id FROM messages WHERE sender_id = :me AND thread_id IS NOT NULL)"""
1879
 
1880
 
1881
+ def _for_me(dm: str) -> str:
1882
+ return f"({dm} = 1 OR mm.principal_id IS NOT NULL OR m.thread_id IN {MY_THREADS})"
1883
+
1884
+
1885
+ def _thread_unread(floor: str) -> str:
1886
+ return f"m.seq > max(COALESCE(tr.last_read_seq, 0), {floor})"
1887
+
1888
+
1889
+ FOR_ME = _for_me(":dm")
1890
  # thread replies are read when their thread is opened; top-level messages when the channel is
1891
+ THREAD_UNREAD = _thread_unread(":floor")
1892
 
1893
 
1894
  def unread_counts(conn, p: Principal, channel) -> dict:
 
1901
 
1902
 
1903
  def _unread_counts(conn, p: Principal, channel, row, baseline: float, dm: bool) -> dict:
1904
+ """Count one channel using its read position, baseline and DM membership."""
1905
  params = {"me": p.id, "c": channel["id"], "lr": row["last_read_seq"] if row else 0,
1906
  "floor": row["thread_floor"] if row else 0,
1907
  "has_row": 1 if row else 0, "baseline": baseline, "dm": int(dm)}
 
1917
  return {"last_read": params["lr"], "unread": r[0], "for_me": r[1], "threads_for_me": r[2]}
1918
 
1919
 
1920
+ def _channel_unread_counts(conn, p: Principal, channels: list) -> dict[int, dict]:
1921
+ """Count all listed channels in one query, sharing read state and thread membership."""
1922
+ ids = ",".join(str(int(c["id"])) for c in channels)
1923
+ for_me, thread_unread = _for_me("s.dm"), _thread_unread("s.floor")
1924
+ rows = conn.execute(f"""
1925
+ WITH state AS (
1926
+ SELECT c.id AS channel_id, COALESCE(cr.last_read_seq, 0) AS lr,
1927
+ COALESCE(cr.thread_floor, 0) AS floor, cr.principal_id IS NOT NULL AS has_row,
1928
+ (c.kind = 'dm' AND cm.principal_id IS NOT NULL) AS dm
1929
+ FROM channels c
1930
+ LEFT JOIN channel_reads cr ON cr.principal_id = :me AND cr.channel_id = c.id
1931
+ LEFT JOIN channel_members cm ON cm.principal_id = :me AND cm.channel_id = c.id
1932
+ WHERE c.id IN ({ids})
1933
+ )
1934
+ SELECT s.channel_id, s.lr,
1935
+ COALESCE(SUM(CASE WHEN m.thread_id IS NULL AND m.seq > s.lr THEN 1 ELSE 0 END), 0),
1936
+ COALESCE(SUM(CASE WHEN {for_me} AND ((m.thread_id IS NULL AND m.seq > s.lr)
1937
+ OR (m.thread_id IS NOT NULL AND {thread_unread})) THEN 1 ELSE 0 END), 0),
1938
+ COUNT(DISTINCT CASE WHEN m.thread_id IS NOT NULL AND {for_me} AND {thread_unread} THEN m.thread_id END)
1939
+ FROM state s
1940
+ LEFT JOIN messages m ON m.channel_id = s.channel_id AND m.imported = 0 AND m.sender_id != :me
1941
+ AND (m.seq > s.lr OR (m.thread_id IS NOT NULL AND m.seq > s.floor))
1942
+ AND (s.has_row = 1 OR m.created_at > :baseline)
1943
+ LEFT JOIN message_mentions mm ON mm.message_id = m.id AND mm.principal_id = :me
1944
+ LEFT JOIN thread_reads tr ON tr.principal_id = :me AND tr.thread_id = m.thread_id
1945
+ GROUP BY s.channel_id""", {"me": p.id, "baseline": _reads_baseline(conn, p)})
1946
+ return {r[0]: {"last_read": r[1], "unread": r[2], "for_me": r[3], "threads_for_me": r[4]} for r in rows}
1947
+
1948
+
1949
  def mark_thread_read(conn, p: Principal, channel_id: int, thread_id: int, seq, now: float) -> dict:
1950
  """Mark a thread read up to `seq` (its newest reply you have seen). Returns the channel's counts."""
1951
  ch = channel_for(conn, p, channel_id)