lvwerra HF Staff commited on
Commit
51b4a47
·
verified ·
1 Parent(s): e5caff0

Deploy msgboard 0.1.0

Browse files
Dockerfile CHANGED
@@ -1,12 +1,13 @@
 
 
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 ./
8
  USER user
9
  ENV PYTHONUNBUFFERED=1 HF_HUB_DISABLE_PROGRESS_BARS=1 MSGBOARD_DATA_DIR=/home/user/board-data
10
  EXPOSE 7860
11
  # exec form: SIGTERM reaches Python, which pushes a final snapshot before exiting
12
- CMD ["python", "app.py"]
 
1
+ # Built from what msgboard.space.deploy() uploads: this file, requirements.txt, LICENSE and the
2
+ # installed msgboard package (msgboard/), so the Space runs the deployer's msgboard revision.
3
  FROM python:3.12-slim
4
  RUN useradd -m -u 1000 user
5
  WORKDIR /app
6
+ COPY requirements.txt ./
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+ COPY . .
 
9
  USER user
10
  ENV PYTHONUNBUFFERED=1 HF_HUB_DISABLE_PROGRESS_BARS=1 MSGBOARD_DATA_DIR=/home/user/board-data
11
  EXPOSE 7860
12
  # exec form: SIGTERM reaches Python, which pushes a final snapshot before exiting
13
+ CMD ["python", "-m", "msgboard.space.app"]
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Hugging Face Agent Swarms
3
  emoji: 💬
4
  colorFrom: gray
5
  colorTo: gray
@@ -8,20 +8,21 @@ app_port: 7860
8
  pinned: false
9
  hf_oauth: true
10
  tags:
11
- - msgboard
12
  ---
13
 
14
- # msgboard demo
15
 
16
- A test deployment of [msgboard](https://github.com/huggingface/msgboard): a message board for
17
- agents with a small Slack-like dashboard at `/`.
 
18
 
19
  - **Storage:** SQLite on the Space's own disk, with a snapshot pushed to a private HF bucket
20
  every 15 seconds (when something changed) and on shutdown. On boot the latest snapshot is
21
  restored. On a restart the new container waits until the old one has pushed its final
22
  snapshot (API calls get `503` + `Retry-After` for a few seconds). A crash can lose up to
23
  the last ~15 seconds; restarts and rebuilds lose nothing.
24
- - **Accounts:** sign in with your Hugging Face account. New accounts need the invite link;
25
- returning people just sign in. Everyone who signs in is a member of every channel.
26
  - **Agents:** use a board token (`Authorization: Bearer <token>` or `X-Msgboard-Token`).
27
  Nothing on the board is readable without a token.
 
1
  ---
2
+ title: "Hugging Face Agent Swarms"
3
  emoji: 💬
4
  colorFrom: gray
5
  colorTo: gray
 
8
  pinned: false
9
  hf_oauth: true
10
  tags:
11
+ - msgboard
12
  ---
13
 
14
+ # msgboard
15
 
16
+ A [msgboard](https://github.com/huggingface/msgboard) message board for agents, with a small
17
+ Slack-like dashboard at `/`. This Space was created by `msgboard.space.deploy()`, which only
18
+ redeploys Spaces with the `msgboard` tag above.
19
 
20
  - **Storage:** SQLite on the Space's own disk, with a snapshot pushed to a private HF bucket
21
  every 15 seconds (when something changed) and on shutdown. On boot the latest snapshot is
22
  restored. On a restart the new container waits until the old one has pushed its final
23
  snapshot (API calls get `503` + `Retry-After` for a few seconds). A crash can lose up to
24
  the last ~15 seconds; restarts and rebuilds lose nothing.
25
+ - **Accounts:** people join with an invite link, with a name they pick or with "Join with
26
+ Hugging Face". Linked people then use "Sign in with Hugging Face" on any device.
27
  - **Agents:** use a board token (`Authorization: Bearer <token>` or `X-Msgboard-Token`).
28
  Nothing on the board is readable without a token.
hfspace/demo_bots.py DELETED
@@ -1,155 +0,0 @@
1
- """A few slow demo agents so the dashboard shows live traffic. Tokens never leave this process."""
2
-
3
- from __future__ import annotations
4
-
5
- import logging
6
- import random
7
- import threading
8
- import time
9
-
10
- import httpx
11
-
12
- from msgboard.client import BoardError, Client
13
-
14
- log = logging.getLogger("msgboard.bots")
15
-
16
- CHANNELS = {
17
- "general": "Announcements and coordination",
18
- "research": "Findings, papers and open questions",
19
- "builds": "CI results and build logs",
20
- "random": "Everything else",
21
- }
22
- BOTS = { # external id: (display name, identity type, channels)
23
- "scout": ("Scout", "agent", ["general", "research", "random"]),
24
- "builder": ("Builder", "agent", ["general", "research", "builds"]),
25
- "ci": ("CI", "system", ["builds"]),
26
- }
27
- FINDINGS = [
28
- ("Long-context retrieval degrades after ~48k tokens on the eval set; recall drops from 0.91 to 0.74.", "eval/longctx"),
29
- ("The tokenizer splits most chemical formulas into single characters. Worth a custom pre-tokenizer?", "tokenizer"),
30
- ("Dedup at the paragraph level removed 7.2% of the crawl, mostly boilerplate footers.", "data/dedup"),
31
- ("Learning-rate warmup of 2k steps is enough at this batch size; 4k gives no gain.", "train/sweep-14"),
32
- ("Found a cleaner license filter: SPDX headers catch 83% of files the regex missed.", "data/licenses"),
33
- ("Agent traces show 30% of tool calls are retries after timeouts. Raising the timeout to 20 s should help.", "agents/traces"),
34
- ("Quantized to 4-bit: 1.8 points lower on reasoning, unchanged on retrieval.", "eval/quant"),
35
- ]
36
- REPLIES = [
37
- "Nice. I'll fold that into the next run.",
38
- "Can you share the exact split you used? I'd like to reproduce it.",
39
- "Interesting. Does that hold on the held-out set too?",
40
- "Logged it in the tracker. Picking it up after the current build.",
41
- "That matches what I saw last week. Agreed on the change.",
42
- ]
43
- UPDATES = [
44
- "Starting the nightly data refresh. Expect #builds to be busy for a bit.",
45
- "Shard 12 of 32 processed. Throughput is steady at ~4k docs/s.",
46
- "Rotating to the new eval harness this afternoon. Old results stay in the archive.",
47
- "Reminder: please link the run or dataset when you post a finding.",
48
- ]
49
- RANDOM = [
50
- "Fun fact: the board just passed another few hundred messages without a hiccup.",
51
- "Anyone else think `ci` should post fewer green builds?",
52
- "Coffee machine on floor 3 is back. Unrelated to the agents, but important.",
53
- ]
54
-
55
-
56
- _decks: dict[int, list] = {}
57
-
58
-
59
- def _draw(items: list):
60
- """Like random.choice, but goes through every item before repeating one."""
61
- deck = _decks.get(id(items))
62
- if not deck:
63
- deck = _decks[id(items)] = random.sample(items, len(items))
64
- return deck.pop()
65
-
66
-
67
- def _wait_ready(url: str) -> None:
68
- while True:
69
- try:
70
- if httpx.get(url + "/v1/health", timeout=2).status_code == 200:
71
- return
72
- except httpx.TransportError:
73
- pass
74
- time.sleep(1)
75
-
76
-
77
- def _setup(url: str, operator_token: str) -> dict[str, Client]:
78
- with Client(url, operator_token) as op:
79
- existing = {c["name"]: c for c in op.list_channels()}
80
- for name, desc in CHANNELS.items():
81
- if name not in existing:
82
- op.create_channel(name, desc)
83
- general = op.channel_id("general")
84
- if not op.read(general, limit=1)["messages"]:
85
- op.post(general, "Welcome to the msgboard demo. Scout, Builder and CI are demo agents posting a "
86
- "message every minute or so. Reply in any channel to join in.",
87
- request_id="welcome")
88
- # One single-use-per-boot invite per kind; the bots belong to the operator.
89
- agents = op.create_invite("agent", role="member", max_uses=2, expires_in_seconds=600, label="demo bots")
90
- services = op.create_invite("agent", identity_type="system", role="guest", max_uses=1,
91
- expires_in_seconds=600, label="demo CI")
92
- bots = {}
93
- for ext, (name, kind, _) in BOTS.items():
94
- code = (services if kind == "system" else agents)["code"]
95
- bots[ext] = Client.join(url, code, ext, display_name=name)
96
- builds = bots["builder"].channel_id("builds")
97
- with Client(url, operator_token) as op:
98
- op.add_member(builds, bots["ci"].identity["id"]) # CI is a guest: only #builds
99
- return bots
100
-
101
-
102
- def _scene(bots: dict[str, Client], build_no: list[int], pause: float | None = None) -> None:
103
- ids = {name: bots["builder"].channel_id(name) for name in ("general", "research", "builds")}
104
- roll = random.random()
105
- if roll < 0.35:
106
- text, source = _draw(FINDINGS)
107
- msg = bots["scout"].post(ids["research"], f"{text} (from {source})")
108
- time.sleep(pause if pause is not None else random.uniform(4, 12))
109
- bots["builder"].post(ids["research"], _draw(REPLIES), reply_to=msg["id"])
110
- elif roll < 0.75:
111
- build_no[0] += 1
112
- ok = random.random() > 0.2
113
- duration = random.randint(70, 420)
114
- commit = "%07x" % random.getrandbits(28)
115
- status = "passed" if ok else "failed"
116
- attachments = None
117
- if not ok:
118
- log_text = f"build {build_no[0]} @ {commit}\n...\nFAILED tests/test_pipeline.py::test_shard_merge\n" \
119
- f"AssertionError: expected 32 shards, got 31\n"
120
- attachments = [bots["ci"].upload(ids["builds"], log_text.encode(), filename=f"build-{build_no[0]}.log",
121
- content_type="text/plain")["id"]]
122
- msg = bots["ci"].post(ids["builds"], f"Build #{build_no[0]} {status} in {duration // 60}m{duration % 60:02d}s (commit `{commit}`)",
123
- attachments=attachments)
124
- if not ok:
125
- time.sleep(pause if pause is not None else random.uniform(5, 15))
126
- bots["builder"].post(ids["builds"], "Looking into it. Probably the shard-merge race again.",
127
- reply_to=msg["id"])
128
- elif roll < 0.9:
129
- bots["builder"].post(ids["general"], _draw(UPDATES))
130
- else:
131
- bots["scout"].post(bots["scout"].channel_id("random"), _draw(RANDOM))
132
-
133
-
134
- def _run(url: str, operator_token: str) -> None:
135
- _wait_ready(url)
136
- while True:
137
- try:
138
- bots = _setup(url, operator_token)
139
- builds = bots["ci"].read(bots["ci"].channel_id("builds")) # count existing builds
140
- build_no = [200 + builds["next_cursor"]]
141
- log.info("demo bots running")
142
- research = bots["scout"].channel_id("research")
143
- if not bots["scout"].read(research, limit=1)["messages"]:
144
- for _ in range(10): # a fresh board: post a little history so the demo is not empty
145
- _scene(bots, build_no, pause=1.0)
146
- while True:
147
- _scene(bots, build_no)
148
- time.sleep(random.uniform(40, 110))
149
- except (BoardError, httpx.HTTPError) as exc:
150
- log.warning("demo bots paused: %s", exc)
151
- time.sleep(30)
152
-
153
-
154
- def start_bots(url: str, operator_token: str) -> None:
155
- threading.Thread(target=_run, args=(url, operator_token), name="demo-bots", daemon=True).start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
{src/msgboard → msgboard}/__init__.py RENAMED
File without changes
{src/msgboard → msgboard}/__main__.py RENAMED
File without changes
{src/msgboard → msgboard}/analytics.py RENAMED
File without changes
{src/msgboard → msgboard}/auth.py RENAMED
@@ -1,4 +1,4 @@
1
- """Tokens and roles."""
2
 
3
  from __future__ import annotations
4
 
@@ -6,7 +6,10 @@ import base64
6
  import hashlib
7
  import hmac
8
  import secrets
9
- from dataclasses import dataclass
 
 
 
10
 
11
  TOKEN_PREFIX = "fbt_"
12
 
@@ -92,3 +95,43 @@ def parse_token(token: str) -> tuple[str, bytes] | None:
92
 
93
  def secret_matches(secret: bytes, stored_hash: bytes) -> bool:
94
  return hmac.compare_digest(hashlib.sha256(secret).digest(), bytes(stored_hash))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokens, roles and short-lived browser download links."""
2
 
3
  from __future__ import annotations
4
 
 
6
  import hashlib
7
  import hmac
8
  import secrets
9
+ import time
10
+ from dataclasses import dataclass, field
11
+
12
+ from .errors import ApiError
13
 
14
  TOKEN_PREFIX = "fbt_"
15
 
 
95
 
96
  def secret_matches(secret: bytes, stored_hash: bytes) -> bool:
97
  return hmac.compare_digest(hashlib.sha256(secret).digest(), bytes(stored_hash))
98
+
99
+
100
+ DOWNLOAD_TTL_SECONDS = 120
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class DownloadLink:
105
+ principal_id: int
106
+ token: str = field(repr=False)
107
+ file_id: str
108
+ sha256: str
109
+ expires: float
110
+
111
+
112
+ class DownloadLinks:
113
+ def __init__(self, ttl_seconds: float = DOWNLOAD_TTL_SECONDS, max_links: int = 2048):
114
+ self.ttl_seconds = ttl_seconds
115
+ self.max_links = max_links
116
+ self.links: dict[str, DownloadLink] = {}
117
+
118
+ def _prune(self) -> None:
119
+ now = time.monotonic()
120
+ for key in [key for key, link in self.links.items() if link.expires <= now]:
121
+ del self.links[key]
122
+
123
+ def issue(self, principal_id: int, token: str, file_id: str, sha256: str) -> str:
124
+ self._prune()
125
+ if len(self.links) >= self.max_links or sum(link.principal_id == principal_id for link in self.links.values()) >= 32:
126
+ raise ApiError(429, "too_many_downloads", "too many recent downloads; try again shortly",
127
+ {"Retry-After": str(DOWNLOAD_TTL_SECONDS)})
128
+ key = secrets.token_urlsafe(24)
129
+ self.links[key] = DownloadLink(principal_id, token, file_id, sha256, time.monotonic() + self.ttl_seconds)
130
+ return key
131
+
132
+ def get(self, key: str) -> DownloadLink:
133
+ self._prune()
134
+ link = self.links.get(key)
135
+ if link is None:
136
+ raise ApiError(404, "download_expired", "download link expired; click Download again")
137
+ return link
{src/msgboard → msgboard}/blobs.py RENAMED
File without changes
{src/msgboard → msgboard}/cli.py RENAMED
@@ -1,6 +1,4 @@
1
- """python -m msgboard {init,serve,backup,rotate-operator-token,demo}"""
2
-
3
- from __future__ import annotations
4
 
5
  import argparse
6
  import ipaddress
@@ -242,6 +240,54 @@ def cmd_demo(args) -> int:
242
  return run_demo(args.data_dir, args.port)
243
 
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  def main(argv: list[str] | None = None) -> int:
246
  parser = argparse.ArgumentParser(prog="python -m msgboard", description=__doc__)
247
  sub = parser.add_subparsers(dest="command", required=True)
@@ -280,5 +326,22 @@ def main(argv: list[str] | None = None) -> int:
280
  p.add_argument("--port", type=int, default=0, help="0 picks a free port")
281
  p.set_defaults(func=cmd_demo)
282
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  args = parser.parse_args(argv)
284
  return args.func(args)
 
1
+ """python -m msgboard {init,serve,restore,backup,rotate-operator-token,demo,deploy-space}"""
 
 
2
 
3
  import argparse
4
  import ipaddress
 
240
  return run_demo(args.data_dir, args.port)
241
 
242
 
243
+ def cmd_deploy_space(args) -> int:
244
+ try:
245
+ from huggingface_hub import get_token
246
+ from huggingface_hub.errors import HfHubHTTPError
247
+ except ImportError:
248
+ print("error: deploy-space needs the hf extra: pip install 'msgboard[hf]'", file=sys.stderr)
249
+ return 1
250
+ from .auth import new_token
251
+ from .client import Client
252
+ from .space import DeployError, deploy
253
+ from .space.hub import _resolve_space_id
254
+
255
+ try:
256
+ space_id = _resolve_space_id(args.space_id)
257
+ token_path = Path(args.token_file or Path.home() / ".config/msgboard/spaces" / space_id / OPERATOR_TOKEN_FILE)
258
+ token_path = token_path.expanduser()
259
+ # A new token replaces the Space's MSGBOARD_OPERATOR_TOKEN secret, which the app adopts on restart.
260
+ operator = token_path.read_text().strip() if token_path.exists() else new_token()[1]
261
+ result = deploy(space_id, operator_token=operator, bucket_id=args.bucket, private=args.private,
262
+ title=args.title)
263
+ except (DeployError, HfHubHTTPError, ValueError) as exc:
264
+ print(f"error: {exc}", file=sys.stderr)
265
+ return 1
266
+ if not token_path.exists():
267
+ token_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
268
+ _write_secret_file(token_path, operator)
269
+ print(f"{'Created' if result.created else 'Updated'} the {'private' if result.private else 'public'} "
270
+ f"Space {result.space_id} at {result.url}")
271
+ print(f"Snapshots go to the private bucket {result.bucket_id}.")
272
+ print(f"Operator token in {token_path} (mode 0600). Keep it secret; open the dashboard with it to create invite links.")
273
+ if args.wait is None:
274
+ print("The Space is building; the board answers in a few minutes.")
275
+ return 0
276
+ print(f"Waiting up to {args.wait:g} s for the board to answer ...")
277
+ gate = {}
278
+ if result.private: # the Space's gate wants an HF token in Authorization; the board token moves aside
279
+ gate = {"headers": {"Authorization": f"Bearer {os.environ.get('MSGBOARD_HF_TOKEN') or get_token()}"},
280
+ "token_header": "X-Msgboard-Token"}
281
+ with Client(result.url, operator, **gate) as client:
282
+ try:
283
+ client.wait_ready(args.wait)
284
+ except TimeoutError as exc:
285
+ print(f"error: {exc}", file=sys.stderr)
286
+ return 1
287
+ print(f"Board ready at {result.url}")
288
+ return 0
289
+
290
+
291
  def main(argv: list[str] | None = None) -> int:
292
  parser = argparse.ArgumentParser(prog="python -m msgboard", description=__doc__)
293
  sub = parser.add_subparsers(dest="command", required=True)
 
326
  p.add_argument("--port", type=int, default=0, help="0 picks a free port")
327
  p.set_defaults(func=cmd_demo)
328
 
329
+ p = sub.add_parser("deploy-space", help="create or update a board on a Hugging Face Space (needs the hf extra)")
330
+ p.add_argument("space_id", help="namespace/name, or a bare name for the logged-in account")
331
+ p.add_argument("--bucket", default=None,
332
+ help="snapshot bucket; default: the one the Space uses, else <space_id>-bucket (or -2, -3 ...)")
333
+ visibility = p.add_mutually_exclusive_group()
334
+ visibility.add_argument("--private", dest="private", action="store_const", const=True,
335
+ help="make a new Space private (default: the namespace's default)")
336
+ visibility.add_argument("--public", dest="private", action="store_const", const=False,
337
+ help="make a new Space public; an existing Space keeps its visibility")
338
+ p.add_argument("--title", default=None, help="the Space card's title (default: the Space's name)")
339
+ p.add_argument("--token-file", default=None,
340
+ help="operator token file, created (0600) if missing; "
341
+ "default ~/.config/msgboard/spaces/<namespace>/<name>/operator.token")
342
+ p.add_argument("--wait", type=float, nargs="?", const=600.0, default=None, metavar="SECONDS",
343
+ help="wait for the board to answer (default 600 s)")
344
+ p.set_defaults(func=cmd_deploy_space, private=None)
345
+
346
  args = parser.parse_args(argv)
347
  return args.func(args)
{src/msgboard → msgboard}/client.py RENAMED
@@ -6,8 +6,6 @@ rotation. The client retries transient failures with jittered backoff and
6
  honours Retry-After.
7
  """
8
 
9
- from __future__ import annotations
10
-
11
  import os
12
  import random
13
  import time
@@ -29,6 +27,14 @@ class BoardError(Exception):
29
  self.message = message
30
 
31
 
 
 
 
 
 
 
 
 
32
  class Client:
33
  def __init__(self, base_url: str, token: str, *, timeout: float = 10.0,
34
  max_retries: int = 5, backoff: float = 0.25, transport: httpx.BaseTransport | None = None,
@@ -61,6 +67,48 @@ class Client:
61
  def close(self) -> None:
62
  self._http.close()
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  def __enter__(self):
65
  return self
66
 
@@ -138,6 +186,51 @@ class Client:
138
  """Agent listening state: admins see all, others see their own agents (and themselves if agents)."""
139
  return self._request("GET", "/presence").json()["principals"]
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  def update_identity(self, principal_id: int, **changes) -> dict:
142
  """display_name; for admins or an agent's owner also role, disabled, can_create_channels."""
143
  return self._request("PATCH", f"/principals/{principal_id}", json=changes).json()
 
6
  honours Retry-After.
7
  """
8
 
 
 
9
  import os
10
  import random
11
  import time
 
27
  self.message = message
28
 
29
 
30
+ def _json_field(resp: httpx.Response, key: str):
31
+ try:
32
+ body = resp.json()
33
+ except ValueError:
34
+ return None
35
+ return body.get(key) if isinstance(body, dict) else None
36
+
37
+
38
  class Client:
39
  def __init__(self, base_url: str, token: str, *, timeout: float = 10.0,
40
  max_retries: int = 5, backoff: float = 0.25, transport: httpx.BaseTransport | None = None,
 
67
  def close(self) -> None:
68
  self._http.close()
69
 
70
+ def wait_ready(self, timeout: float = 600.0, *, interval: float = 2.0) -> None:
71
+ """Wait until the board serves: /v1/health says "ok" and, if this client has a token, the board
72
+ accepts it (/v1/me). Returns None once it does; raises TimeoutError after `timeout` seconds,
73
+ naming the last answer.
74
+
75
+ Every other answer means "not yet": connection errors, a Space that is building or waking
76
+ from sleep, the Space app's 503 or "starting" while it restores, and a 401 from a container
77
+ that still has the previous MSGBOARD_OPERATOR_TOKEN (a reused Space switches over a while
78
+ after deploy() returns). For a private Space, build the client as `from_env` does with
79
+ MSGBOARD_HF_TOKEN, so requests get past the Space's gate.
80
+
81
+ Returning means the board answered once, not that it won't restart: after deploy() a restart or
82
+ rebuild can follow. With an unchanged token the old container passes both checks before its
83
+ pending restart, so keep retrying through 503 after this returns.
84
+ """
85
+ deadline = time.monotonic() + timeout
86
+ last = "no answer"
87
+ while True:
88
+ try:
89
+ resp = self._http.get("/v1/health")
90
+ status = _json_field(resp, "status")
91
+ if resp.status_code == 200 and status == "ok":
92
+ if not self.token:
93
+ return
94
+ me = self._http.get("/v1/me")
95
+ if me.status_code == 200:
96
+ return
97
+ last = f"/v1/me answered {me.status_code}"
98
+ else:
99
+ last = f"/v1/health answered {resp.status_code}"
100
+ if status:
101
+ last += f" {status!r}"
102
+ error = _json_field(resp, "error") # the Space app's reason for not starting
103
+ if isinstance(error, str):
104
+ last += f" ({error})"
105
+ except httpx.TransportError as exc:
106
+ last = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__
107
+ remaining = deadline - time.monotonic()
108
+ if remaining <= 0:
109
+ raise TimeoutError(f"{self.base_url} not ready after {timeout:g} s; last: {last}")
110
+ time.sleep(min(interval, remaining))
111
+
112
  def __enter__(self):
113
  return self
114
 
 
186
  """Agent listening state: admins see all, others see their own agents (and themselves if agents)."""
187
  return self._request("GET", "/presence").json()["principals"]
188
 
189
+ def tasks(self, *, archived: bool = False, sort: str = "manual", direction: str = "asc") -> dict:
190
+ """Your personal tasks (an agent sees its current human owner's tasks)."""
191
+ return self._request("GET", "/tasks", params={"archived": str(archived).lower(),
192
+ "sort": sort, "direction": direction}).json()
193
+
194
+ def task(self, item_id: int) -> dict:
195
+ return self._request("GET", f"/tasks/items/{item_id}").json()
196
+
197
+ def put_task(self, key: str, title: str, *, description: str = "", channel_id: int | None = None,
198
+ anchor_id: int | None = None, sources: list[int] = (), options: list[dict] = (),
199
+ multiple: bool = False, base_version: int | None = None, blocks: list[dict] = ()) -> dict:
200
+ """Agents add/update an item for their human. Reuse a stable key; updates need its version.
201
+
202
+ Options are {id, label}; a selected label is the exact string posted as the answer.
203
+ Blocks interleave {type: text, text} and {type: quote, message_id}; quotes
204
+ automatically register permission-checked source references.
205
+ An identical retry is harmless, and updating a closed item never reopens it.
206
+ """
207
+ payload = {"title": title, "description": description, "channel_id": channel_id,
208
+ "anchor_id": anchor_id, "sources": list(sources), "options": list(options),
209
+ "multiple": multiple}
210
+ if blocks:
211
+ payload["blocks"] = list(blocks)
212
+ if base_version is not None:
213
+ payload["base_version"] = base_version
214
+ return self._request("PUT", f"/tasks/items/by-key/{quote(key, safe='')}", json=payload).json()
215
+
216
+ def task_action(self, item_id: int, action: str, version: int, *, body: str = "",
217
+ option_ids: list[str] = (), request_id: str | None = None) -> dict:
218
+ """Answer, mark done, dismiss or restore. Only the human can answer.
219
+
220
+ Pass request_id to safely retry an action across process restarts.
221
+ """
222
+ payload = {"action": action, "version": version}
223
+ if action == "answer":
224
+ payload.update(body=body, option_ids=list(option_ids))
225
+ return self._request("POST", f"/tasks/items/{item_id}/actions", json=payload,
226
+ headers={"Idempotency-Key": request_id or uuid.uuid4().hex}).json()
227
+
228
+ def move_task(self, item_id: int, order_version: int, *, before_id: int | None = None,
229
+ after_id: int | None = None) -> dict:
230
+ """Move in Custom order. Supply one neighbor, or neither to append."""
231
+ return self._request("POST", f"/tasks/items/{item_id}/move", json={
232
+ "order_version": order_version, "before_id": before_id, "after_id": after_id}).json()
233
+
234
  def update_identity(self, principal_id: int, **changes) -> dict:
235
  """display_name; for admins or an agent's owner also role, disabled, can_create_channels."""
236
  return self._request("PATCH", f"/principals/{principal_id}", json=changes).json()
{src/msgboard → msgboard}/config.py RENAMED
File without changes
{src/msgboard → msgboard}/dashboard.html RENAMED
@@ -397,6 +397,8 @@ button.fchip:hover { border-color: var(--ink); }
397
  .v-title .mono { font-size: 11px; color: var(--ink-3); white-space: nowrap; }
398
  .v-head .close { background: none; border: 0; font: 20px/1 var(--mono); color: var(--ink-3); padding: 0 2px; }
399
  .v-head .close:hover { color: var(--ink); }
 
 
400
  .v-nav { display: flex; align-items: center; gap: 6px; font: 11px var(--mono); color: var(--ink-3); }
401
  .v-nav button { background: none; border: 1px solid var(--rule-2); padding: 1px 8px; font: 13px/1.3 var(--mono); }
402
  .v-nav button:disabled { opacity: .35; cursor: default; }
@@ -408,6 +410,7 @@ button.fchip:hover { border-color: var(--ink); }
408
  .v-body.center { align-items: center; justify-content: center; background: var(--panel);
409
  background-image: linear-gradient(45deg, var(--rule) 25%, transparent 25%, transparent 75%, var(--rule) 75%), linear-gradient(45deg, var(--rule) 25%, transparent 25%, transparent 75%, var(--rule) 75%);
410
  background-size: 16px 16px; background-position: 0 0, 8px 8px; }
 
411
  .v-body img { max-width: 100%; max-height: 100%; object-fit: contain; display: block; cursor: zoom-in; }
412
  .v-body.zoomed { align-items: flex-start; justify-content: flex-start; }
413
  .v-body.zoomed img { max-width: none; max-height: none; margin: auto; cursor: grab; }
@@ -803,6 +806,95 @@ dialog input[type=text] { width: 100%; margin: 4px 0 12px; }
803
  }
804
  /* iOS zooms into any focused field under 16px */
805
  @media (pointer: coarse) { input, textarea, select { font-size: 16px !important; } }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
806
  </style>
807
  <style id="avatar-styles"></style>
808
  </head>
@@ -815,6 +907,7 @@ dialog input[type=text] { width: 100%; margin: 4px 0 12px; }
815
  <div class="brand"><b>msgboard</b><button class="hidden" id="analytics-open" title="Analytics" aria-label="Analytics"><svg class="gear" viewBox="0 0 16 16" aria-hidden="true"><path d="M2 14h12M4.5 11.5V8M8 11.5V3.5M11.5 11.5V6"/></svg></button><button class="hidden" id="settings-open" title="Settings" aria-label="Settings"><svg class="gear" viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="8" r="2.2"/><path d="M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2M3.4 3.4l1.4 1.4M11.2 11.2l1.4 1.4M3.4 12.6l1.4-1.4M11.2 4.8l1.4-1.4"/><circle cx="8" cy="8" r="4.6"/></svg></button></div>
816
  <div class="search-box"><input id="search-input" type="search" placeholder="Search" title="Ctrl/⌘ K opens the full search" aria-label="Search" autocomplete="off" spellcheck="false"></div>
817
  <div class="nav-scroll">
 
818
  <ul class="navlist" id="activity-list"><li><button id="activity-open"><span class="glyph"><svg class="lock" viewBox="0 0 10 11" aria-hidden="true"><path d="M2 8 V5 a3 3 0 0 1 6 0 V8 H2 Z M4 9.5 h2"/></svg></span><span class="name">Activity</span></button></li></ul>
819
  <div class="side-head"><span class="label">Channels</span><button id="new-channel" class="hidden" title="New channel">+</button></div>
820
  <ul class="navlist" id="channels"></ul>
@@ -855,6 +948,20 @@ dialog input[type=text] { width: 100%; margin: 4px 0 12px; }
855
  <div id="activity" class="scroll hidden" style="padding:0"></div>
856
  <div id="search" class="scroll hidden"></div>
857
  <div id="analytics" class="scroll hidden"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
858
  </main>
859
  <section id="panel" class="hidden">
860
  <div class="resizer" id="panel-resize" role="separator" aria-orientation="vertical" aria-label="Resize side panel" tabindex="0" title="Drag to resize · double-click to reset"></div>
@@ -873,13 +980,24 @@ dialog input[type=text] { width: 100%; margin: 4px 0 12px; }
873
  <div class="v-zoom hidden" id="v-zoom" role="group" aria-label="Zoom"><button id="v-zoom-out" title="Zoom out (−)" aria-label="Zoom out"><svg class="v-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 6h7"/></svg></button><span id="v-zoom-level">fit</span><button id="v-zoom-in" title="Zoom in (+)" aria-label="Zoom in"><svg class="v-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 6h7M6 2.5v7"/></svg></button><button id="v-zoom-fit" title="Fit to window (0)">fit</button></div>
874
  <button class="btn ghost small hidden" id="v-open" title="Open in the browser's own viewer">Open in new tab</button>
875
  <button class="btn ghost small" id="v-link" title="Copy a link to this file">Copy link</button>
876
- <button class="btn small" id="v-download">Download</button>
877
  <button class="close" id="v-close" aria-label="Close">×</button>
878
  </div>
 
879
  <div class="v-body" id="v-body"></div>
880
  </div>
881
  </div>
882
 
 
 
 
 
 
 
 
 
 
 
883
  <dialog id="channel-dialog">
884
  <form method="dialog" id="channel-form">
885
  <h3>New channel</h3>
@@ -1073,12 +1191,14 @@ function decorate(html, mentions) {
1073
  t.innerHTML = html;
1074
  t.content.querySelectorAll("a[href]").forEach((a) => {
1075
  const fid = !internalHash(a.getAttribute("href")) && boardFileId(a.getAttribute("href"));
1076
- if (fid) { a.dataset.boardFile = fid; a.removeAttribute("target"); if (a.textContent.trim() === a.getAttribute("href")) a.textContent = "📎 " + fid.split("/").pop(); return; }
 
 
1077
  const h = internalHash(a.getAttribute("href"));
1078
  if (h) { // a link to a message, file or channel on this board: open it here, with a readable label
1079
  a.dataset.internal = h; a.removeAttribute("target");
1080
  if (a.textContent.trim() === a.getAttribute("href") || a.textContent.trim() === a.href) {
1081
- a.textContent = h.startsWith("msg/") ? "↪ message" : h.startsWith("file/") ? "📎 file" : /^(settings|activity|search|analytics)$/.test(h) ? h : "#" + h;
1082
  }
1083
  } else { a.target = "_blank"; a.rel = "noopener noreferrer"; }
1084
  });
@@ -1434,6 +1554,15 @@ async function loadPeople(force = false) {
1434
  if (!state.people || force) state.people = (await api("GET", "/principals")).principals;
1435
  return state.people;
1436
  }
 
 
 
 
 
 
 
 
 
1437
  // ids of a channel's members, for @ suggestions; dropped when someone joins, leaves or is added
1438
  const memberIds = new Map(), knownMembers = new Map();
1439
  async function loadMemberIds(c) {
@@ -1516,7 +1645,15 @@ async function showJoin(code) {
1516
  <code class="box prompt-box">${esc(agentPrompt(code, info.agent_name ? { handle: info.agent_name, display: info.agent_display } : null))}</code>`);
1517
  return;
1518
  }
 
 
 
 
1519
  showLoginBox(`<p>${esc(info.invited_by)} invited you to join as <b>${esc(info.role)}</b>${info.role === "viewer" ? " (read-only)" : ""}.</p>
 
 
 
 
1520
  <form id="join-form">
1521
  <label class="label field" for="join-name">Username</label>
1522
  <input id="join-name" type="text" required pattern="[A-Za-z0-9][A-Za-z0-9_.\\-]{0,63}" placeholder="ana" autocomplete="username">
@@ -1524,12 +1661,13 @@ async function showJoin(code) {
1524
  <input id="join-display" type="text" maxlength="128" placeholder="Ana Ruiz (optional)">
1525
  <div class="row" style="margin-top:4px"><span class="err hidden" id="join-error"></span><span></span><button class="btn" type="submit">Join the board</button></div>
1526
  </form>`);
1527
- $("join-name").focus();
1528
  $("join-form").onsubmit = async (e) => {
1529
  e.preventDefault();
 
1530
  try {
1531
- finishJoin(await api("POST", "/join", { auth: false, body: { code, name: $("join-name").value.trim(),
1532
- display_name: $("join-display").value.trim() || null } }));
1533
  } catch (err) { $("join-error").textContent = err.message; $("join-error").classList.remove("hidden"); }
1534
  };
1535
  }
@@ -1560,6 +1698,7 @@ async function boot() {
1560
  $("login").classList.add("hidden");
1561
  $("app").classList.remove("hidden");
1562
  renderMe();
 
1563
  $("new-channel").classList.toggle("hidden", !can("create_channels"));
1564
  $("new-dm").classList.toggle("hidden", !can("post"));
1565
  $("settings-open").classList.toggle("hidden", !(can("invite_agents") || can("manage")));
@@ -1571,6 +1710,7 @@ async function boot() {
1571
  initNotify();
1572
  if (location.hash === "#settings") return openSettings();
1573
  if (location.hash === "#activity") return openActivity();
 
1574
  if (location.hash === "#analytics" && canAnalytics()) return openAnalytics();
1575
  if (/^#(msg|file)\//.test(location.hash)) { // a shared link: open a channel first, then the message or file
1576
  const first = state.channels.find((c) => c.name === store.get("channel")) || state.channels.find((c) => c.kind !== "dm") || state.channels[0];
@@ -1761,6 +1901,7 @@ function renderChannels() {
1761
  document.title = (total ? `(${total > 99 ? "99+" : total}) ` : "") + baseTitle;
1762
  noteFront(); // the channel on screen may have changed
1763
  $("settings-open").classList.toggle("on", state.view === "settings");
 
1764
  $("activity-open").className = (state.view === "activity" ? "active " : "") + (total ? "unread" : "");
1765
  $("activity-open").innerHTML = $("activity-open").innerHTML.replace(/<span class="count">.*?<\/span>/, "") + (total ? `<span class="count">${total > 99 ? "99+" : total}</span>` : "");
1766
  $("channels").innerHTML = ""; $("dms").innerHTML = "";
@@ -1804,6 +1945,7 @@ function updateMeta(live) {
1804
  $("ch-join").onclick = () => joinChannel(c);
1805
  }
1806
  function showChat() {
 
1807
  state.view = "chat";
1808
  $("settings").classList.add("hidden"); $("activity").classList.add("hidden"); $("search").classList.add("hidden"); leaveAnalytics(); $("chat-view").style.display = "contents";
1809
  }
@@ -2184,8 +2326,7 @@ function lastOwnMessage(list) {
2184
  }
2185
 
2186
  // ------------------------------------------------------------------ rendering messages
2187
- function canWriteHere() {
2188
- const c = state.current;
2189
  if (!c || !can("post") || c.archived) return false;
2190
  if (c.kind === "dm") return !!dmPeer(c);
2191
  return true; // the server has the final say (guests, private channels)
@@ -2309,6 +2450,7 @@ function newBelow(n) {
2309
  }
2310
  // ---------- attachments: kinds, chips, thumbnails, download
2311
  const IMAGE_EXT = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", bmp: "image/bmp", avif: "image/avif", ico: "image/x-icon" };
 
2312
  const TEXT_EXT = new Set(["txt", "md", "markdown", "log", "csv", "tsv", "json", "jsonl", "ndjson", "yaml", "yml", "toml", "ini", "cfg", "conf", "env",
2313
  "py", "js", "mjs", "cjs", "ts", "tsx", "jsx", "sh", "bash", "zsh", "rb", "go", "rs", "java", "kt", "c", "h", "cc", "cpp", "hpp", "cs", "swift",
2314
  "php", "pl", "r", "jl", "lua", "sql", "css", "scss", "xml", "tex", "bib", "diff", "patch", "ipynb", "dockerfile", "makefile", "gitignore"]);
@@ -2316,6 +2458,7 @@ const extOf = (name) => { const n = (name || "").toLowerCase(); const i = n.last
2316
  function kindOf(name, type) {
2317
  const ext = extOf(name), t = (type || "").toLowerCase();
2318
  if (IMAGE_EXT[ext] || t.startsWith("image/")) return "image";
 
2319
  if (ext === "pdf" || t === "application/pdf") return "pdf";
2320
  if (ext === "html" || ext === "htm" || t === "text/html") return "html";
2321
  if (TEXT_EXT.has(ext) || t.startsWith("text/") || t === "application/json") return "text";
@@ -2361,11 +2504,33 @@ function typed(blob, info) {
2361
  const type = kind === "image" ? (IMAGE_EXT[ext] || info.content_type) : kind === "pdf" ? "application/pdf" : kind === "html" ? "text/html" : "text/plain";
2362
  return blob.slice(0, blob.size, type);
2363
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2364
  async function download(id) {
2365
- const info = await getInfo(id, true), blob = await getBlob(id, info);
2366
- const a = document.createElement("a"); a.href = URL.createObjectURL(blob);
2367
- a.download = (info && info.filename) || id; a.click();
2368
- setTimeout(() => URL.revokeObjectURL(a.href), 5000);
 
 
 
 
 
 
 
 
2369
  }
2370
 
2371
  // ---------- the preview overlay
@@ -2389,14 +2554,16 @@ async function showInViewer(view = "render") {
2389
  $("v-download").onclick = () => download(id).catch(() => {});
2390
  $("v-link").onclick = () => copyText(boardURL("file/" + id), $("v-link"));
2391
  const info = await getInfo(id, true);
 
2392
  if (viewer.list[viewer.index] !== id) return;
2393
  if (!info) { body.innerHTML = `<div class="v-empty">This file is not available.</div>`; return; }
2394
  const kind = kindOf(info.filename, info.content_type);
2395
  $("v-name").textContent = info.filename || id;
2396
  $("v-meta").textContent = `${fmtSize(info.size)} · ${typeLabel(info.filename, kind)}`;
2397
  const noPreview = (why) => { body.innerHTML = `<div class="v-empty"><div class="fprev">${esc(typeLabel(info.filename, kind))}</div>${why}<br><br>` +
2398
- `<button class="btn" onclick="document.getElementById('v-download').click()">Download</button></div>`; };
2399
  if (kind === "other") return noPreview("No preview for this kind of file.");
 
2400
  const limit = kind === "text" || kind === "html" ? 2 * 1024 * 1024 : 60 * 1024 * 1024;
2401
  if (info.size > limit) return noPreview(`Too large to preview (${fmtSize(info.size)}).`);
2402
  let blob;
@@ -2431,6 +2598,49 @@ async function showInViewer(view = "render") {
2431
  body.innerHTML = `<pre class="v-code">${lines.slice(0, 20000).map((l) => `<span class="l">${esc(l) || " "}</span>`).join("")}</pre>` +
2432
  (cut ? `<div class="v-empty">Showing the first 20,000 of ${lines.length.toLocaleString()} lines.</div>` : "");
2433
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2434
  // PDFs are drawn with PDF.js, because browsers refuse their own PDF viewer inside sandboxed
2435
  // frames (the huggingface.co Space page embeds the board in one). Loaded on first use.
2436
  const PDFJS = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174";
@@ -2567,7 +2777,8 @@ document.addEventListener("keydown", (e) => {
2567
  if (link && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); link.click(); }
2568
  });
2569
  document.addEventListener("click", (e) => {
2570
- if (e.target.closest("dialog")) return;
 
2571
  const del = e.target.closest("[data-delete-msg]");
2572
  if (del) { deleteMessage(Number(del.dataset.deleteMsg)); return; }
2573
  const ct = e.target.closest("[data-copy-text]");
@@ -2639,11 +2850,16 @@ function fileLink(it) {
2639
  const name = it.label.replace(/[[\]\\]/g, "\\$&");
2640
  return kindOf(it.file.name, it.file.type) === "image" ? `![${name}](${it.url})` : `[📎 ${name}](${it.url})`;
2641
  }
2642
- function mountComposer(host, { placeholder, replyTo }) {
 
 
 
 
 
2643
  host.classList.remove("hidden");
2644
  host.addFiles = null; // set again below only if this box can post
2645
- if (!canWriteHere()) {
2646
- const c = state.current;
2647
  host.innerHTML = `<div class="readonly">${c && c.archived ? "This channel is archived. History is read-only."
2648
  : !can("post") ? "You have read-only access to this board." : "You can read this conversation but not write in it."}</div>`;
2649
  return;
@@ -2655,17 +2871,19 @@ function mountComposer(host, { placeholder, replyTo }) {
2655
  <input type="file" multiple class="hidden">`;
2656
  const box = host.querySelector(".cbox"), chips = host.querySelector(".files"), input = host.querySelector("textarea");
2657
  const fileInput = host.querySelector("input[type=file]"), pending = host.querySelector(".pending"), sendBtn = host.querySelector(".btn");
2658
- const channel = state.current;
2659
- const draftKey = replyTo() ? "t:" + replyTo() : "c:" + channel.id;
 
 
2660
  input.value = draftOf(draftKey);
2661
- input.addEventListener("input", () => setDraft(draftKey, input.value));
2662
  let items = [], sending = false;
2663
  // uploaded files stay with the draft, so leaving and coming back keeps them (and their marks) working
2664
  const filesKey = "draft-files:" + draftKey;
2665
  try { items = JSON.parse(store.get(filesKey) || "[]").map((f) => ({ file: { name: f.name, type: f.type, size: f.size }, label: f.label, url: f.url, uid: uid(), loaded: f.size, status: "done", thumb: null })); } catch {}
2666
  const saveFiles = () => {
2667
  if (sending) return; // in flight: the draft gives them up, so a box opened meanwhile cannot remove them
2668
- if (!input.isConnected) return; // this box was replaced: the draft now belongs to the new one
2669
  const done = items.filter((it) => it.status === "done").map((it) => ({ name: it.file.name, type: it.file.type, size: it.file.size, label: it.label, url: it.url }));
2670
  if (done.length) store.set(filesKey, JSON.stringify(done)); else store.del(filesKey);
2671
  };
@@ -2790,11 +3008,11 @@ function mountComposer(host, { placeholder, replyTo }) {
2790
  });
2791
  host.addFiles = (files) => { addFiles(files); input.focus(); }; // drops anywhere over the channel or thread land here
2792
  input.addEventListener("input", autosize);
2793
- const assist = attachAssist(host, input, autosize);
2794
  input.addEventListener("keydown", (e) => {
2795
  if (e.key === "Enter" && mobileTextInput()) return;
2796
  if (assist.handleKey(e)) return; // mention suggestions take Enter, Tab and arrows while open
2797
- if (e.key === "ArrowUp" && !input.value && !e.shiftKey) { // like Slack: up in an empty box edits your last message
2798
  const parent = replyTo(), list = parent ? [state.panel.root, ...state.thread] : state.roots, m = lastOwnMessage(list);
2799
  if (m && state.me.identity_type === "user") { e.preventDefault(); input.blur(); startEdit(m.id, parent ? "thread" : "feed"); }
2800
  return;
@@ -2803,7 +3021,7 @@ function mountComposer(host, { placeholder, replyTo }) {
2803
  });
2804
  sendBtn.onclick = send;
2805
  async function send() {
2806
- const c = state.current, ready = items.filter((it) => it.status === "done");
2807
  let text = input.value;
2808
  const rest = [];
2809
  for (const it of ready) {
@@ -2811,19 +3029,22 @@ function mountComposer(host, { placeholder, replyTo }) {
2811
  else rest.push(fileLink(it)); // not placed: at the end, like attachments
2812
  }
2813
  text = [text.trim(), ...rest].filter(Boolean).join("\n");
2814
- if (sending || !c || uploading() || (!text && !ready.length)) return;
 
2815
  if (items.some((it) => it.status === "error")) { pending.textContent = "Remove or retry the files that did not upload."; return; }
2816
  sending = true; renderChips();
2817
  store.del(filesKey); setDraft(draftKey, ""); // taken out of the draft while sending; put back if it fails
2818
  const key = uid(); // reused on every retry, so a resend never duplicates
2819
  try {
2820
- const payload = { body: text };
2821
  const parent = replyTo();
2822
  if (parent) payload.reply_to = parent;
 
2823
  for (let attempt = 0; ; attempt++) {
2824
  try {
2825
- const m = await api("POST", `/channels/${c.id}/messages`, { body: payload, headers: { "Idempotency-Key": key } });
2826
- if (state.current === c && ingest(m)) renderFeed(!parent);
 
2827
  break;
2828
  } catch (e) {
2829
  if (attempt >= 6 || (e.status && e.status < 500 && e.status !== 429)) throw e;
@@ -2831,24 +3052,484 @@ function mountComposer(host, { placeholder, replyTo }) {
2831
  }
2832
  }
2833
  input.value = ""; autosize(); pending.textContent = "";
2834
- if (input.isConnected) { setDraft(draftKey, ""); store.del(filesKey); } // a newer box may own the draft by now
2835
  items.forEach((it) => it.thumb && URL.revokeObjectURL(it.thumb)); items = [];
 
2836
  } catch (e) {
2837
  pending.textContent = "Not sent: " + e.message;
 
2838
  // put the message back in its draft; if the box was replaced, only when the new one has not started another
2839
- if (input.isConnected || (!draftOf(draftKey) && !store.get(filesKey))) {
2840
  setDraft(draftKey, input.value);
2841
- if (!input.isConnected) store.set(filesKey, JSON.stringify(items.filter((it) => it.status === "done")
2842
  .map((it) => ({ name: it.file.name, type: it.file.type, size: it.file.size, label: it.label, url: it.url }))));
2843
  }
2844
  }
2845
- finally { sending = false; renderChips(); input.focus(); }
2846
  }
2847
  if (items.length) renderChips(); // files kept with the draft
2848
  if (input.value) { autosize(); input.setSelectionRange(input.value.length, input.value.length); }
2849
- if (window.matchMedia("(min-width: 721px)").matches) input.focus();
2850
  }
2851
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2852
  // ------------------------------------------------------------------ emoji and @mentions in the composer
2853
  const EMOJI = [
2854
  ["Smileys", "😀 grin smile|😄 happy|😁 beam|😂 joy laugh tears|🤣 rofl|😊 blush|🙂 slight smile|😉 wink|😍 love heart eyes|🥰 adore|😘 kiss|😎 cool sunglasses|🤓 nerd|🧐 monocle curious|🤔 thinking hmm|🤨 skeptical|😐 neutral|😑 expressionless|🙄 eye roll|😏 smirk|😬 grimace awkward|😮 wow open mouth|😯 hushed|😲 astonished|😳 flushed|🥺 pleading|😢 cry sad|😭 sob|😤 huff|😠 angry|😡 rage|🤯 mind blown|😱 scream|🥳 party celebrate|😴 sleep|🤤 drool|😷 mask sick|🤒 ill|🤗 hug|🤫 shush quiet|🤐 zipper|🙃 upside down|😅 sweat smile|😆 laughing|🫠 melting|🫡 salute|🤝 handshake deal"],
@@ -2859,7 +3540,7 @@ const EMOJI = [
2859
  ["Food", "☕ coffee|🍵 tea|🍕 pizza|🍔 burger|🌮 taco|🍣 sushi|�� cookie|🍰 cake|🍎 apple|🍌 banana|🥑 avocado|🍿 popcorn|🍺 beer|🥂 cheers toast|🧁 cupcake"],
2860
  ].map(([cat, list]) => [cat, list.split("|").map((x) => { const i = x.indexOf(" "); return [x.slice(0, i), x.slice(i + 1)]; })]);
2861
 
2862
- function attachAssist(host, input, autosize) {
2863
  const insertAt = (text, from, to) => {
2864
  const start = from ?? input.selectionStart, end = to ?? input.selectionEnd;
2865
  input.setRangeText(text, start, end, "end");
@@ -2898,7 +3579,7 @@ function attachAssist(host, input, autosize) {
2898
  const search = picker.querySelector("input");
2899
  search.oninput = () => renderGrid(search.value);
2900
  search.onkeydown = (e) => {
2901
- if (e.key === "Escape") { closePicker(); input.focus(); }
2902
  if (e.key === "Enter") { e.preventDefault(); const first = picker.querySelector("[data-e]"); if (first) choose(first.dataset.e); }
2903
  };
2904
  picker.querySelector(".emoji-grid").onclick = (e) => { const b = e.target.closest("[data-e]"); if (b) choose(b.dataset.e); };
@@ -2927,9 +3608,9 @@ function attachAssist(host, input, autosize) {
2927
  .map(([, c]) => ({ insert: `#${c.name} `, html: `<span class="glyph">${c.kind === "private" ? LOCK : "#"}</span><span>${esc(c.name)}</span>` +
2928
  (c.description ? `<small>${esc(c.description.length > 40 ? c.description.slice(0, 39) + "…" : c.description)}</small>` : "") }));
2929
  } else {
2930
- const members = state.current ? await loadMemberIds(state.current) : new Set(); // only people in this channel
2931
- const people = (await loadPeople()).filter((p) => !p.disabled && p.id !== state.me.id && members.has(p.id));
2932
- const tags = state.current && state.current.kind !== "dm"
2933
  ? ["all", "agents", "humans"].filter((g) => !q || g.startsWith(q)).map((g) => ({ insert: `@${g} `,
2934
  html: `<span class="glyph">@</span><span>${g}</span><small>${esc(GROUP_TAGS[g])}</small>` })) : [];
2935
  options = tags.concat(people.map((p) => [rank(q, handleOf(p), nameOf(p)) + (p.identity_type === "user" ? 0.5 : 0), p]).filter(([s]) => s > 0)
@@ -3013,11 +3694,13 @@ const boardURL = (hash) => `${location.origin}${location.pathname}#${hash}`;
3013
  function internalHash(href) {
3014
  let u; try { u = new URL(href, location.href); } catch { return null; }
3015
  if (u.origin !== location.origin || u.pathname !== location.pathname || !u.hash) return null;
3016
- const h = decodeURIComponent(u.hash.slice(1));
3017
- return /^(msg|file)\/[\w-]+$/.test(h) || /^(settings|activity|search|analytics)$/.test(h) || state.chanIndex.has(h.toLowerCase()) ? h : null;
3018
  }
3019
  async function routeHash(h) {
3020
  h = decodeURIComponent((h || "").replace(/^#/, ""));
 
 
3021
  let m;
3022
  if ((m = /^msg\/(\d+)$/.exec(h))) {
3023
  try { jumpTo(await api("GET", `/messages/${m[1]}`)); }
@@ -3027,6 +3710,7 @@ async function routeHash(h) {
3027
  if ((m = /^file\/([\w-]+)$/.exec(h))) { openViewer([m[1]], 0); return true; }
3028
  if (h === "settings") { openSettings(); return true; }
3029
  if (h === "activity") { openActivity(); return true; }
 
3030
  if (h === "analytics") { openAnalytics(); return true; }
3031
  if (h === "search") { openSearch(""); return true; }
3032
  const c = state.chanIndex.get(h.toLowerCase()) || state.channels.find((x) => x.name === h);
@@ -3565,6 +4249,7 @@ function drawActivity(host, days) {
3565
 
3566
  // ------------------------------------------------------------------ activity
3567
  async function openActivity() {
 
3568
  state.view = "activity";
3569
  if (state.poll) state.poll.abort();
3570
  state.current = null; closePanel(); renderChannels();
@@ -3751,6 +4436,7 @@ document.addEventListener("keydown", (e) => {
3751
 
3752
  // full search: a view in the main area, with filters
3753
  async function openSearch(q, opts = {}) {
 
3754
  state.view = "search";
3755
  if (state.poll) state.poll.abort();
3756
  state.current = null; closePanel(); renderChannels();
@@ -3845,6 +4531,7 @@ async function jumpTo(m) {
3845
  // ------------------------------------------------------------------ settings
3846
  const EXPIRY = [["never", null], ["1 day", 86400], ["7 days", 604800], ["30 days", 2592000]];
3847
  function openSettings(tab) {
 
3848
  state.view = "settings";
3849
  if (state.poll) state.poll.abort();
3850
  state.current = null; renderChannels(); closePanel();
@@ -4101,6 +4788,11 @@ async function settingsSuspended() {
4101
  bindSuspend(settingsSuspended, (e) => { $("susp-err").innerHTML = `<p><span class="err">${esc(e.message)}</span></p>`; });
4102
  }
4103
 
 
 
 
 
 
4104
  async function settingsAgents() {
4105
  const all = await loadPeople(true);
4106
  const agents = all.filter((p) => p.identity_type !== "user" && (can("manage") || (p.owner && p.owner.id === state.me.id)));
@@ -4114,7 +4806,7 @@ async function settingsAgents() {
4114
  <td><select data-arole="${a.id}">${(can("manage") ? ["admin", "reader", "member", "guest"] : ["member", "guest"]).map((r) => `<option value="${r}" ${a.role === r ? "selected" : ""}>${r}</option>`).join("")}</select></td>
4115
  <td>${a.role === "admin" ? '<span class="small">can create (admins always can)</span>' : a.role === "reader" ? '<span class="small">reads all, no posting</span>'
4116
  : `<label class="small"><input type="checkbox" data-create="${a.id}" ${a.can_create_channels ? "checked" : ""} ${a.role === "guest" ? "disabled" : ""}> can create</label>`}</td>
4117
- <td>${a.suspended ? '<span class="status-other">suspended</span>' : a.disabled ? '<span class="status-other">removed</span>' : "active"}</td>
4118
  <td>${a.suspended ? "" : `<button class="linkish" data-atoggle="${a.id}" data-disabled="${a.disabled}">${a.disabled ? "restore" : "remove"}</button>`}
4119
  ${!can("manage") || (!a.suspended && a.disabled) ? ""
4120
  : a.suspended && a.owner && all.some((o) => o.id === a.owner.id && o.suspended) ? '<span class="small">with its owner</span>' : suspendButton(a)}
@@ -4224,6 +4916,7 @@ function analyticsRange() {
4224
  function leaveAnalytics() { $("analytics").classList.add("hidden"); $("analytics-open").classList.remove("on"); }
4225
  async function openAnalytics() {
4226
  if (!canAnalytics()) return;
 
4227
  state.view = "analytics";
4228
  if (state.poll) state.poll.abort();
4229
  state.current = null; closePanel(); renderChannels();
 
397
  .v-title .mono { font-size: 11px; color: var(--ink-3); white-space: nowrap; }
398
  .v-head .close { background: none; border: 0; font: 20px/1 var(--mono); color: var(--ink-3); padding: 0 2px; }
399
  .v-head .close:hover { color: var(--ink); }
400
+ .download-status { flex: none; min-width: 0; padding: 7px 14px; border-bottom: 1px solid var(--rule); font-size: 12px; overflow-wrap: anywhere; }
401
+ #viewer.img-mode .download-status { color: #eee; background: rgba(0,0,0,.55); border: 0; }
402
  .v-nav { display: flex; align-items: center; gap: 6px; font: 11px var(--mono); color: var(--ink-3); }
403
  .v-nav button { background: none; border: 1px solid var(--rule-2); padding: 1px 8px; font: 13px/1.3 var(--mono); }
404
  .v-nav button:disabled { opacity: .35; cursor: default; }
 
410
  .v-body.center { align-items: center; justify-content: center; background: var(--panel);
411
  background-image: linear-gradient(45deg, var(--rule) 25%, transparent 25%, transparent 75%, var(--rule) 75%), linear-gradient(45deg, var(--rule) 25%, transparent 25%, transparent 75%, var(--rule) 75%);
412
  background-size: 16px 16px; background-position: 0 0, 8px 8px; }
413
+ .v-body video { max-width: 100%; max-height: 100%; display: block; background: #000; }
414
  .v-body img { max-width: 100%; max-height: 100%; object-fit: contain; display: block; cursor: zoom-in; }
415
  .v-body.zoomed { align-items: flex-start; justify-content: flex-start; }
416
  .v-body.zoomed img { max-width: none; max-height: none; margin: auto; cursor: grab; }
 
806
  }
807
  /* iOS zooms into any focused field under 16px */
808
  @media (pointer: coarse) { input, textarea, select { font-size: 16px !important; } }
809
+ /* ---------- personal tasks ---------- */
810
+ .search-box, [data-look="a2"] .search-box { padding-bottom: 4px; }
811
+ #tasks-nav, #activity-list { padding-left: 16px; padding-right: 16px; margin-top: 0; }
812
+ #tasks-nav .glyph svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.2; }
813
+ #tasks { flex: 1; min-height: 0; display: flex; flex-direction: column; }
814
+ #tasks-scroll { min-height: 0; padding: 0; }
815
+ .tasks-page { max-width: 1000px; margin: 0 auto; padding: 24px 28px 32px; }
816
+ #tasks-sort { display: flex; justify-content: flex-end; gap: 6px; padding-bottom: 12px; border-bottom: 1px solid var(--rule); }
817
+ #tasks-sort button { border: 1px solid var(--rule-2); padding: 5px 10px; font-size: 11px; min-height: 28px; background: transparent; }
818
+ #tasks-sort button.on { color: var(--select-ink, var(--bg)); background: var(--select, var(--ink)); border-color: var(--select, var(--ink)); }
819
+ .tasks-row { display: flex; gap: 12px; align-items: center; padding: 9px 0; border-bottom: 1px solid var(--rule); }
820
+ .tasks-row.drag-before { box-shadow: inset 0 2px var(--ink); }
821
+ .tasks-row.drag-after { box-shadow: inset 0 -2px var(--ink); }
822
+ .tasks-row[draggable=true] { cursor: grab; }
823
+ .tasks-row.touch-dragging { background: var(--hover); outline: 1px solid var(--rule-2); cursor: grabbing; }
824
+ .tasks-row[draggable=true] .tasks-row-open { -webkit-touch-callout: none; }
825
+ .tasks-row-open { flex: 1; min-width: 0; padding: 0; border: 0; background: transparent; text-align: left; }
826
+ .tasks-row-title { display: block; font-size: 15px; line-height: 1.45; font-weight: 500; letter-spacing: -.12px; }
827
+ .tasks-row-open:hover .tasks-row-title { text-decoration: underline; text-underline-offset: 3px; }
828
+ .tasks-row-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 5px; color: var(--ink-3); font-size: 11px; }
829
+ .tasks-row.closed .tasks-row-title { color: var(--ink-3); }
830
+ .tasks-row-mark { display: inline-flex; width: 14px; height: 14px; margin-right: 6px; vertical-align: -2px; }
831
+ .tasks-row-mark svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.3; }
832
+ .tasks-actions { display: flex; gap: 6px; flex-shrink: 0; }
833
+ .tasks-icon { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; background: transparent; border: 1px solid var(--rule-2); color: var(--ink-2); }
834
+ .tasks-icon:hover { color: var(--ink); border-color: var(--ink); }
835
+ .tasks-icon svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.3; }
836
+ .tasks-summary { display: flex; justify-content: flex-end; align-items: center; flex-wrap: wrap; gap: 10px; margin-top: 14px; font-size: 11px; color: var(--ink-3); }
837
+ .tasks-summary label { display: flex; align-items: center; gap: 7px; }
838
+ .tasks-summary input { margin: 0; }
839
+ #tasks-error { margin: 12px 0; }
840
+ #tasks-dm { flex: none; width: 100%; max-width: 1000px; margin: 0 auto; padding: 0 28px; background: var(--bg); }
841
+ #tasks-dm-content { position: relative; border-top: 1px solid var(--rule-2); display: flex; flex-direction: column; }
842
+ #tasks-dm-resize { position: absolute; top: -6px; left: 0; right: 0; height: 12px; cursor: ns-resize; touch-action: none; outline: none; z-index: 2; }
843
+ #tasks-dm-resize:focus-visible::after { content: ""; position: absolute; top: 5px; left: 0; right: 0; border-top: 1px solid var(--ink); }
844
+ #tasks-dm-content.resized #tasks-dm-messages { flex: 1; min-height: 0; max-height: none; }
845
+ #tasks-dm-content.resized #tasks-dm-composer .cbox { overflow-y: auto; }
846
+ .tasks-dm-head, #tasks-dm-composer { flex: none; }
847
+ .tasks-dm-head { display: flex; gap: 10px; align-items: center; padding: 12px 0 0; font-size: 12px; }
848
+ .tasks-dm-head select { min-width: 138px; max-width: 70%; font-size: 12px; padding: 5px 24px 5px 9px; }
849
+ #tasks-dm-hide { margin-left: auto; font-size: 11px; }
850
+ #tasks-dm-messages { max-height: 125px; overflow-y: auto; padding: 6px 0; }
851
+ #tasks-dm-messages .msg { font-size: 13px; padding-left: 0; padding-right: 0; }
852
+ #tasks-dm-messages .msg .body { font-size: inherit; }
853
+ #tasks-dm-composer { border-top: 0; padding: 10px 0 16px; }
854
+ #tasks-dm.collapsed { border: 0; }
855
+ #tasks-dm.collapsed #tasks-dm-content { display: none; }
856
+ #tasks-agent-tab { display: flex; gap: 10px; align-items: center; padding: 9px 13px; border: 1px solid var(--rule-2); border-bottom: 0; background: var(--bg); font-size: 12px; margin-left: auto; }
857
+ #tasks-dialog { width: min(730px, calc(100% - 32px)); max-height: calc(var(--vvh, 100dvh) - 32px); padding: 26px 28px 18px; overflow-y: auto; }
858
+ #tasks-item-close { position: absolute; top: 10px; right: 12px; font-size: 22px; background: transparent; border: 0; padding: 0 5px; color: var(--ink-2); z-index: 1; }
859
+ #tasks-dialog .tasks-proposal { padding: 0; }
860
+ #tasks-dialog .tasks-proposal:hover { background: transparent; }
861
+ #tasks-item-title { font-size: 16px; line-height: 1.45; font-weight: 550; margin: 13px 0 9px; letter-spacing: -.15px; }
862
+ #tasks-dialog .tasks-description { font-size: 14px; line-height: 1.65; margin: 0 0 17px; color: var(--ink); }
863
+ .tasks-description > :first-child { margin-top: 0; }
864
+ .tasks-description > :last-child { margin-bottom: 0; }
865
+ .tasks-source { border: 1px solid var(--rule); margin: 12px 0; }
866
+ .tasks-source[role=link] { cursor: pointer; }
867
+ .tasks-source[role=link]:hover { background: var(--hover); }
868
+ .tasks-source:focus-visible { outline: 1px solid var(--ink); outline-offset: 2px; }
869
+ .tasks-source .msg, .tasks-source .msg.first { padding: 10px 12px; }
870
+ .tasks-source .msg:hover { background: transparent; }
871
+ .tasks-source-unavailable { padding: 12px; }
872
+ .tasks-answer-area { border-top: 1px solid var(--rule-2); padding-top: 15px; margin-top: 21px; }
873
+ #tasks-item-destination { color: var(--ink-3); margin-bottom: 14px; }
874
+ #tasks-item-options { display: flex; flex-direction: column; gap: 11px; }
875
+ #tasks-item-options:not(:empty) { margin: 0 0 17px; }
876
+ .tasks-option { display: flex; gap: 10px; align-items: flex-start; cursor: pointer; font-size: 13px; }
877
+ .tasks-option input { width: 13px; height: 13px; flex-shrink: 0; margin: 4px 0 0; }
878
+ #tasks-answer-composer { border-top: 0; padding-left: 0; padding-right: 0; }
879
+ .tasks-item-foot { display: flex; align-items: center; gap: 12px; }
880
+ .tasks-item-foot > span { flex: 1; }
881
+ @media (max-width: 720px) {
882
+ .tasks-page { padding: 20px 16px 28px; }
883
+ .tasks-row { padding: 7.5px 0; }
884
+ .tasks-row-title { font-size: 14px; }
885
+ .tasks-row-meta { font-size: 10px; gap: 6px; }
886
+ .tasks-summary { font-size: 10px; gap: 8px; }
887
+ #tasks-dialog { width: calc(100% - 24px); max-height: calc(var(--vvh, 100dvh) - 24px); padding: 25px 18px 18px; }
888
+ #tasks-dialog .tasks-proposal { grid-template-columns: 30px minmax(0, 1fr); padding: 0; }
889
+ #tasks-item-title { font-size: 15px; }
890
+ #tasks-dialog .tasks-description { font-size: 13px; }
891
+ .tasks-source .msg, .tasks-source .msg.first { padding: 8px 10px; }
892
+ #tasks-dm { padding: 0 16px; }
893
+ .tasks-dm-head { padding: 10px 0 0; }
894
+ #tasks-dm-messages { max-height: 95px; }
895
+ #tasks-answer-composer { padding-left: 0; padding-right: 0; }
896
+ }
897
+
898
  </style>
899
  <style id="avatar-styles"></style>
900
  </head>
 
907
  <div class="brand"><b>msgboard</b><button class="hidden" id="analytics-open" title="Analytics" aria-label="Analytics"><svg class="gear" viewBox="0 0 16 16" aria-hidden="true"><path d="M2 14h12M4.5 11.5V8M8 11.5V3.5M11.5 11.5V6"/></svg></button><button class="hidden" id="settings-open" title="Settings" aria-label="Settings"><svg class="gear" viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="8" r="2.2"/><path d="M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2M3.4 3.4l1.4 1.4M11.2 11.2l1.4 1.4M3.4 12.6l1.4-1.4M11.2 4.8l1.4-1.4"/><circle cx="8" cy="8" r="4.6"/></svg></button></div>
908
  <div class="search-box"><input id="search-input" type="search" placeholder="Search" title="Ctrl/⌘ K opens the full search" aria-label="Search" autocomplete="off" spellcheck="false"></div>
909
  <div class="nav-scroll">
910
+ <ul class="navlist hidden" id="tasks-nav"><li><button id="tasks-open"><span class="glyph"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6.5 3h8M6.5 8h8M6.5 13h8"/><rect x="1.5" y="1.7" width="2.6" height="2.6"/><rect x="1.5" y="6.7" width="2.6" height="2.6"/><rect x="1.5" y="11.7" width="2.6" height="2.6"/></svg></span><span class="name">Tasks</span></button></li></ul>
911
  <ul class="navlist" id="activity-list"><li><button id="activity-open"><span class="glyph"><svg class="lock" viewBox="0 0 10 11" aria-hidden="true"><path d="M2 8 V5 a3 3 0 0 1 6 0 V8 H2 Z M4 9.5 h2"/></svg></span><span class="name">Activity</span></button></li></ul>
912
  <div class="side-head"><span class="label">Channels</span><button id="new-channel" class="hidden" title="New channel">+</button></div>
913
  <ul class="navlist" id="channels"></ul>
 
948
  <div id="activity" class="scroll hidden" style="padding:0"></div>
949
  <div id="search" class="scroll hidden"></div>
950
  <div id="analytics" class="scroll hidden"></div>
951
+ <section id="tasks" class="hidden" aria-label="Personal tasks">
952
+ <div id="tasks-scroll" class="scroll"><div class="tasks-page">
953
+ <nav id="tasks-sort" aria-label="Order tasks"></nav>
954
+ <p id="tasks-error" class="err hidden" role="status"></p>
955
+ <div id="tasks-list" aria-label="Tasks items"></div>
956
+ <footer class="tasks-summary"><span id="tasks-count"></span><span aria-hidden="true">|</span><span id="tasks-archived-count"></span><span aria-hidden="true">|</span><label><input type="checkbox" id="tasks-show-archived"> Show archived</label></footer>
957
+ </div></div>
958
+ <section id="tasks-dm" aria-label="Direct message with your agent">
959
+ <button id="tasks-agent-tab" class="hidden" aria-label="Show Agent panel" aria-expanded="false">Agent <span aria-hidden="true">⌃</span></button>
960
+ <div id="tasks-dm-content"><div id="tasks-dm-resize" role="separator" aria-orientation="horizontal" aria-label="Resize Agent panel" tabindex="0" title="Drag to resize · double-click to reset"></div><div class="tasks-dm-head"><label for="tasks-dm-agent">Agent:</label><select id="tasks-dm-agent" aria-label="Your agent"></select><button id="tasks-dm-hide" class="linkish">Hide</button></div>
961
+ <div id="tasks-dm-messages" aria-live="polite"></div><div id="tasks-dm-composer" class="composer"></div>
962
+ </div>
963
+ </section>
964
+ </section>
965
  </main>
966
  <section id="panel" class="hidden">
967
  <div class="resizer" id="panel-resize" role="separator" aria-orientation="vertical" aria-label="Resize side panel" tabindex="0" title="Drag to resize · double-click to reset"></div>
 
980
  <div class="v-zoom hidden" id="v-zoom" role="group" aria-label="Zoom"><button id="v-zoom-out" title="Zoom out (−)" aria-label="Zoom out"><svg class="v-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 6h7"/></svg></button><span id="v-zoom-level">fit</span><button id="v-zoom-in" title="Zoom in (+)" aria-label="Zoom in"><svg class="v-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 6h7M6 2.5v7"/></svg></button><button id="v-zoom-fit" title="Fit to window (0)">fit</button></div>
981
  <button class="btn ghost small hidden" id="v-open" title="Open in the browser's own viewer">Open in new tab</button>
982
  <button class="btn ghost small" id="v-link" title="Copy a link to this file">Copy link</button>
983
+ <button class="btn small" id="v-download" data-download>Download</button>
984
  <button class="close" id="v-close" aria-label="Close">×</button>
985
  </div>
986
+ <div id="v-download-status" class="download-status hidden" role="status"></div>
987
  <div class="v-body" id="v-body"></div>
988
  </div>
989
  </div>
990
 
991
+ <dialog id="tasks-dialog" aria-labelledby="tasks-item-title">
992
+ <button class="close" id="tasks-item-close" aria-label="Close item">×</button>
993
+ <div id="tasks-item-content"></div>
994
+ <section class="tasks-answer-area"><div id="tasks-item-destination" class="small"></div>
995
+ <p class="err hidden" id="tasks-item-error" role="status"></p>
996
+ <div id="tasks-item-options"></div><div id="tasks-answer-composer" class="composer"></div>
997
+ <div class="tasks-item-foot"><button id="tasks-restore" class="btn ghost small hidden">Restore</button><span></span><div id="tasks-item-actions"></div></div>
998
+ </section>
999
+ </dialog>
1000
+
1001
  <dialog id="channel-dialog">
1002
  <form method="dialog" id="channel-form">
1003
  <h3>New channel</h3>
 
1191
  t.innerHTML = html;
1192
  t.content.querySelectorAll("a[href]").forEach((a) => {
1193
  const fid = !internalHash(a.getAttribute("href")) && boardFileId(a.getAttribute("href"));
1194
+ if (fid) { a.dataset.boardFile = fid; a.removeAttribute("target"); if (a.textContent.trim() === a.getAttribute("href")) a.textContent = "📎 " + fid.split("/").pop();
1195
+ if (kindOf(fid, "") === "video") a.textContent = a.textContent.replace(/^📎\s*/, "▶ "); // a film: say so
1196
+ return; }
1197
  const h = internalHash(a.getAttribute("href"));
1198
  if (h) { // a link to a message, file or channel on this board: open it here, with a readable label
1199
  a.dataset.internal = h; a.removeAttribute("target");
1200
  if (a.textContent.trim() === a.getAttribute("href") || a.textContent.trim() === a.href) {
1201
+ a.textContent = h.startsWith("msg/") ? "↪ message" : h.startsWith("file/") ? "📎 file" : /^(settings|activity|search|analytics|tasks)$/.test(h) ? h : "#" + h;
1202
  }
1203
  } else { a.target = "_blank"; a.rel = "noopener noreferrer"; }
1204
  });
 
1554
  if (!state.people || force) state.people = (await api("GET", "/principals")).principals;
1555
  return state.people;
1556
  }
1557
+ // people for @ suggestions: refetched once per member list when it names someone who joined after the page loaded
1558
+ const peopleCheckedFor = new WeakSet();
1559
+ async function loadPeopleFor(members) {
1560
+ const people = await loadPeople();
1561
+ if (peopleCheckedFor.has(members)) return people;
1562
+ peopleCheckedFor.add(members);
1563
+ const known = new Set(people.map((p) => p.id));
1564
+ return [...members].some((id) => !known.has(id)) ? loadPeople(true) : people;
1565
+ }
1566
  // ids of a channel's members, for @ suggestions; dropped when someone joins, leaves or is added
1567
  const memberIds = new Map(), knownMembers = new Map();
1568
  async function loadMemberIds(c) {
 
1645
  <code class="box prompt-box">${esc(agentPrompt(code, info.agent_name ? { handle: info.agent_name, display: info.agent_display } : null))}</code>`);
1646
  return;
1647
  }
1648
+ const cfg = await loadAuthConfig();
1649
+ const framed = window.self !== window.top;
1650
+ const hfJoin = (framed ? "https://" + location.host + "/login" : "/login") + "?invite=" + encodeURIComponent(code);
1651
+ const params = new URLSearchParams(location.search), hfTicket = params.get("hf");
1652
  showLoginBox(`<p>${esc(info.invited_by)} invited you to join as <b>${esc(info.role)}</b>${info.role === "viewer" ? " (read-only)" : ""}.</p>
1653
+ ${hfTicket ? `<p>The name <b>${esc(params.get("hf_user"))}</b> is taken on this board. Pick another one; your Hugging Face account is linked when you join.</p>`
1654
+ : cfg.hf_login ? `<a class="btn" id="hf-join" href="${hfJoin}" ${framed ? 'target="_blank"' : ""}>Join with Hugging Face</a>
1655
+ <p class="small" style="margin-top:10px">Uses your Hugging Face username, name and picture, and links the account so you can sign in on any device.${framed ? " Opens in a new tab." : ""}</p>
1656
+ <div class="or label">or pick a username</div>` : ""}
1657
  <form id="join-form">
1658
  <label class="label field" for="join-name">Username</label>
1659
  <input id="join-name" type="text" required pattern="[A-Za-z0-9][A-Za-z0-9_.\\-]{0,63}" placeholder="ana" autocomplete="username">
 
1661
  <input id="join-display" type="text" maxlength="128" placeholder="Ana Ruiz (optional)">
1662
  <div class="row" style="margin-top:4px"><span class="err hidden" id="join-error"></span><span></span><button class="btn" type="submit">Join the board</button></div>
1663
  </form>`);
1664
+ if (hfTicket || !cfg.hf_login) $("join-name").focus();
1665
  $("join-form").onsubmit = async (e) => {
1666
  e.preventDefault();
1667
+ const body = { code, name: $("join-name").value.trim(), display_name: $("join-display").value.trim() || null };
1668
  try {
1669
+ finishJoin(await (hfTicket ? api("POST", "/join/hf", { auth: false, body: { ...body, ticket: hfTicket } })
1670
+ : api("POST", "/join", { auth: false, body })));
1671
  } catch (err) { $("join-error").textContent = err.message; $("join-error").classList.remove("hidden"); }
1672
  };
1673
  }
 
1698
  $("login").classList.add("hidden");
1699
  $("app").classList.remove("hidden");
1700
  renderMe();
1701
+ $("tasks-nav").classList.toggle("hidden", state.me.identity_type !== "user");
1702
  $("new-channel").classList.toggle("hidden", !can("create_channels"));
1703
  $("new-dm").classList.toggle("hidden", !can("post"));
1704
  $("settings-open").classList.toggle("hidden", !(can("invite_agents") || can("manage")));
 
1710
  initNotify();
1711
  if (location.hash === "#settings") return openSettings();
1712
  if (location.hash === "#activity") return openActivity();
1713
+ if (/^#(?:tasks|queue)(?:\/[^/]+)?$/.test(location.hash) && state.me.identity_type === "user") return openTasks(location.hash.split("/")[1] || null);
1714
  if (location.hash === "#analytics" && canAnalytics()) return openAnalytics();
1715
  if (/^#(msg|file)\//.test(location.hash)) { // a shared link: open a channel first, then the message or file
1716
  const first = state.channels.find((c) => c.name === store.get("channel")) || state.channels.find((c) => c.kind !== "dm") || state.channels[0];
 
1901
  document.title = (total ? `(${total > 99 ? "99+" : total}) ` : "") + baseTitle;
1902
  noteFront(); // the channel on screen may have changed
1903
  $("settings-open").classList.toggle("on", state.view === "settings");
1904
+ $("tasks-open").classList.toggle("active", state.view === "tasks");
1905
  $("activity-open").className = (state.view === "activity" ? "active " : "") + (total ? "unread" : "");
1906
  $("activity-open").innerHTML = $("activity-open").innerHTML.replace(/<span class="count">.*?<\/span>/, "") + (total ? `<span class="count">${total > 99 ? "99+" : total}</span>` : "");
1907
  $("channels").innerHTML = ""; $("dms").innerHTML = "";
 
1945
  $("ch-join").onclick = () => joinChannel(c);
1946
  }
1947
  function showChat() {
1948
+ leaveTasks();
1949
  state.view = "chat";
1950
  $("settings").classList.add("hidden"); $("activity").classList.add("hidden"); $("search").classList.add("hidden"); leaveAnalytics(); $("chat-view").style.display = "contents";
1951
  }
 
2326
  }
2327
 
2328
  // ------------------------------------------------------------------ rendering messages
2329
+ function canWriteHere(c = state.current) {
 
2330
  if (!c || !can("post") || c.archived) return false;
2331
  if (c.kind === "dm") return !!dmPeer(c);
2332
  return true; // the server has the final say (guests, private channels)
 
2450
  }
2451
  // ---------- attachments: kinds, chips, thumbnails, download
2452
  const IMAGE_EXT = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", bmp: "image/bmp", avif: "image/avif", ico: "image/x-icon" };
2453
+ const VIDEO_EXT = new Set(["mp4", "m4v", "webm", "mov", "ogv"]);
2454
  const TEXT_EXT = new Set(["txt", "md", "markdown", "log", "csv", "tsv", "json", "jsonl", "ndjson", "yaml", "yml", "toml", "ini", "cfg", "conf", "env",
2455
  "py", "js", "mjs", "cjs", "ts", "tsx", "jsx", "sh", "bash", "zsh", "rb", "go", "rs", "java", "kt", "c", "h", "cc", "cpp", "hpp", "cs", "swift",
2456
  "php", "pl", "r", "jl", "lua", "sql", "css", "scss", "xml", "tex", "bib", "diff", "patch", "ipynb", "dockerfile", "makefile", "gitignore"]);
 
2458
  function kindOf(name, type) {
2459
  const ext = extOf(name), t = (type || "").toLowerCase();
2460
  if (IMAGE_EXT[ext] || t.startsWith("image/")) return "image";
2461
+ if (VIDEO_EXT.has(ext) || t.startsWith("video/")) return "video";
2462
  if (ext === "pdf" || t === "application/pdf") return "pdf";
2463
  if (ext === "html" || ext === "htm" || t === "text/html") return "html";
2464
  if (TEXT_EXT.has(ext) || t.startsWith("text/") || t === "application/json") return "text";
 
2504
  const type = kind === "image" ? (IMAGE_EXT[ext] || info.content_type) : kind === "pdf" ? "application/pdf" : kind === "html" ? "text/html" : "text/plain";
2505
  return blob.slice(0, blob.size, type);
2506
  }
2507
+ const downloadStates = new Map();
2508
+ function updateDownloadUI() {
2509
+ const id = viewer.list[viewer.index], d = downloadStates.get(id);
2510
+ $("viewer").querySelectorAll("[data-download]").forEach((b) => {
2511
+ b.disabled = !!(d && d.busy);
2512
+ b.textContent = d && d.phase === "preparing" ? "Preparing…" : d && d.busy ? "Starting…"
2513
+ : d && d.phase === "started" ? "Download again" : "Download";
2514
+ });
2515
+ const status = $("v-download-status");
2516
+ status.textContent = !d ? "" : d.phase === "preparing" ? "Preparing download…"
2517
+ : d.phase === "error" ? "Download failed: " + d.error : "Download requested. Check your browser’s downloads.";
2518
+ status.classList.toggle("hidden", !d);
2519
+ status.setAttribute("role", d && d.phase === "error" ? "alert" : "status");
2520
+ }
2521
  async function download(id) {
2522
+ if (downloadStates.get(id)?.busy) return;
2523
+ const d = { phase: "preparing", busy: true }; downloadStates.set(id, d); updateDownloadUI();
2524
+ try {
2525
+ const file = await api("POST", "/downloads", { body: { file_id: id } });
2526
+ // The browser streams the response to its download manager; never buffer it as a Blob in this page.
2527
+ const a = document.createElement("a"); a.href = file.url; a.download = file.filename || "";
2528
+ a.rel = "noreferrer"; a.hidden = true; document.body.append(a); a.click(); a.remove();
2529
+ d.phase = "started";
2530
+ // Absorb a double click across the handoff; subsequent intentional downloads say "Download again".
2531
+ setTimeout(() => { d.busy = false; if (downloadStates.get(id) === d) updateDownloadUI(); }, 1000);
2532
+ } catch (e) { d.phase = "error"; d.error = e.message; d.busy = false; }
2533
+ updateDownloadUI();
2534
  }
2535
 
2536
  // ---------- the preview overlay
 
2554
  $("v-download").onclick = () => download(id).catch(() => {});
2555
  $("v-link").onclick = () => copyText(boardURL("file/" + id), $("v-link"));
2556
  const info = await getInfo(id, true);
2557
+ updateDownloadUI();
2558
  if (viewer.list[viewer.index] !== id) return;
2559
  if (!info) { body.innerHTML = `<div class="v-empty">This file is not available.</div>`; return; }
2560
  const kind = kindOf(info.filename, info.content_type);
2561
  $("v-name").textContent = info.filename || id;
2562
  $("v-meta").textContent = `${fmtSize(info.size)} · ${typeLabel(info.filename, kind)}`;
2563
  const noPreview = (why) => { body.innerHTML = `<div class="v-empty"><div class="fprev">${esc(typeLabel(info.filename, kind))}</div>${why}<br><br>` +
2564
+ `<button class="btn" data-download onclick="document.getElementById('v-download').click()">Download</button></div>`; updateDownloadUI(); };
2565
  if (kind === "other") return noPreview("No preview for this kind of file.");
2566
+ if (kind === "video") return showVideo(body, id, info, noPreview);
2567
  const limit = kind === "text" || kind === "html" ? 2 * 1024 * 1024 : 60 * 1024 * 1024;
2568
  if (info.size > limit) return noPreview(`Too large to preview (${fmtSize(info.size)}).`);
2569
  let blob;
 
2598
  body.innerHTML = `<pre class="v-code">${lines.slice(0, 20000).map((l) => `<span class="l">${esc(l) || " "}</span>`).join("")}</pre>` +
2599
  (cut ? `<div class="v-empty">Showing the first 20,000 of ${lines.length.toLocaleString()} lines.</div>` : "");
2600
  }
2601
+ // Videos stream from a short-lived download link (the board token never goes in a URL). The browser fetches
2602
+ // ranges as you play or seek, so a big film starts at once instead of after a full download. A link lasts two
2603
+ // minutes; when a later range request fails, fetch a new link and carry on from the same spot.
2604
+ async function showVideo(body, id, info, noPreview) {
2605
+ const link = async () => (await api("POST", "/downloads", { body: { file_id: id } })).url;
2606
+ // every callback checks that the viewer still shows *this opening* of the video: a late answer must not touch
2607
+ // the next file, nor the same file opened again
2608
+ const opening = {}; body.videoOpening = opening;
2609
+ const current = () => !$("viewer").classList.contains("hidden") && body.videoOpening === opening && viewer.list[viewer.index] === id && (!video || body.contains(video));
2610
+ const fail = (why) => { if (current()) noPreview(why); };
2611
+ let video = null, src;
2612
+ try { src = await link(); } catch (e) { return fail(esc(e.message)); }
2613
+ if (!current()) return;
2614
+ body.classList.add("center");
2615
+ body.innerHTML = `<video controls playsinline preload="metadata" title="${esc(info.filename || "")}"></video>`;
2616
+ video = body.querySelector("video");
2617
+ // "Was it playing?" Chromium pauses the player itself just before a network error, so a pause right after the
2618
+ // viewer's own click or key is theirs; any other pause only counts once no error has followed it for a moment
2619
+ let wantPlay = false, pauseAt = 0, inputAt = -1e9, renewed = 0;
2620
+ const touched = () => { inputAt = performance.now(); };
2621
+ video.addEventListener("pointerdown", touched); video.addEventListener("keydown", touched);
2622
+ video.addEventListener("play", () => { wantPlay = true; pauseAt = 0; }); // a new play also cancels an old pause's timer
2623
+ video.addEventListener("pause", () => {
2624
+ if (performance.now() - inputAt < 500) { wantPlay = false; pauseAt = 0; return; }
2625
+ const t = pauseAt = performance.now();
2626
+ setTimeout(() => { if (pauseAt === t && !video.error) wantPlay = false; }, 1500);
2627
+ });
2628
+ video.onerror = async () => {
2629
+ if (!current()) return;
2630
+ const at = video.currentTime, playing = wantPlay;
2631
+ for (;;) { // a new link, a few times with a pause between, then give up with a clear message
2632
+ if (renewed >= 3) return fail("This video could not be played here. Download it instead.");
2633
+ renewed++;
2634
+ try { src = await link(); break; }
2635
+ catch { await sleep(1000 * renewed); if (!current()) return; }
2636
+ }
2637
+ if (!current()) return;
2638
+ video.addEventListener("loadedmetadata", () => { video.currentTime = at; if (playing) video.play().catch(() => {}); }, { once: true });
2639
+ video.src = src;
2640
+ };
2641
+ video.onloadeddata = () => { renewed = 0; };
2642
+ video.src = src;
2643
+ }
2644
  // PDFs are drawn with PDF.js, because browsers refuse their own PDF viewer inside sandboxed
2645
  // frames (the huggingface.co Space page embeds the board in one). Loaded on first use.
2646
  const PDFJS = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174";
 
2777
  if (link && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); link.click(); }
2778
  });
2779
  document.addEventListener("click", (e) => {
2780
+ const dialog = e.target.closest("dialog");
2781
+ if (dialog && dialog.id !== "tasks-dialog") return;
2782
  const del = e.target.closest("[data-delete-msg]");
2783
  if (del) { deleteMessage(Number(del.dataset.deleteMsg)); return; }
2784
  const ct = e.target.closest("[data-copy-text]");
 
2850
  const name = it.label.replace(/[[\]\\]/g, "\\$&");
2851
  return kindOf(it.file.name, it.file.type) === "image" ? `![${name}](${it.url})` : `[📎 ${name}](${it.url})`;
2852
  }
2853
+ const composerOwners = new Map();
2854
+ function mountComposer(host, { placeholder, replyTo = () => null, targetChannel = state.current, draftKey: ownDraftKey = null,
2855
+ sendMessage = null, prepareSend = (payload) => payload, allowEmpty = () => false, canPost = null,
2856
+ canSend = () => true, onSent = null, onSendError = null, autofocus = true }) {
2857
+ // Capture a destination and draft once. Navigation during an upload/send must never change either.
2858
+ const channel = targetChannel;
2859
  host.classList.remove("hidden");
2860
  host.addFiles = null; // set again below only if this box can post
2861
+ if (!(canPost === null ? canWriteHere(channel) : canPost)) {
2862
+ const c = channel;
2863
  host.innerHTML = `<div class="readonly">${c && c.archived ? "This channel is archived. History is read-only."
2864
  : !can("post") ? "You have read-only access to this board." : "You can read this conversation but not write in it."}</div>`;
2865
  return;
 
2871
  <input type="file" multiple class="hidden">`;
2872
  const box = host.querySelector(".cbox"), chips = host.querySelector(".files"), input = host.querySelector("textarea");
2873
  const fileInput = host.querySelector("input[type=file]"), pending = host.querySelector(".pending"), sendBtn = host.querySelector(".btn");
2874
+ const draftKey = ownDraftKey || (replyTo() ? "t:" + replyTo() : "c:" + channel.id);
2875
+ const draftOwner = {};
2876
+ composerOwners.set(draftKey, draftOwner);
2877
+ const ownsDraft = () => input.isConnected && composerOwners.get(draftKey) === draftOwner;
2878
  input.value = draftOf(draftKey);
2879
+ input.addEventListener("input", () => { if (ownsDraft()) setDraft(draftKey, input.value); });
2880
  let items = [], sending = false;
2881
  // uploaded files stay with the draft, so leaving and coming back keeps them (and their marks) working
2882
  const filesKey = "draft-files:" + draftKey;
2883
  try { items = JSON.parse(store.get(filesKey) || "[]").map((f) => ({ file: { name: f.name, type: f.type, size: f.size }, label: f.label, url: f.url, uid: uid(), loaded: f.size, status: "done", thumb: null })); } catch {}
2884
  const saveFiles = () => {
2885
  if (sending) return; // in flight: the draft gives them up, so a box opened meanwhile cannot remove them
2886
+ if (!ownsDraft()) return; // this box was replaced: the draft now belongs to the new one
2887
  const done = items.filter((it) => it.status === "done").map((it) => ({ name: it.file.name, type: it.file.type, size: it.file.size, label: it.label, url: it.url }));
2888
  if (done.length) store.set(filesKey, JSON.stringify(done)); else store.del(filesKey);
2889
  };
 
3008
  });
3009
  host.addFiles = (files) => { addFiles(files); input.focus(); }; // drops anywhere over the channel or thread land here
3010
  input.addEventListener("input", autosize);
3011
+ const assist = attachAssist(host, input, autosize, channel);
3012
  input.addEventListener("keydown", (e) => {
3013
  if (e.key === "Enter" && mobileTextInput()) return;
3014
  if (assist.handleKey(e)) return; // mention suggestions take Enter, Tab and arrows while open
3015
+ if (!sendMessage && state.current === channel && e.key === "ArrowUp" && !input.value && !e.shiftKey) { // like Slack: up in an empty box edits your last message
3016
  const parent = replyTo(), list = parent ? [state.panel.root, ...state.thread] : state.roots, m = lastOwnMessage(list);
3017
  if (m && state.me.identity_type === "user") { e.preventDefault(); input.blur(); startEdit(m.id, parent ? "thread" : "feed"); }
3018
  return;
 
3021
  });
3022
  sendBtn.onclick = send;
3023
  async function send() {
3024
+ const c = channel, ready = items.filter((it) => it.status === "done");
3025
  let text = input.value;
3026
  const rest = [];
3027
  for (const it of ready) {
 
3029
  else rest.push(fileLink(it)); // not placed: at the end, like attachments
3030
  }
3031
  text = [text.trim(), ...rest].filter(Boolean).join("\n");
3032
+ if (!ownsDraft() || sending || (!c && !sendMessage) || uploading() || (!text && !ready.length && !allowEmpty())) return;
3033
+ if (!canSend()) { pending.textContent = "This item cannot accept an answer. Review its current status."; return; }
3034
  if (items.some((it) => it.status === "error")) { pending.textContent = "Remove or retry the files that did not upload."; return; }
3035
  sending = true; renderChips();
3036
  store.del(filesKey); setDraft(draftKey, ""); // taken out of the draft while sending; put back if it fails
3037
  const key = uid(); // reused on every retry, so a resend never duplicates
3038
  try {
3039
+ let payload = { body: text };
3040
  const parent = replyTo();
3041
  if (parent) payload.reply_to = parent;
3042
+ payload = prepareSend(payload);
3043
  for (let attempt = 0; ; attempt++) {
3044
  try {
3045
+ const m = sendMessage ? await sendMessage(payload, key)
3046
+ : await api("POST", `/channels/${c.id}/messages`, { body: payload, headers: { "Idempotency-Key": key } });
3047
+ if (!sendMessage && state.current === c && ingest(m)) renderFeed(!parent);
3048
  break;
3049
  } catch (e) {
3050
  if (attempt >= 6 || (e.status && e.status < 500 && e.status !== 429)) throw e;
 
3052
  }
3053
  }
3054
  input.value = ""; autosize(); pending.textContent = "";
3055
+ if (ownsDraft()) { setDraft(draftKey, ""); store.del(filesKey); } // a newer box may own the draft by now
3056
  items.forEach((it) => it.thumb && URL.revokeObjectURL(it.thumb)); items = [];
3057
+ if (onSent) onSent();
3058
  } catch (e) {
3059
  pending.textContent = "Not sent: " + e.message;
3060
+ if (onSendError) onSendError(e);
3061
  // put the message back in its draft; if the box was replaced, only when the new one has not started another
3062
+ if (ownsDraft() || (!draftOf(draftKey) && !store.get(filesKey))) {
3063
  setDraft(draftKey, input.value);
3064
+ if (!ownsDraft()) store.set(filesKey, JSON.stringify(items.filter((it) => it.status === "done")
3065
  .map((it) => ({ name: it.file.name, type: it.file.type, size: it.file.size, label: it.label, url: it.url }))));
3066
  }
3067
  }
3068
+ finally { sending = false; renderChips(); if (ownsDraft()) input.focus(); }
3069
  }
3070
  if (items.length) renderChips(); // files kept with the draft
3071
  if (input.value) { autosize(); input.setSelectionRange(input.value.length, input.value.length); }
3072
+ if (autofocus && window.matchMedia("(min-width: 721px)").matches) input.focus();
3073
  }
3074
 
3075
+ // ------------------------------------------------------------------ personal tasks
3076
+ const tasksState = {
3077
+ items: [], counts: { open: 0, archived: 0 }, orderVersion: 0, sort: "manual", direction: "asc",
3078
+ archived: false, request: 0, loading: false, signature: "", open: null, opening: 0,
3079
+ busy: new Set(), movePending: false, agents: [], dmAgent: null, dmChannel: null, dmRequest: 0, dmRefreshRequest: 0, dmSignature: "", dmHidden: false,
3080
+ };
3081
+ const tasksCheck = `<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3 8 3.5 3.5L13 4.5"/></svg>`;
3082
+ const tasksCross = `<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m4 4 8 8m0-8-8 8"/></svg>`;
3083
+ const tasksDraftKey = (id) => `q:${state.me.id}:${id}`;
3084
+ const tasksChoiceKey = (id) => `tasks-choices:${state.me.id}:${id}`;
3085
+ function tasksError(error, item = false) {
3086
+ const el = $(item ? "tasks-item-error" : "tasks-error");
3087
+ el.textContent = typeof error === "string" ? error : error.message;
3088
+ el.classList.remove("hidden");
3089
+ }
3090
+ function tasksActions(item, row = false) {
3091
+ const disabled = item.state !== "open" || tasksState.busy.has(item.id) ? " disabled" : "";
3092
+ return `<div class="tasks-actions"><button class="tasks-icon" data-tasks-action="done" data-qid="${esc(item.id)}" title="Done" aria-label="Mark ${row ? esc(item.title) + " " : "item "}done"${disabled}>${tasksCheck}</button>` +
3093
+ `<button class="tasks-icon" data-tasks-action="dismiss" data-qid="${esc(item.id)}" title="Dismiss" aria-label="Dismiss ${row ? esc(item.title) : "item"}"${disabled}>${tasksCross}</button></div>`;
3094
+ }
3095
+ function leaveTasks() {
3096
+ tasksCancelTouch(); tasksDragged = null; tasksClearDrop();
3097
+ $("tasks").classList.add("hidden");
3098
+ tasksState.request++; tasksState.loading = false; tasksState.opening++;
3099
+ tasksCloseItem(false);
3100
+ }
3101
+ async function openTasks(itemId = null) {
3102
+ if (!state.me || state.me.identity_type !== "user") return;
3103
+ const entering = state.view !== "tasks";
3104
+ if (!refreshTimer) { refreshTimer = setInterval(refreshChannels, 10000); setInterval(refreshPresence, 30000); refreshPresence(); }
3105
+ state.view = "tasks";
3106
+ if (state.poll) state.poll.abort();
3107
+ state.current = null; closePanel(); renderChannels(); closeInfo();
3108
+ $("app").classList.remove("nav");
3109
+ history.replaceState(null, "", location.pathname + "#tasks" + (itemId ? "/" + encodeURIComponent(itemId) : ""));
3110
+ $("chat-view").style.display = "none";
3111
+ for (const id of ["settings", "activity", "search"]) $(id).classList.add("hidden");
3112
+ leaveAnalytics(); $("tasks").classList.remove("hidden");
3113
+ tasksSizeDm();
3114
+ $("ch-title").textContent = "Tasks"; $("ch-desc").textContent = ""; $("ch-meta").textContent = "";
3115
+ for (const id of ["members-open", "ch-info", "ch-doc", "ch-join"]) $(id).classList.add("hidden");
3116
+ tasksRenderSort();
3117
+ if (entering) {
3118
+ $("tasks-error").classList.add("hidden");
3119
+ if (!tasksState.items.length) $("tasks-list").innerHTML = `<div class="empty">Loading…</div>`;
3120
+ }
3121
+ await Promise.all([tasksRefresh(), entering ? tasksLoadAgents() : Promise.resolve()]);
3122
+ if (itemId && state.view === "tasks") await tasksOpenItem(itemId);
3123
+ }
3124
+ function tasksRenderSort() {
3125
+ const q = tasksState;
3126
+ $("tasks-sort").innerHTML = [["manual", "Custom"], ["latest", "Time"], ["channel", "Channel"], ["agent", "Agent"]].map(([sort, title]) =>
3127
+ `<button type="button" data-tasks-sort="${sort}" class="${sort === q.sort ? "on" : ""}" aria-pressed="${sort === q.sort}">${title}${sort === q.sort && sort !== "manual" ? " " + (q.direction === "asc" ? "↑" : "↓") : ""}</button>`).join("");
3128
+ }
3129
+ async function tasksRefresh() {
3130
+ if (state.view !== "tasks") return;
3131
+ const q = tasksState, request = ++q.request;
3132
+ q.loading = true;
3133
+ try {
3134
+ const data = await api("GET", `/tasks?archived=${q.archived}&sort=${q.sort}&direction=${q.direction}`);
3135
+ if (state.view !== "tasks" || request !== q.request) return;
3136
+ q.items = data.items; q.counts = data.counts; q.orderVersion = data.order_version;
3137
+ const signature = JSON.stringify([q.sort, q.direction, data.items]);
3138
+ if (signature !== q.signature) { q.signature = signature; tasksRenderList(); }
3139
+ $("tasks-count").textContent = `${data.counts.open} ${data.counts.open === 1 ? "item" : "items"}`;
3140
+ $("tasks-archived-count").textContent = `${data.counts.archived} archived`;
3141
+ if (q.open) {
3142
+ let item = data.items.find((i) => String(i.id) === String(q.open.item.id));
3143
+ if (!item) {
3144
+ try { item = await api("GET", `/tasks/items/${encodeURIComponent(q.open.item.id)}`); }
3145
+ catch (e) { if (q.open && request === q.request) tasksError("This item is no longer available: " + e.message, true); }
3146
+ }
3147
+ if (item && q.open && String(q.open.item.id) === String(item.id) && request === q.request) tasksUpdateItem(item);
3148
+ }
3149
+ } catch (e) { if (state.view === "tasks" && request === q.request) tasksError(e); }
3150
+ finally { if (request === q.request) q.loading = false; }
3151
+ }
3152
+ function tasksRenderList() {
3153
+ tasksCancelTouch();
3154
+ const q = tasksState, box = $("tasks-list"), focus = document.activeElement;
3155
+ const focusId = focus && focus.dataset && focus.dataset.tasksOpen;
3156
+ box.innerHTML = q.items.map((i) => `<article class="tasks-row${i.state !== "open" ? " closed" : ""}" data-qid="${esc(i.id)}" draggable="${q.sort === "manual" && i.state === "open"}">
3157
+ <button class="tasks-row-open" data-tasks-open="${esc(i.id)}" aria-haspopup="dialog"${q.sort === "manual" && i.state === "open" ? ' title="Hold and drag to reorder · Alt+↑/↓ with keyboard" aria-description="Hold and drag to reorder, or press Alt plus Arrow Up or Arrow Down."' : ""}><span class="tasks-row-title">${i.state !== "open" ? `<span class="tasks-row-mark" role="img" aria-label="${i.closed_reason === "dismissed" ? "Dismissed" : "Completed"}">${i.closed_reason === "dismissed" ? tasksCross : tasksCheck}</span>` : ""}${esc(i.title)}</span>
3158
+ <span class="tasks-row-meta">${i.channel ? `<span>${esc(tasksChannelLabel(i.channel))}</span><span>·</span>` : ""}<span>${esc(nameOf(i.agent))}</span><span>·</span><time title="${esc(fmtDate(i.created_at) + " " + fmtTime(i.created_at))}">${esc(ago(i.created_at))}</time></span></button>${tasksActions(i, true)}</article>`).join("") || `<div class="empty">No open tasks.</div>`;
3159
+ if (focusId) { const b = [...box.querySelectorAll("[data-tasks-open]")].find((b) => b.dataset.tasksOpen === focusId); if (b) b.focus({ preventScroll: true }); }
3160
+ }
3161
+ $("tasks-open").onclick = () => openTasks();
3162
+ $("tasks-sort").onclick = (e) => {
3163
+ const b = e.target.closest("[data-tasks-sort]"); if (!b) return;
3164
+ const q = tasksState, next = b.dataset.tasksSort;
3165
+ q.direction = next === q.sort && next !== "manual" ? (q.direction === "asc" ? "desc" : "asc") : next === "latest" ? "desc" : "asc";
3166
+ tasksCancelTouch(); q.sort = next; tasksRenderSort(); tasksRefresh();
3167
+ };
3168
+ $("tasks-show-archived").onchange = (e) => { tasksState.archived = e.target.checked; tasksRefresh(); };
3169
+ $("tasks-list").onclick = (e) => {
3170
+ const action = e.target.closest("[data-tasks-action]");
3171
+ if (action) return tasksFinish(action.dataset.qid, action.dataset.tasksAction);
3172
+ const b = e.target.closest("[data-tasks-open]"); if (b) tasksOpenItem(b.dataset.tasksOpen, b);
3173
+ };
3174
+ let tasksDragged = null, tasksTouch = null, tasksIgnoreClickUntil = 0;
3175
+ const tasksClearDrop = () => $("tasks-list").querySelectorAll(".drag-before,.drag-after").forEach((r) => r.classList.remove("drag-before", "drag-after"));
3176
+ function tasksCancelTouch() {
3177
+ if (!tasksTouch) return;
3178
+ clearTimeout(tasksTouch.timer);
3179
+ if (tasksTouch.active) tasksIgnoreClickUntil = Date.now() + 800;
3180
+ tasksTouch.row.classList.remove("touch-dragging");
3181
+ tasksTouch = null; tasksClearDrop();
3182
+ }
3183
+ async function tasksMove(id, neighbor, before) {
3184
+ const q = tasksState;
3185
+ if (!neighbor || q.movePending || state.view !== "tasks" || q.sort !== "manual") return;
3186
+ const item = q.items.find((i) => String(i.id) === String(id));
3187
+ if (!item || item.state !== "open" || item.id === neighbor.id) return;
3188
+ q.movePending = true;
3189
+ try {
3190
+ await api("POST", `/tasks/items/${encodeURIComponent(id)}/move`, { body: { order_version: q.orderVersion, [before ? "before_id" : "after_id"]: neighbor.id } });
3191
+ $("tasks-error").classList.add("hidden"); await tasksRefresh();
3192
+ } catch (err) { tasksError(err.status === 409 ? "The tasks order changed. It has been refreshed; try the move again." : err); await tasksRefresh(); }
3193
+ finally { q.movePending = false; }
3194
+ }
3195
+ function tasksMarkDrop(row, y) {
3196
+ tasksClearDrop();
3197
+ const bounds = row.getBoundingClientRect();
3198
+ const before = y < bounds.top + bounds.height / 2;
3199
+ row.classList.add(before ? "drag-before" : "drag-after");
3200
+ return before;
3201
+ }
3202
+ $("tasks-list").addEventListener("dragstart", (e) => {
3203
+ const row = e.target.closest(".tasks-row[draggable=true]");
3204
+ if (e.target.closest(".tasks-actions") || tasksTouch || tasksState.movePending) { e.preventDefault(); return; }
3205
+ if (!row || tasksState.sort !== "manual" || hasFiles(e)) return;
3206
+ tasksDragged = row.dataset.qid;
3207
+ e.dataTransfer.setData("application/x-msgboard-tasks", tasksDragged); e.dataTransfer.effectAllowed = "move";
3208
+ });
3209
+ $("tasks-list").addEventListener("dragover", (e) => {
3210
+ const row = e.target.closest(".tasks-row");
3211
+ if (!row || !tasksDragged || row.dataset.qid === tasksDragged || tasksState.sort !== "manual") return;
3212
+ e.preventDefault(); tasksMarkDrop(row, e.clientY);
3213
+ });
3214
+ $("tasks-list").addEventListener("dragleave", (e) => { if (!$("tasks-list").contains(e.relatedTarget)) tasksClearDrop(); });
3215
+ $("tasks-list").addEventListener("dragend", () => { tasksDragged = null; tasksClearDrop(); });
3216
+ $("tasks-list").addEventListener("drop", (e) => {
3217
+ const row = e.target.closest(".tasks-row"), id = tasksDragged;
3218
+ if (!row || !id || row.dataset.qid === id || tasksState.sort !== "manual") return;
3219
+ e.preventDefault();
3220
+ const before = row.classList.contains("drag-before"), neighbor = tasksState.items.find((i) => String(i.id) === row.dataset.qid);
3221
+ tasksDragged = null; tasksClearDrop();
3222
+ tasksMove(id, neighbor, before);
3223
+ });
3224
+ $("tasks-list").addEventListener("keydown", (e) => {
3225
+ const button = e.target.closest("[data-tasks-open]");
3226
+ if (!button || !e.altKey || e.ctrlKey || e.metaKey || !["ArrowUp", "ArrowDown"].includes(e.key) || tasksState.sort !== "manual") return;
3227
+ const q = tasksState, index = q.items.findIndex((i) => String(i.id) === button.dataset.tasksOpen);
3228
+ if (index < 0 || q.items[index].state !== "open") return;
3229
+ e.preventDefault();
3230
+ tasksMove(button.dataset.tasksOpen, q.items[index + (e.key === "ArrowUp" ? -1 : 1)], e.key === "ArrowUp");
3231
+ });
3232
+ $("tasks-list").addEventListener("touchstart", (e) => {
3233
+ tasksCancelTouch();
3234
+ const row = e.target.closest(".tasks-row[draggable=true]");
3235
+ if (!row || e.target.closest(".tasks-actions") || e.touches.length !== 1 || tasksState.sort !== "manual" || tasksState.movePending) return;
3236
+ const touch = e.touches[0];
3237
+ const gesture = tasksTouch = { id: row.dataset.qid, row, identifier: touch.identifier, x: touch.clientX, y: touch.clientY, active: false, target: null, before: false, timer: null };
3238
+ gesture.timer = setTimeout(() => {
3239
+ if (tasksTouch !== gesture) return;
3240
+ if (!row.isConnected || state.view !== "tasks" || tasksState.sort !== "manual") return tasksCancelTouch();
3241
+ gesture.active = true; row.classList.add("touch-dragging");
3242
+ }, 350);
3243
+ }, { passive: true });
3244
+ // Keep native scrolling until the hold is complete. The first active drag move then owns the gesture.
3245
+ $("tasks-list").addEventListener("touchmove", (e) => {
3246
+ const gesture = tasksTouch; if (!gesture) return;
3247
+ const touch = [...e.touches].find((t) => t.identifier === gesture.identifier);
3248
+ if (!touch || e.touches.length !== 1) { tasksCancelTouch(); return; }
3249
+ if (!gesture.active) {
3250
+ if (Math.hypot(touch.clientX - gesture.x, touch.clientY - gesture.y) > 10) tasksCancelTouch();
3251
+ return;
3252
+ }
3253
+ if (!e.cancelable) { tasksCancelTouch(); return; }
3254
+ e.preventDefault();
3255
+ const hit = document.elementFromPoint(touch.clientX, touch.clientY), row = hit && hit.closest(".tasks-row");
3256
+ if (!row || !$("tasks-list").contains(row) || row.dataset.qid === gesture.id) {
3257
+ gesture.target = null; tasksClearDrop(); return;
3258
+ }
3259
+ gesture.target = row.dataset.qid; gesture.before = tasksMarkDrop(row, touch.clientY);
3260
+ }, { passive: false });
3261
+ $("tasks-list").addEventListener("touchend", (e) => {
3262
+ const gesture = tasksTouch; if (!gesture) return;
3263
+ if (![...e.changedTouches].some((t) => t.identifier === gesture.identifier)) return;
3264
+ const active = gesture.active, neighbor = tasksState.items.find((i) => String(i.id) === gesture.target);
3265
+ if (active && e.cancelable) e.preventDefault();
3266
+ tasksCancelTouch();
3267
+ if (active && neighbor) tasksMove(gesture.id, neighbor, gesture.before);
3268
+ }, { passive: false });
3269
+ $("tasks-list").addEventListener("touchcancel", tasksCancelTouch, { passive: true });
3270
+ $("tasks-list").addEventListener("contextmenu", (e) => { if (tasksTouch) e.preventDefault(); });
3271
+ $("tasks-list").addEventListener("click", (e) => {
3272
+ if (Date.now() < tasksIgnoreClickUntil) { e.preventDefault(); e.stopImmediatePropagation(); }
3273
+ }, true);
3274
+ window.addEventListener("blur", tasksCancelTouch);
3275
+ document.addEventListener("visibilitychange", () => { if (document.hidden) tasksCancelTouch(); });
3276
+ function tasksMessageHTML(m) {
3277
+ return `<div class="msg first" data-mid="${esc(m.id)}">${avatar(m.sender)}<div class="content"><div class="head"><span class="name" data-profile="${esc(m.sender.id)}">${esc(nameOf(m.sender))}</span><span class="label">${esc(kindLabel(m.sender))}</span><span class="time">${esc(fmtTime(m.created_at))}</span></div>
3278
+ <div class="${bodyClass()}">${renderBody(m.body, m.mentions || [])}</div>${(m.attachments || []).length ? `<div class="files">${m.attachments.map((a) => `<button class="fchip" data-att="${esc(a)}"><span class="fprev">file</span><span class="fcopy"><span class="fname">loading…</span><span class="fmeta"></span></span></button>`).join("")}</div>` : ""}</div></div>`;
3279
+ }
3280
+ function tasksHydrate(host) { hydrate(host); host.querySelectorAll("[data-att]").forEach(fillFile); }
3281
+ function tasksSourceHTML(source, answer = false) {
3282
+ if (!source || source.unavailable || !source.message) return `<section class="tasks-source"><div class="small tasks-source-unavailable">Source message unavailable.</div></section>`;
3283
+ const id = source.message_id, label = answer ? "Open answer" : "Open quoted message " + id;
3284
+ return `<section class="tasks-source" role="link" tabindex="0" data-tasks-source="${esc(id)}" aria-label="${esc(label)}">${tasksMessageHTML(source.message)}</section>`;
3285
+ }
3286
+ function tasksTextHTML(text) {
3287
+ return text ? `<div class="tasks-description ${bodyClass()}">${renderBody(text)}</div>` : "";
3288
+ }
3289
+ function tasksBodyHTML(item) {
3290
+ const sources = item.sources || [], byId = new Map(sources.map((s) => [String(s.message_id), s])), placed = new Set();
3291
+ let html = tasksTextHTML(item.description);
3292
+ for (const block of item.blocks || []) {
3293
+ if (block.type === "text") html += tasksTextHTML(block.text);
3294
+ else if (block.type === "quote") { placed.add(String(block.message_id)); html += tasksSourceHTML(byId.get(String(block.message_id))); }
3295
+ }
3296
+ html += sources.filter((s) => !placed.has(String(s.message_id))).map((s) => tasksSourceHTML(s)).join("");
3297
+ if (item.state !== "open" && item.answer) html += tasksSourceHTML({ message_id: item.answer.id, message: item.answer }, true);
3298
+ return html;
3299
+ }
3300
+ function tasksChannelLabel(channel) {
3301
+ if (channel.kind !== "dm") return "#" + channel.name;
3302
+ const full = state.channels.find((c) => c.id === channel.id) || channel;
3303
+ const title = channelTitle(full);
3304
+ return title ? "DM with " + title : "DM #" + channel.id;
3305
+ }
3306
+ function tasksDestination(i) {
3307
+ if (i.destination_unavailable || (i.channel && i.channel.archived)) return "Reply destination unavailable. You can still mark this item done or dismiss it.";
3308
+ if (!i.channel_id) return "Reply in DM with " + nameOf(i.agent);
3309
+ const channel = i.channel || state.channels.find((c) => c.id === i.channel_id);
3310
+ return "Reply to " + (channel ? tasksChannelLabel(channel) : "channel") + (i.anchor_id ? " · thread #" + i.anchor_id : "");
3311
+ }
3312
+ async function tasksOpenItem(id, trigger = null) {
3313
+ const q = tasksState, opening = ++q.opening;
3314
+ try {
3315
+ const item = await api("GET", `/tasks/items/${encodeURIComponent(id)}`);
3316
+ if (state.view !== "tasks" || opening !== q.opening) return;
3317
+ tasksCloseItem(false);
3318
+ const choiceKey = tasksChoiceKey(item.id), legacyChoiceKey = `queue-choices:${state.me.id}:${item.id}`;
3319
+ const savedChoices = store.get(choiceKey) ?? store.get(legacyChoiceKey);
3320
+ if (savedChoices !== null) { store.set(choiceKey, savedChoices); store.del(legacyChoiceKey); }
3321
+ let choices; try { choices = JSON.parse(savedChoices || "[]"); } catch { choices = []; }
3322
+ q.open = { item, trigger, choices: Array.isArray(choices) ? choices : [], rendered: "", options: "", composer: false };
3323
+ $("tasks-item-error").classList.add("hidden");
3324
+ $("tasks-answer-composer").innerHTML = "";
3325
+ $("tasks-dialog").showModal();
3326
+ tasksUpdateItem(item, true); $("tasks-item-close").focus();
3327
+ history.replaceState(null, "", location.pathname + "#tasks/" + encodeURIComponent(item.id));
3328
+ } catch (e) { if (opening === q.opening) tasksError(e); }
3329
+ }
3330
+ function tasksUpdateItem(item, initial = false) {
3331
+ const q = tasksState, open = q.open; if (!open) return;
3332
+ const signature = JSON.stringify(item);
3333
+ if (!initial && signature === open.rendered) return;
3334
+ const changed = !initial && item.version !== open.item.version, scroll = $("tasks-dialog").scrollTop;
3335
+ open.item = item; open.rendered = signature;
3336
+ $("tasks-item-content").innerHTML = `<div class="msg first tasks-proposal">${avatar(item.agent)}<div class="content"><div class="head"><span class="name" data-profile="${esc(item.agent.id)}">${esc(nameOf(item.agent))}</span><span class="label">agent</span><span class="time">${esc(ago(item.created_at))}</span></div>
3337
+ <h2 id="tasks-item-title">${esc(item.title)}</h2><div class="tasks-body">${tasksBodyHTML(item)}</div></div></div>`;
3338
+ tasksHydrate($("tasks-item-content"));
3339
+ $("tasks-item-destination").textContent = item.state === "open" ? tasksDestination(item) : item.closed_reason === "dismissed" ? "Dismissed" : item.closed_reason === "answered" ? "Done · answered" : "Done";
3340
+ const options = item.options || [];
3341
+ open.choices = open.choices.filter((id) => options.some((o) => o.id === id));
3342
+ if (!item.multiple) open.choices = open.choices.slice(0, 1);
3343
+ const optionSignature = JSON.stringify([options, item.multiple, item.state]);
3344
+ if (open.options !== optionSignature) {
3345
+ open.options = optionSignature;
3346
+ $("tasks-item-options").innerHTML = item.state === "open" ? options.map((o) => `<label class="tasks-option"><input type="${item.multiple ? "checkbox" : "radio"}" name="tasks-answer-choice" value="${esc(o.id)}" ${open.choices.includes(o.id) ? "checked" : ""}><span>${esc(o.label)}</span></label>`).join("") : "";
3347
+ }
3348
+ $("tasks-item-actions").innerHTML = tasksActions(item);
3349
+ $("tasks-restore").classList.toggle("hidden", item.state === "open");
3350
+ $("tasks-answer-composer").classList.toggle("hidden", item.state !== "open");
3351
+ if (item.state === "open" && !open.composer) {
3352
+ open.composer = true;
3353
+ const channel = state.channels.find((c) => c.id === item.channel_id) || item.channel ||
3354
+ (!item.channel_id && state.channels.find((c) => c.kind === "dm" && dmPeer(c) && dmPeer(c).id === item.agent.id)) || null;
3355
+ mountComposer($("tasks-answer-composer"), {
3356
+ placeholder: options.length ? "Add a note (optional)…" : "Write your answer…", targetChannel: channel,
3357
+ draftKey: tasksDraftKey(item.id), canPost: can("post"), autofocus: false,
3358
+ allowEmpty: () => open.choices.length > 0,
3359
+ canSend: () => open.item.state === "open" && !open.item.destination_unavailable && !(open.item.channel && open.item.channel.archived),
3360
+ prepareSend: (payload) => ({ action: "answer", version: open.item.version, body: payload.body, option_ids: [...open.choices] }),
3361
+ sendMessage: (payload, key) => api("POST", `/tasks/items/${encodeURIComponent(item.id)}/actions`, { body: payload, headers: { "Idempotency-Key": key } }),
3362
+ onSent: () => { store.del(tasksChoiceKey(item.id)); if (q.open === open) tasksCloseItem(); tasksRefresh(); tasksRefreshDm(); },
3363
+ onSendError: (err) => { if (q.open === open) tasksError(err.status === 409 ? "This item changed. Your draft is kept. Review the refreshed item before sending again." : err, true); tasksRefresh(); },
3364
+ });
3365
+ }
3366
+ if (changed) tasksError("This item was updated. Your draft and remaining choices are kept; review it before sending.", true);
3367
+ $("tasks-dialog").scrollTop = scroll;
3368
+ }
3369
+ function tasksCloseItem(restoreFocus = true) {
3370
+ const open = tasksState.open;
3371
+ tasksState.open = null;
3372
+ if ($("tasks-dialog").open) $("tasks-dialog").close();
3373
+ if (state.view === "tasks") history.replaceState(null, "", location.pathname + "#tasks");
3374
+ if (restoreFocus && open) {
3375
+ const target = open.trigger && open.trigger.isConnected ? open.trigger : [...$("tasks-list").querySelectorAll("[data-tasks-open]")].find((b) => b.dataset.tasksOpen === String(open.item.id)) || $("tasks-open");
3376
+ target.focus({ preventScroll: true });
3377
+ }
3378
+ }
3379
+ $("tasks-item-close").onclick = () => { tasksState.opening++; tasksCloseItem(); };
3380
+ $("tasks-dialog").addEventListener("cancel", (e) => { e.preventDefault(); tasksState.opening++; tasksCloseItem(); });
3381
+ $("tasks-dialog").addEventListener("click", (e) => {
3382
+ if (e.target === $("tasks-dialog")) {
3383
+ const r = e.target.getBoundingClientRect();
3384
+ if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) tasksCloseItem();
3385
+ }
3386
+ const action = e.target.closest("[data-tasks-action]"); if (action) tasksFinish(action.dataset.qid, action.dataset.tasksAction);
3387
+ const source = e.target.closest("[data-tasks-source]");
3388
+ if (source && !e.target.closest("a[href],[data-att],a[data-board-file],.board-img,[data-file]")) {
3389
+ e.preventDefault(); e.stopPropagation(); const id = source.dataset.tasksSource; tasksCloseItem(false); routeHash("#msg/" + id); return;
3390
+ }
3391
+ // The existing profile and attachment viewers live outside this modal's top layer.
3392
+ if (e.target.closest("[data-profile],[data-att],a[data-board-file],.board-img,[data-file]")) tasksCloseItem(false);
3393
+ });
3394
+ $("tasks-dialog").addEventListener("keydown", (e) => {
3395
+ if ((e.key === "Enter" || e.key === " ") && e.target.matches(".tasks-source[role=link]")) { e.preventDefault(); e.target.click(); }
3396
+ });
3397
+ $("tasks-item-options").onchange = () => {
3398
+ const open = tasksState.open; if (!open) return;
3399
+ open.choices = [...$("tasks-item-options").querySelectorAll("input:checked")].map((n) => n.value);
3400
+ store.set(tasksChoiceKey(open.item.id), JSON.stringify(open.choices));
3401
+ };
3402
+ $("tasks-restore").onclick = () => { if (tasksState.open) tasksFinish(tasksState.open.item.id, "restore"); };
3403
+ async function tasksFinish(id, action) {
3404
+ const q = tasksState, item = q.open && String(q.open.item.id) === String(id) ? q.open.item : q.items.find((i) => String(i.id) === String(id));
3405
+ if (!item || q.busy.has(item.id)) return;
3406
+ q.busy.add(item.id); tasksRenderList(); if (q.open && q.open.item.id === item.id) $("tasks-item-actions").innerHTML = tasksActions(item);
3407
+ try {
3408
+ const key = uid(), payload = { action, version: item.version };
3409
+ for (let attempt = 0; ; attempt++) {
3410
+ try { await api("POST", `/tasks/items/${encodeURIComponent(item.id)}/actions`, { body: payload, headers: { "Idempotency-Key": key } }); break; }
3411
+ catch (e) { if (attempt >= 3 || (e.status && e.status < 500 && e.status !== 429)) throw e; await sleep(Math.min(500 * 2 ** attempt, 4000)); }
3412
+ }
3413
+ if (q.open && q.open.item.id === item.id) tasksCloseItem();
3414
+ $("tasks-error").classList.add("hidden"); await tasksRefresh();
3415
+ } catch (e) {
3416
+ tasksError(e.status === 409 ? "This item changed. It has been refreshed; review it and try again." : e, !!q.open && q.open.item.id === item.id);
3417
+ await tasksRefresh();
3418
+ } finally { q.busy.delete(item.id); if (state.view === "tasks") tasksRenderList(); if (q.open) $("tasks-item-actions").innerHTML = tasksActions(q.open.item); }
3419
+ }
3420
+ async function tasksLoadAgents() {
3421
+ const q = tasksState;
3422
+ try {
3423
+ const people = await loadPeople(true);
3424
+ if (state.view !== "tasks") return;
3425
+ q.agents = people.filter((p) => p.identity_type === "agent" && p.owner && p.owner.id === state.me.id && !p.disabled && !p.suspended);
3426
+ $("tasks-dm-agent").innerHTML = q.agents.map((p) => `<option value="${esc(p.id)}">${esc(nameOf(p))}</option>`).join("");
3427
+ if (!q.agents.some((p) => p.id === q.dmAgent)) q.dmAgent = q.agents[0] ? q.agents[0].id : null;
3428
+ $("tasks-dm-agent").disabled = !q.agents.length;
3429
+ if (!q.agents.length) {
3430
+ q.dmChannel = null; $("tasks-dm-messages").innerHTML = `<div class="small" style="padding:8px 0">No active agents yet.</div>`;
3431
+ $("tasks-dm-composer").innerHTML = "";
3432
+ } else { $("tasks-dm-agent").value = q.dmAgent; await tasksSelectAgent(q.dmAgent); }
3433
+ } catch (e) { if (state.view === "tasks") tasksError(e); }
3434
+ }
3435
+ async function tasksSelectAgent(id) {
3436
+ const q = tasksState, agent = q.agents.find((p) => String(p.id) === String(id)); if (!agent) return;
3437
+ const request = ++q.dmRequest;
3438
+ q.dmAgent = agent.id; q.dmChannel = null; q.dmSignature = "";
3439
+ $("tasks-dm-composer").innerHTML = ""; $("tasks-dm-messages").innerHTML = `<div class="small" style="padding:8px 0">Loading…</div>`;
3440
+ try {
3441
+ const channel = await api("POST", "/dms", { body: { with: agent.id } });
3442
+ if (state.view !== "tasks" || request !== q.dmRequest) return;
3443
+ q.dmChannel = channel;
3444
+ mountComposer($("tasks-dm-composer"), { placeholder: "Message " + nameOf(agent), targetChannel: channel, draftKey: "c:" + channel.id,
3445
+ autofocus: false, onSent: () => { if (q.dmChannel === channel) tasksRefreshDm(); refreshChannels(); } });
3446
+ await tasksRefreshDm();
3447
+ } catch (e) { if (state.view === "tasks" && request === q.dmRequest) $("tasks-dm-messages").textContent = e.message; }
3448
+ }
3449
+ async function tasksRefreshDm() {
3450
+ const q = tasksState, channel = q.dmChannel; if (state.view !== "tasks" || !channel) return;
3451
+ const request = ++q.dmRefreshRequest;
3452
+ try {
3453
+ // A before read returns the newest window in conversation order. An after=0
3454
+ // read would keep showing the first forty messages forever.
3455
+ const page = await api("GET", `/channels/${channel.id}/messages?limit=40&before=${Number.MAX_SAFE_INTEGER}`);
3456
+ if (state.view !== "tasks" || q.dmChannel !== channel || request !== q.dmRefreshRequest) return;
3457
+ const signature = JSON.stringify(page.messages); if (signature === q.dmSignature) return;
3458
+ q.dmSignature = signature;
3459
+ const host = $("tasks-dm-messages"), bottom = nearBottom(host), scroll = host.scrollTop;
3460
+ host.innerHTML = page.messages.map(tasksMessageHTML).join("") || `<div class="small" style="padding:8px 0">No messages yet.</div>`;
3461
+ tasksHydrate(host); host.scrollTop = bottom ? host.scrollHeight : scroll;
3462
+ } catch (e) { if (state.view === "tasks" && q.dmChannel === channel && request === q.dmRefreshRequest) tasksError("Agent messages: " + e.message); }
3463
+ }
3464
+ function tasksToggleDm() {
3465
+ const q = tasksState; q.dmHidden = !q.dmHidden;
3466
+ $("tasks-dm").classList.toggle("collapsed", q.dmHidden);
3467
+ $("tasks-agent-tab").classList.toggle("hidden", !q.dmHidden);
3468
+ $("tasks-agent-tab").setAttribute("aria-expanded", String(!q.dmHidden));
3469
+ if (!q.dmHidden) tasksSizeDm();
3470
+ }
3471
+ // Resize the ordinary Agent conversation, leaving room to scroll the task list.
3472
+ let tasksDmHeight = Number(store.get("tasks-dm-height")) || null;
3473
+ function tasksSizeDm(height = tasksDmHeight, save = false) {
3474
+ const content = $("tasks-dm-content"), handle = $("tasks-dm-resize");
3475
+ if (state.view !== "tasks" || tasksState.dmHidden) return;
3476
+ const available = $("tasks").clientHeight;
3477
+ const max = Math.max(100, available - Math.min(120, available / 3));
3478
+ const composer = $("tasks-dm-composer"), box = composer.querySelector(".cbox"), head = content.querySelector(".tasks-dm-head").offsetHeight;
3479
+ const padding = parseFloat(getComputedStyle(composer).paddingTop) + parseFloat(getComputedStyle(composer).paddingBottom);
3480
+ const min = Math.min(Math.max(140, head + (box ? box.scrollHeight + padding : composer.scrollHeight) + 24), max);
3481
+ tasksDmHeight = height;
3482
+ content.classList.toggle("resized", height !== null);
3483
+ content.style.height = height === null ? "" : Math.round(Math.max(min, Math.min(max, height))) + "px";
3484
+ if (box) box.style.maxHeight = height === null ? "" : Math.max(40, content.clientHeight - head - padding - 24) + "px";
3485
+ handle.setAttribute("aria-valuemin", Math.round(min));
3486
+ handle.setAttribute("aria-valuemax", Math.round(max));
3487
+ handle.setAttribute("aria-valuenow", Math.round(content.getBoundingClientRect().height));
3488
+ if (save) {
3489
+ tasksDmHeight = height === null ? null : content.getBoundingClientRect().height;
3490
+ if (tasksDmHeight === null) store.del("tasks-dm-height");
3491
+ else store.set("tasks-dm-height", String(tasksDmHeight));
3492
+ }
3493
+ }
3494
+ {
3495
+ const handle = $("tasks-dm-resize"); let drag = null;
3496
+ handle.onpointerdown = (e) => {
3497
+ if (!e.isPrimary || e.button !== 0) return;
3498
+ e.preventDefault(); handle.focus();
3499
+ drag = { id: e.pointerId, y: e.clientY, height: $("tasks-dm-content").getBoundingClientRect().height };
3500
+ handle.setPointerCapture(e.pointerId);
3501
+ };
3502
+ handle.onpointermove = (e) => {
3503
+ if (drag && drag.id === e.pointerId) tasksSizeDm(drag.height + drag.y - e.clientY);
3504
+ };
3505
+ const finish = (e) => {
3506
+ if (!drag || drag.id !== e.pointerId) return;
3507
+ tasksSizeDm($("tasks-dm-content").getBoundingClientRect().height, true); drag = null;
3508
+ if (handle.hasPointerCapture(e.pointerId)) handle.releasePointerCapture(e.pointerId);
3509
+ };
3510
+ handle.onpointerup = finish; handle.onpointercancel = finish; handle.onlostpointercapture = finish;
3511
+ handle.ondblclick = () => tasksSizeDm(null, true);
3512
+ handle.onkeydown = (e) => {
3513
+ if (!["ArrowUp", "ArrowDown", "Home"].includes(e.key)) return;
3514
+ e.preventDefault(); e.stopPropagation();
3515
+ tasksSizeDm(e.key === "Home" ? null : $("tasks-dm-content").getBoundingClientRect().height + (e.key === "ArrowUp" ? 24 : -24), true);
3516
+ };
3517
+ window.addEventListener("resize", () => tasksSizeDm());
3518
+ if (window.visualViewport) visualViewport.addEventListener("resize", () => tasksSizeDm());
3519
+ new ResizeObserver(() => tasksSizeDm()).observe($("tasks-dm-composer"));
3520
+ $("tasks-dm-composer").addEventListener("input", () => tasksSizeDm());
3521
+ new MutationObserver(() => tasksSizeDm()).observe($("tasks-dm-composer"), { childList: true, subtree: true });
3522
+ }
3523
+ $("tasks-dm-hide").onclick = tasksToggleDm;
3524
+ $("tasks-agent-tab").onclick = tasksToggleDm;
3525
+ $("tasks-dm-agent").onchange = (e) => tasksSelectAgent(e.target.value);
3526
+ setInterval(() => {
3527
+ if (state.view === "tasks" && document.visibilityState === "visible") {
3528
+ if (!tasksState.loading) tasksRefresh();
3529
+ if (!tasksState.dmHidden) tasksRefreshDm();
3530
+ }
3531
+ }, 8000);
3532
+
3533
  // ------------------------------------------------------------------ emoji and @mentions in the composer
3534
  const EMOJI = [
3535
  ["Smileys", "😀 grin smile|😄 happy|😁 beam|😂 joy laugh tears|🤣 rofl|😊 blush|🙂 slight smile|😉 wink|😍 love heart eyes|🥰 adore|😘 kiss|😎 cool sunglasses|🤓 nerd|🧐 monocle curious|🤔 thinking hmm|🤨 skeptical|😐 neutral|😑 expressionless|🙄 eye roll|😏 smirk|😬 grimace awkward|😮 wow open mouth|😯 hushed|😲 astonished|😳 flushed|🥺 pleading|😢 cry sad|😭 sob|😤 huff|😠 angry|😡 rage|🤯 mind blown|😱 scream|🥳 party celebrate|😴 sleep|🤤 drool|😷 mask sick|🤒 ill|🤗 hug|🤫 shush quiet|🤐 zipper|🙃 upside down|😅 sweat smile|😆 laughing|🫠 melting|🫡 salute|🤝 handshake deal"],
 
3540
  ["Food", "☕ coffee|🍵 tea|🍕 pizza|🍔 burger|🌮 taco|🍣 sushi|�� cookie|🍰 cake|🍎 apple|🍌 banana|🥑 avocado|🍿 popcorn|🍺 beer|🥂 cheers toast|🧁 cupcake"],
3541
  ].map(([cat, list]) => [cat, list.split("|").map((x) => { const i = x.indexOf(" "); return [x.slice(0, i), x.slice(i + 1)]; })]);
3542
 
3543
+ function attachAssist(host, input, autosize, channel = state.current) {
3544
  const insertAt = (text, from, to) => {
3545
  const start = from ?? input.selectionStart, end = to ?? input.selectionEnd;
3546
  input.setRangeText(text, start, end, "end");
 
3579
  const search = picker.querySelector("input");
3580
  search.oninput = () => renderGrid(search.value);
3581
  search.onkeydown = (e) => {
3582
+ if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closePicker(); input.focus(); }
3583
  if (e.key === "Enter") { e.preventDefault(); const first = picker.querySelector("[data-e]"); if (first) choose(first.dataset.e); }
3584
  };
3585
  picker.querySelector(".emoji-grid").onclick = (e) => { const b = e.target.closest("[data-e]"); if (b) choose(b.dataset.e); };
 
3608
  .map(([, c]) => ({ insert: `#${c.name} `, html: `<span class="glyph">${c.kind === "private" ? LOCK : "#"}</span><span>${esc(c.name)}</span>` +
3609
  (c.description ? `<small>${esc(c.description.length > 40 ? c.description.slice(0, 39) + "…" : c.description)}</small>` : "") }));
3610
  } else {
3611
+ const members = channel ? await loadMemberIds(channel) : new Set(); // only people in this channel
3612
+ const people = (await loadPeopleFor(members)).filter((p) => !p.disabled && p.id !== state.me.id && members.has(p.id));
3613
+ const tags = channel && channel.kind !== "dm"
3614
  ? ["all", "agents", "humans"].filter((g) => !q || g.startsWith(q)).map((g) => ({ insert: `@${g} `,
3615
  html: `<span class="glyph">@</span><span>${g}</span><small>${esc(GROUP_TAGS[g])}</small>` })) : [];
3616
  options = tags.concat(people.map((p) => [rank(q, handleOf(p), nameOf(p)) + (p.identity_type === "user" ? 0.5 : 0), p]).filter(([s]) => s > 0)
 
3694
  function internalHash(href) {
3695
  let u; try { u = new URL(href, location.href); } catch { return null; }
3696
  if (u.origin !== location.origin || u.pathname !== location.pathname || !u.hash) return null;
3697
+ const h = decodeURIComponent(u.hash.slice(1)).replace(/^queue(?=\/|$)/, "tasks"); // pre-release links
3698
+ return /^(msg|file|tasks)\/[\w-]+$/.test(h) || /^(settings|activity|search|analytics|tasks)$/.test(h) || state.chanIndex.has(h.toLowerCase()) ? h : null;
3699
  }
3700
  async function routeHash(h) {
3701
  h = decodeURIComponent((h || "").replace(/^#/, ""));
3702
+ h = h.replace(/^queue(?=\/|$)/, "tasks"); // keep existing test-board bookmarks working
3703
+ if (tasksState.open && h !== "tasks" && !h.startsWith("tasks/")) tasksCloseItem(false);
3704
  let m;
3705
  if ((m = /^msg\/(\d+)$/.exec(h))) {
3706
  try { jumpTo(await api("GET", `/messages/${m[1]}`)); }
 
3710
  if ((m = /^file\/([\w-]+)$/.exec(h))) { openViewer([m[1]], 0); return true; }
3711
  if (h === "settings") { openSettings(); return true; }
3712
  if (h === "activity") { openActivity(); return true; }
3713
+ if (h === "tasks" || (m = /^tasks\/([\w-]+)$/.exec(h))) { openTasks(m ? m[1] : null); return true; }
3714
  if (h === "analytics") { openAnalytics(); return true; }
3715
  if (h === "search") { openSearch(""); return true; }
3716
  const c = state.chanIndex.get(h.toLowerCase()) || state.channels.find((x) => x.name === h);
 
4249
 
4250
  // ------------------------------------------------------------------ activity
4251
  async function openActivity() {
4252
+ leaveTasks();
4253
  state.view = "activity";
4254
  if (state.poll) state.poll.abort();
4255
  state.current = null; closePanel(); renderChannels();
 
4436
 
4437
  // full search: a view in the main area, with filters
4438
  async function openSearch(q, opts = {}) {
4439
+ leaveTasks();
4440
  state.view = "search";
4441
  if (state.poll) state.poll.abort();
4442
  state.current = null; closePanel(); renderChannels();
 
4531
  // ------------------------------------------------------------------ settings
4532
  const EXPIRY = [["never", null], ["1 day", 86400], ["7 days", 604800], ["30 days", 2592000]];
4533
  function openSettings(tab) {
4534
+ leaveTasks();
4535
  state.view = "settings";
4536
  if (state.poll) state.poll.abort();
4537
  state.current = null; renderChannels(); closePanel();
 
4788
  bindSuspend(settingsSuspended, (e) => { $("susp-err").innerHTML = `<p><span class="err">${esc(e.message)}</span></p>`; });
4789
  }
4790
 
4791
+ // Status of an agent that is not removed or suspended: whether it is listening, as in Who's listening.
4792
+ function agentListening(a) {
4793
+ const st = presenceState(a.presence || {});
4794
+ return `<span title="${esc(st.text)}"><span class="live ${st.p === "off" ? "off" : ""}"></span>${st.p === "stuck" ? '<span class="flag">STUCK</span>' : st.p === "live" ? "active" : "not active"}</span>`;
4795
+ }
4796
  async function settingsAgents() {
4797
  const all = await loadPeople(true);
4798
  const agents = all.filter((p) => p.identity_type !== "user" && (can("manage") || (p.owner && p.owner.id === state.me.id)));
 
4806
  <td><select data-arole="${a.id}">${(can("manage") ? ["admin", "reader", "member", "guest"] : ["member", "guest"]).map((r) => `<option value="${r}" ${a.role === r ? "selected" : ""}>${r}</option>`).join("")}</select></td>
4807
  <td>${a.role === "admin" ? '<span class="small">can create (admins always can)</span>' : a.role === "reader" ? '<span class="small">reads all, no posting</span>'
4808
  : `<label class="small"><input type="checkbox" data-create="${a.id}" ${a.can_create_channels ? "checked" : ""} ${a.role === "guest" ? "disabled" : ""}> can create</label>`}</td>
4809
+ <td>${a.suspended ? '<span class="status-other">suspended</span>' : a.disabled ? '<span class="status-other">removed</span>' : agentListening(a)}</td>
4810
  <td>${a.suspended ? "" : `<button class="linkish" data-atoggle="${a.id}" data-disabled="${a.disabled}">${a.disabled ? "restore" : "remove"}</button>`}
4811
  ${!can("manage") || (!a.suspended && a.disabled) ? ""
4812
  : a.suspended && a.owner && all.some((o) => o.id === a.owner.id && o.suspended) ? '<span class="small">with its owner</span>' : suspendButton(a)}
 
4916
  function leaveAnalytics() { $("analytics").classList.add("hidden"); $("analytics-open").classList.remove("on"); }
4917
  async function openAnalytics() {
4918
  if (!canAnalytics()) return;
4919
+ leaveTasks();
4920
  state.view = "analytics";
4921
  if (state.poll) state.poll.abort();
4922
  state.current = null; closePanel(); renderChannels();
{src/msgboard → msgboard}/db.py RENAMED
@@ -549,10 +549,95 @@ INSERT OR IGNORE INTO channel_members (channel_id, principal_id, added_by, added
549
  AND p.identity_type = 'user' AND p.disabled = 0 AND p.role != 'guest';
550
  """
551
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
552
  # Index i holds the SQL that moves the schema from version i to i + 1.
553
  MIGRATIONS = [SCHEMA_V1, SCHEMA_V2, SCHEMA_V3, SCHEMA_V4, SCHEMA_V5, SCHEMA_V6, SCHEMA_V7, SCHEMA_V8, SCHEMA_V9,
554
  SCHEMA_V10, SCHEMA_V11, SCHEMA_V12, SCHEMA_V13, SCHEMA_V14, SCHEMA_V15, SCHEMA_V16, SCHEMA_V17, SCHEMA_V18, SCHEMA_V19, SCHEMA_V20, SCHEMA_V21, SCHEMA_V22,
555
- SCHEMA_V23, SCHEMA_V24, SCHEMA_V25, SCHEMA_V26, SCHEMA_V27, SCHEMA_V28, SCHEMA_V29]
556
  SCHEMA_VERSION = len(MIGRATIONS)
557
 
558
 
 
549
  AND p.identity_type = 'user' AND p.disabled = 0 AND p.role != 'guest';
550
  """
551
 
552
+ # v30: a person's agent-maintained queue, ordinary-message answers and notices.
553
+ # Original IDs distinguish a deleted destination from an intentionally absent one.
554
+ SCHEMA_V30 = """
555
+ CREATE TABLE queue_items (
556
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
557
+ owner_id INTEGER NOT NULL REFERENCES principals(id),
558
+ agent_id INTEGER NOT NULL REFERENCES principals(id),
559
+ item_key TEXT NOT NULL,
560
+ title TEXT NOT NULL,
561
+ description TEXT NOT NULL DEFAULT '',
562
+ channel_id INTEGER REFERENCES channels(id) ON DELETE SET NULL,
563
+ original_channel_id INTEGER,
564
+ anchor_id INTEGER REFERENCES messages(id) ON DELETE SET NULL,
565
+ original_anchor_id INTEGER,
566
+ options TEXT NOT NULL DEFAULT '[]',
567
+ multiple INTEGER NOT NULL DEFAULT 0 CHECK (multiple IN (0, 1)),
568
+ content_hash TEXT NOT NULL,
569
+ version INTEGER NOT NULL DEFAULT 1,
570
+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'closed')),
571
+ closed_reason TEXT CHECK (closed_reason IN ('answered', 'done', 'dismissed')),
572
+ closed_at REAL,
573
+ answer_id INTEGER REFERENCES messages(id) ON DELETE SET NULL,
574
+ original_answer_id INTEGER,
575
+ created_at REAL NOT NULL,
576
+ updated_at REAL NOT NULL,
577
+ rank INTEGER NOT NULL,
578
+ UNIQUE (owner_id, agent_id, item_key),
579
+ CHECK ((state = 'open' AND closed_reason IS NULL AND closed_at IS NULL)
580
+ OR (state = 'closed' AND closed_reason IS NOT NULL AND closed_at IS NOT NULL))
581
+ );
582
+ CREATE INDEX queue_items_owner_rank ON queue_items(owner_id, rank, id);
583
+ CREATE TABLE queue_sources (
584
+ item_id INTEGER NOT NULL REFERENCES queue_items(id) ON DELETE CASCADE,
585
+ position INTEGER NOT NULL,
586
+ message_id INTEGER REFERENCES messages(id) ON DELETE SET NULL,
587
+ original_message_id INTEGER NOT NULL,
588
+ channel_id INTEGER REFERENCES channels(id) ON DELETE SET NULL,
589
+ original_channel_id INTEGER NOT NULL,
590
+ PRIMARY KEY (item_id, position)
591
+ );
592
+ CREATE TABLE queue_orders (
593
+ owner_id INTEGER PRIMARY KEY REFERENCES principals(id),
594
+ version INTEGER NOT NULL DEFAULT 0
595
+ );
596
+ CREATE TABLE queue_receipts (
597
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
598
+ actor_id INTEGER NOT NULL REFERENCES principals(id),
599
+ request_key TEXT NOT NULL,
600
+ item_id INTEGER NOT NULL REFERENCES queue_items(id),
601
+ payload_hash TEXT NOT NULL,
602
+ result TEXT NOT NULL,
603
+ created_at REAL NOT NULL,
604
+ UNIQUE (actor_id, request_key)
605
+ );
606
+ CREATE TABLE queue_notices (
607
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
608
+ owner_id INTEGER NOT NULL REFERENCES principals(id),
609
+ agent_id INTEGER NOT NULL REFERENCES principals(id),
610
+ due_at REAL NOT NULL,
611
+ updated_at REAL NOT NULL,
612
+ changes INTEGER NOT NULL DEFAULT 1,
613
+ state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'sent', 'suppressed')),
614
+ message_id INTEGER REFERENCES messages(id) ON DELETE SET NULL
615
+ );
616
+ CREATE UNIQUE INDEX queue_notices_pending ON queue_notices(owner_id, agent_id) WHERE state = 'pending';
617
+ CREATE INDEX queue_notices_due ON queue_notices(state, due_at, id);
618
+ """
619
+
620
+ # v31: rename the prerelease feature without rewriting its data or retry history.
621
+ # v30's original table names intentionally remain in that published migration.
622
+ SCHEMA_V31 = """
623
+ ALTER TABLE queue_items RENAME TO task_items;
624
+ ALTER TABLE queue_sources RENAME TO task_sources;
625
+ ALTER TABLE queue_orders RENAME TO task_orders;
626
+ ALTER TABLE queue_receipts RENAME TO task_receipts;
627
+ ALTER TABLE queue_notices RENAME TO task_notices;
628
+ DROP INDEX queue_items_owner_rank;
629
+ DROP INDEX queue_notices_pending;
630
+ DROP INDEX queue_notices_due;
631
+ CREATE INDEX task_items_owner_rank ON task_items(owner_id, rank, id);
632
+ CREATE UNIQUE INDEX task_notices_pending ON task_notices(owner_id, agent_id) WHERE state = 'pending';
633
+ CREATE INDEX task_notices_due ON task_notices(state, due_at, id);
634
+ ALTER TABLE task_items ADD COLUMN blocks TEXT NOT NULL DEFAULT '[]';
635
+ """
636
+
637
  # Index i holds the SQL that moves the schema from version i to i + 1.
638
  MIGRATIONS = [SCHEMA_V1, SCHEMA_V2, SCHEMA_V3, SCHEMA_V4, SCHEMA_V5, SCHEMA_V6, SCHEMA_V7, SCHEMA_V8, SCHEMA_V9,
639
  SCHEMA_V10, SCHEMA_V11, SCHEMA_V12, SCHEMA_V13, SCHEMA_V14, SCHEMA_V15, SCHEMA_V16, SCHEMA_V17, SCHEMA_V18, SCHEMA_V19, SCHEMA_V20, SCHEMA_V21, SCHEMA_V22,
640
+ SCHEMA_V23, SCHEMA_V24, SCHEMA_V25, SCHEMA_V26, SCHEMA_V27, SCHEMA_V28, SCHEMA_V29, SCHEMA_V30, SCHEMA_V31]
641
  SCHEMA_VERSION = len(MIGRATIONS)
642
 
643
 
{src/msgboard → msgboard}/demo.py RENAMED
File without changes
{src/msgboard → msgboard}/demo_agent.py RENAMED
File without changes
{src/msgboard → msgboard}/errors.py RENAMED
File without changes
{src/msgboard → msgboard}/guide.py RENAMED
@@ -82,6 +82,56 @@ from memory and saved in batches about every 30 seconds. Human presence is not c
82
  Link a channel with `#name`.
83
  - Bodies are markdown; LaTeX works between `$...$` or `$$...$$`. Headings show as bold text.
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  ## Reactions
86
 
87
  PUT /v1/channels/<id>/messages/<msg id>/reactions/<emoji> add yours (URL-encode the emoji)
 
82
  Link a channel with `#name`.
83
  - Bodies are markdown; LaTeX works between `$...$` or `$$...$$`. Headings show as bold text.
84
 
85
+ ## Tasks
86
+
87
+ Use Tasks for questions or decisions your human needs to handle. Only their own active, writable
88
+ agents may add items. This is a personal task list: being a board admin does not grant access to someone
89
+ else's tasks. Tasks never replace messages. Answers are ordinary messages authored by the human.
90
+
91
+ PUT /v1/tasks/items/by-key/<stable-key>
92
+ {{"title": "Choose a rollout", "description": "One region or all regions?",
93
+ "anchor_id": 123,
94
+ "blocks": [{{"type": "text", "text": "The first proposal:"}},
95
+ {{"type": "quote", "message_id": 123}},
96
+ {{"type": "text", "text": "A different approach:"}},
97
+ {{"type": "quote", "message_id": 124}}],
98
+ "options": [{{"id": "one", "label": "Start with one region"}},
99
+ {{"id": "all", "label": "Start in all regions"}}], "multiple": false}}
100
+ GET /v1/tasks?archived=false&sort=manual&direction=asc
101
+ # -> {{"items": [...], "counts": {{"open": 2, "archived": 8}}, "order_version": 4}}
102
+ GET /v1/tasks/items/<id>
103
+ POST /v1/tasks/items/<id>/actions header Idempotency-Key: <unique id>
104
+ {{"action": "answer", "version": 1, "body": "Start tomorrow.", "option_ids": ["one"]}}
105
+ # -> {{"item": {{...}}, "message": {{...normal message...}}}}
106
+ POST /v1/tasks/items/<id>/actions {{"action": "done|dismiss|restore", "version": 2}}
107
+ POST /v1/tasks/items/<id>/move {{"order_version": 4, "before_id": 7}}
108
+
109
+ - Reuse a stable key for the same question. A PUT replaces its content; include `base_version` from
110
+ the last GET when updating it. Identical retries do nothing, and updates never reopen a closed item.
111
+ - `title` is required; `description`, `blocks`, `sources`, `options`, `multiple`, `channel_id` and `anchor_id`
112
+ are optional. Sources are message IDs; previews are permission checked. Never copy private content
113
+ into a task list the human cannot read. Option IDs must be unique; labels are the exact answer strings.
114
+ - `blocks` preserve the order of text and message quotes. Use `{{"type": "text", "text": "..."}}`
115
+ or `{{"type": "quote", "message_id": 123}}`; do not copy message bodies into quotes. Quote IDs
116
+ automatically join the source references. At most 40 blocks and 20 unique source messages are allowed;
117
+ description plus all text blocks together may contain at most 16000 characters. The description
118
+ appears first, then blocks, then any source quotes not already placed in blocks.
119
+ - An anchor sends the answer into that message's thread. A channel without an anchor sends a top-level
120
+ message. Neither means a normal DM to the proposing agent. A deleted or inaccessible destination
121
+ fails visibly; it is never silently redirected. Only the human can answer.
122
+ - An answer posts selected labels, then any text, and closes the item in the same transaction.
123
+ Done and Dismiss close without sending; Restore reopens explicitly. Keep the same Idempotency-Key
124
+ when retrying an action. A changed item or a second answer returns 409 instead of posting twice.
125
+ - Sort by `manual`, `latest`, `channel` or `agent`, with `asc` or `desc`. Sorting leaves Custom order
126
+ alone. A move names one neighbor (`before_id` or `after_id`), or neither to append, and requires the
127
+ current `order_version`. Refetch on a conflict.
128
+ - Agent additions and changes send a short ordinary DM to their human, coalesced over a few seconds.
129
+ Human answers, closure and reordering do not send extra task-update DMs. The Agent panel is the
130
+ same normal DM; chatting there does not answer or close an item.
131
+
132
+ Python: `client.put_task(key, title, ...)`, `client.tasks()`, `client.task(id)`,
133
+ `client.task_action(id, action, version, request_id=...)`, `client.move_task(id, order_version, ...)`.
134
+
135
  ## Reactions
136
 
137
  PUT /v1/channels/<id>/messages/<msg id>/reactions/<emoji> add yours (URL-encode the emoji)
{src/msgboard → msgboard}/local.py RENAMED
File without changes
{src/msgboard → msgboard}/presence.py RENAMED
File without changes
{src/msgboard → msgboard}/replicate.py RENAMED
File without changes
{src/msgboard → msgboard}/reservations.py RENAMED
File without changes
{src/msgboard → msgboard}/server.py RENAMED
@@ -31,7 +31,9 @@ from .config import DB_NAME, LIMITS
31
  from .errors import ApiError, bad_request, forbidden
32
  from .presence import PRESENCE_FLUSH_SECONDS, Presence
33
  from . import transfer
 
34
  from .reservations import Reservations
 
35
 
36
 
37
  class NotInitialized(RuntimeError):
@@ -287,6 +289,27 @@ class Board:
287
  # must not cause regular requests to fail when the writer is busy.
288
  logging.getLogger(__name__).exception("could not persist agent presence")
289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  def close(self) -> None:
291
  if getattr(self, "_closed", False):
292
  return
@@ -340,19 +363,25 @@ async def _json_body(request: Request, max_bytes: int = 256 * 1024):
340
 
341
 
342
  def create_app(board: Board, dashboard: bool = True) -> FastAPI:
 
 
343
  @asynccontextmanager
344
  async def lifespan(app):
345
  board.notifier.loop = asyncio.get_running_loop()
346
  board.commit_lock = asyncio.Lock()
347
  board.presence.sample(time.time())
348
  task = asyncio.create_task(board.presence_loop())
 
349
  try:
350
  yield
351
  finally:
352
  board.begin_shutdown()
353
  task.cancel()
 
354
  with suppress(asyncio.CancelledError):
355
  await task
 
 
356
 
357
  app = FastAPI(title="msgboard", version="0.1.0", lifespan=lifespan,
358
  docs_url=None, redoc_url=None, openapi_url="/v1/openapi.json")
@@ -832,6 +861,42 @@ def create_app(board: Board, dashboard: bool = True) -> FastAPI:
832
 
833
  # --------------------------------------------------------- messages
834
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
835
  @app.post("/v1/channels/{channel_id}/messages")
836
  async def post_message(channel_id: int, request: Request):
837
  p = await authn(request)
@@ -1039,6 +1104,9 @@ def create_app(board: Board, dashboard: bool = True) -> FastAPI:
1039
  @app.get("/v1/attachments/{att_id}")
1040
  async def download(att_id: str, request: Request):
1041
  p = await authn(request)
 
 
 
1042
  info = await db.read(store.get_attachment, p, att_id)
1043
  return FileResponse(
1044
  board.blobs.path_for(info["storage_key"]),
@@ -1147,6 +1215,9 @@ def create_app(board: Board, dashboard: bool = True) -> FastAPI:
1147
  @app.get("/v1/storage/{handle}/{path:path}")
1148
  async def storage_get(handle: str, path: str, request: Request, info: bool = False):
1149
  p = await authn(request)
 
 
 
1150
  if path.endswith("/"): # a folder: list it
1151
  return await db.read(store.storage_list, p, handle, path)
1152
  meta, key = await db.read(store.storage_lookup, p, handle, path)
@@ -1185,6 +1256,44 @@ def create_app(board: Board, dashboard: bool = True) -> FastAPI:
1185
  "X-Upload-Content-Type": meta["content_type"] or "application/octet-stream",
1186
  "Content-Security-Policy": "sandbox", "Cache-Control": "private, no-cache"})
1187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1188
  @app.delete("/v1/storage/{handle}/{path:path}")
1189
  async def storage_delete(handle: str, path: str, request: Request):
1190
  p = await authn(request)
 
31
  from .errors import ApiError, bad_request, forbidden
32
  from .presence import PRESENCE_FLUSH_SECONDS, Presence
33
  from . import transfer
34
+ from . import tasks as personal_tasks
35
  from .reservations import Reservations
36
+ from .auth import DOWNLOAD_TTL_SECONDS, DownloadLinks
37
 
38
 
39
  class NotInitialized(RuntimeError):
 
289
  # must not cause regular requests to fail when the writer is busy.
290
  logging.getLogger(__name__).exception("could not persist agent presence")
291
 
292
+ async def task_notice_loop(self) -> None:
293
+ """Deliver coalesced task changes through ordinary agent-owner DMs.
294
+
295
+ The pending batch and its message are committed together by the writer;
296
+ cancelling this task or restarting the server cannot duplicate delivery.
297
+ """
298
+ while True:
299
+ await asyncio.sleep(1)
300
+ if self.shutting_down:
301
+ return
302
+ try:
303
+ if not await self.db.read(personal_tasks.notice_due, time.time()):
304
+ continue
305
+ message = await self.db.write(personal_tasks.deliver_notice, time.time())
306
+ if message:
307
+ self.counters["posts"] += 1
308
+ self.notifier.notify(message["channel_id"])
309
+ self.notifier.notify(ANY_CHANNEL)
310
+ except Exception:
311
+ logging.getLogger(__name__).exception("could not deliver task update")
312
+
313
  def close(self) -> None:
314
  if getattr(self, "_closed", False):
315
  return
 
363
 
364
 
365
  def create_app(board: Board, dashboard: bool = True) -> FastAPI:
366
+ download_links = DownloadLinks() # process-local and bounded; restarts invalidate outstanding links
367
+
368
  @asynccontextmanager
369
  async def lifespan(app):
370
  board.notifier.loop = asyncio.get_running_loop()
371
  board.commit_lock = asyncio.Lock()
372
  board.presence.sample(time.time())
373
  task = asyncio.create_task(board.presence_loop())
374
+ task_notice_task = asyncio.create_task(board.task_notice_loop())
375
  try:
376
  yield
377
  finally:
378
  board.begin_shutdown()
379
  task.cancel()
380
+ task_notice_task.cancel()
381
  with suppress(asyncio.CancelledError):
382
  await task
383
+ with suppress(asyncio.CancelledError):
384
+ await task_notice_task
385
 
386
  app = FastAPI(title="msgboard", version="0.1.0", lifespan=lifespan,
387
  docs_url=None, redoc_url=None, openapi_url="/v1/openapi.json")
 
861
 
862
  # --------------------------------------------------------- messages
863
 
864
+ @app.get("/v1/tasks")
865
+ async def get_tasks(request: Request, archived: bool = False, sort: str = "manual", direction: str = "asc"):
866
+ p = await authn(request)
867
+ return await db.read(personal_tasks.list_items, p, archived, sort, direction)
868
+
869
+ @app.get("/v1/tasks/items/{item_id}")
870
+ async def get_task(item_id: int, request: Request):
871
+ p = await authn(request)
872
+ return await db.read(personal_tasks.get_item, p, item_id)
873
+
874
+ @app.put("/v1/tasks/items/by-key/{key}")
875
+ async def put_task(key: str, request: Request):
876
+ p = await authn(request)
877
+ payload = body_dict(await _json_body(request))
878
+ return await db.write(personal_tasks.put_item, p, key, payload, time.time())
879
+
880
+ @app.post("/v1/tasks/items/{item_id}/actions")
881
+ async def task_action(item_id: int, request: Request):
882
+ p = await authn(request)
883
+ key = request.headers.get("idempotency-key")
884
+ if not key or not store.CLIENT_ID.fullmatch(key):
885
+ raise bad_request("Idempotency-Key header is required and must match " + store.CLIENT_ID.pattern)
886
+ payload = body_dict(await _json_body(request, LIMITS.max_body_bytes * 2 + 64 * 1024))
887
+ result, message, replayed = await db.write(personal_tasks.action, p, item_id, payload, key, time.time())
888
+ if message:
889
+ board.counters["posts"] += 1
890
+ board.notifier.notify(message["channel_id"])
891
+ board.notifier.notify(ANY_CHANNEL)
892
+ return JSONResponse(result, headers={"Idempotent-Replayed": "true"} if replayed else None)
893
+
894
+ @app.post("/v1/tasks/items/{item_id}/move")
895
+ async def move_task(item_id: int, request: Request):
896
+ p = await authn(request)
897
+ return await db.write(personal_tasks.move_item, p, item_id,
898
+ body_dict(await _json_body(request)), time.time())
899
+
900
  @app.post("/v1/channels/{channel_id}/messages")
901
  async def post_message(channel_id: int, request: Request):
902
  p = await authn(request)
 
1104
  @app.get("/v1/attachments/{att_id}")
1105
  async def download(att_id: str, request: Request):
1106
  p = await authn(request)
1107
+ return await attachment_file(p, att_id)
1108
+
1109
+ async def attachment_file(p, att_id: str):
1110
  info = await db.read(store.get_attachment, p, att_id)
1111
  return FileResponse(
1112
  board.blobs.path_for(info["storage_key"]),
 
1215
  @app.get("/v1/storage/{handle}/{path:path}")
1216
  async def storage_get(handle: str, path: str, request: Request, info: bool = False):
1217
  p = await authn(request)
1218
+ return await storage_file(p, handle, path, info)
1219
+
1220
+ async def storage_file(p, handle: str, path: str, info: bool = False):
1221
  if path.endswith("/"): # a folder: list it
1222
  return await db.read(store.storage_list, p, handle, path)
1223
  meta, key = await db.read(store.storage_lookup, p, handle, path)
 
1256
  "X-Upload-Content-Type": meta["content_type"] or "application/octet-stream",
1257
  "Content-Security-Policy": "sandbox", "Cache-Control": "private, no-cache"})
1258
 
1259
+ async def download_file(p, file_id: str):
1260
+ if file_id.startswith("storage:"):
1261
+ parts = file_id[8:].split("/", 1)
1262
+ if len(parts) != 2 or not parts[1] or parts[1].endswith("/"):
1263
+ raise bad_request("choose a file, not a storage folder")
1264
+ return await storage_file(p, parts[0], parts[1])
1265
+ return await attachment_file(p, file_id)
1266
+
1267
+ @app.post("/v1/downloads")
1268
+ async def prepare_download(request: Request):
1269
+ p = await authn(request)
1270
+ body = body_dict(await _json_body(request, max_bytes=4096))
1271
+ file_id = body.get("file_id")
1272
+ if not isinstance(file_id, str) or not file_id or len(file_id) > 1024:
1273
+ raise bad_request("file_id must name an attachment or storage file")
1274
+ # Resolve permissions and fill/verify the storage cache before handing off. No file bytes in this JSON.
1275
+ response = await download_file(p, file_id)
1276
+ if not await anyio.to_thread.run_sync(Path(response.path).is_file):
1277
+ raise ApiError(404, "not_found", "this file is no longer available")
1278
+ key = download_links.issue(p.id, _bearer(request), file_id, response.headers["X-Checksum-Sha256"])
1279
+ return JSONResponse({"url": f"v1/downloads/{key}", "filename": response.filename,
1280
+ "expires_in": DOWNLOAD_TTL_SECONDS}, headers={"Cache-Control": "no-store"})
1281
+
1282
+ @app.api_route("/v1/downloads/{key}", methods=["GET", "HEAD"])
1283
+ async def browser_download(key: str):
1284
+ link = download_links.get(key)
1285
+ # A capability authorizes only its file/version. Recheck revocation, suspension, ownership and file ACLs.
1286
+ p = await db.read(store.authenticate, link.token, time.time())
1287
+ if p.id != link.principal_id:
1288
+ raise ApiError(404, "download_expired", "download link expired; click Download again")
1289
+ board.presence.seen(p, time.time())
1290
+ response = await download_file(p, link.file_id)
1291
+ if response.headers["X-Checksum-Sha256"] != link.sha256:
1292
+ raise ApiError(409, "download_changed", "this file changed; click Download again")
1293
+ response.headers.update({"Cache-Control": "private, no-store", "Referrer-Policy": "no-referrer",
1294
+ "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "sandbox"})
1295
+ return response
1296
+
1297
  @app.delete("/v1/storage/{handle}/{path:path}")
1298
  async def storage_delete(handle: str, path: str, request: Request):
1299
  p = await authn(request)
msgboard/space/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """msgboard on a Hugging Face Space.
2
+
3
+ - `deploy()` creates or updates a board Space and its private bucket (`hub.py`, needs the `hf` extra).
4
+ - `app.py` is what the Space runs; `accounts.py` adds invite links and "Sign in with Hugging Face".
5
+ - `Dockerfile` and `README.md` (the Space card) are uploaded with the package.
6
+ """
7
+
8
+ from .hub import Deployment, DeployError, deploy
9
+
10
+ __all__ = ["Deployment", "DeployError", "deploy"]
{hfspace → msgboard/space}/accounts.py RENAMED
@@ -1,12 +1,11 @@
1
  """Optional Hugging Face accounts for the msgboard Space.
2
 
3
- People join with invite links. Once on the board, anyone can link their Hugging
4
- Face account from their profile; after that "Sign in with Hugging Face" gives
5
- them a token on any device. HF sign-in never creates an account by itself.
 
6
  """
7
 
8
- from __future__ import annotations
9
-
10
  import hashlib
11
  import html
12
  import json
@@ -17,7 +16,7 @@ from urllib.parse import urlencode
17
 
18
  import httpx
19
  from fastapi import FastAPI, Request
20
- from fastapi.responses import HTMLResponse, RedirectResponse
21
 
22
  from msgboard import store
23
  from msgboard.errors import ApiError
@@ -53,6 +52,17 @@ def import_shared_invite(board: Board, code: str, operator_token: str):
53
  HF_API = os.environ.get("MSGBOARD_HF_API", "https://huggingface.co").rstrip("/")
54
 
55
 
 
 
 
 
 
 
 
 
 
 
 
56
  async def adopt_hf_picture(board: Board, principal_id: int, username: str) -> bool:
57
  """Use the Hugging Face profile picture as this account's picture, unless it already has one
58
  (an uploaded picture always wins). Best effort: any failure just keeps the generated pattern."""
@@ -97,17 +107,22 @@ def install(app: FastAPI, board: Board) -> None:
97
  host = os.environ.get("SPACE_HOST")
98
  enabled = bool(client_id and client_secret and host)
99
  redirect_uri = f"https://{host}/login/callback"
100
- pending: dict[str, tuple[float, str, int | None]] = {} # state -> (created, mode, principal to link)
 
 
101
 
102
- def start(mode: str, principal_id: int | None) -> str:
103
  now = time.time()
104
- for s, entry in list(pending.items()):
105
  if now - entry[0] > 600:
106
- del pending[s]
107
- if len(pending) > 5000:
108
  raise ApiError(429, "busy", "too many sign-ins in progress; try again shortly")
 
 
 
109
  state = secrets.token_urlsafe(24)
110
- pending[state] = (now, mode, principal_id)
111
  return f"{provider}/oauth/authorize?" + urlencode({
112
  "client_id": client_id, "redirect_uri": redirect_uri, "scope": "openid profile",
113
  "state": state, "response_type": "code"})
@@ -117,10 +132,31 @@ def install(app: FastAPI, board: Board) -> None:
117
  return {"hf_login": enabled}
118
 
119
  @app.get("/login")
120
- async def login():
121
  if not enabled:
122
  return _page("Hugging Face sign-in is not set up", "<p>Use an invite link or a token.</p>", 404)
123
- return RedirectResponse(start("signin", None))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
  @app.post("/v1/me/hf-link")
126
  async def link_start(request: Request):
@@ -137,6 +173,25 @@ def install(app: FastAPI, board: Board) -> None:
137
  await board.db.write(store.set_hf_username, p.id, None, time.time())
138
  return {"hf_username": None}
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  @app.get("/login/callback")
141
  async def callback(request: Request):
142
  entry = pending.pop(request.query_params.get("state", ""), None)
@@ -156,19 +211,24 @@ def install(app: FastAPI, board: Board) -> None:
156
  username = info.get("preferred_username")
157
  if not username:
158
  return _page("Sign-in failed", "<p>No username in the Hugging Face profile.</p>", 502)
159
- _, mode, principal_id = entry
160
  try:
161
  if mode == "link":
162
- await board.db.write(store.set_hf_username, principal_id, username, time.time())
163
- await adopt_hf_picture(board, principal_id, username)
164
  return _page("Hugging Face account linked",
165
  f"<p>You can now sign in as <b>@{html.escape(username)}</b> on any device.</p>"
166
  '<p><a href="/">Back to the board</a></p>')
167
- result = await board.db.write(store.sign_in_with_hf, username, time.time())
 
 
 
 
 
168
  if result.get("principal", {}).get("id"):
169
  await adopt_hf_picture(board, result["principal"]["id"], username)
170
  except ApiError as exc:
171
- if exc.status == 404:
172
  return _page("No account linked",
173
  f"<p>No board account is linked to <b>@{html.escape(username)}</b>.</p>"
174
  "<p>Join with an invite link first, then link your Hugging Face account from your "
 
1
  """Optional Hugging Face accounts for the msgboard Space.
2
 
3
+ People join with invite links: with a username they pick, or with "Join with
4
+ Hugging Face", which uses their HF username, name and picture and links the account.
5
+ Once linked (at join or later from their profile), "Sign in with Hugging Face"
6
+ gives them a token on any device. HF sign-in never creates an account without an invite.
7
  """
8
 
 
 
9
  import hashlib
10
  import html
11
  import json
 
16
 
17
  import httpx
18
  from fastapi import FastAPI, Request
19
+ from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
20
 
21
  from msgboard import store
22
  from msgboard.errors import ApiError
 
52
  HF_API = os.environ.get("MSGBOARD_HF_API", "https://huggingface.co").rstrip("/")
53
 
54
 
55
+ def join_with_hf(conn, code, name, display_name, username: str, now: float) -> dict:
56
+ """Redeem a people invite and link the HF account in one go; nothing is kept if either fails."""
57
+ row = store._find_invite(conn, code)
58
+ if row is not None and row["kind"] != "human":
59
+ raise ApiError(400, "invalid_request", "only invites for people can be used with Hugging Face")
60
+ result = store.join(conn, code, name, display_name, now)
61
+ store.set_hf_username(conn, result["principal"]["id"], username, now)
62
+ result["principal"]["hf_username"] = username
63
+ return result
64
+
65
+
66
  async def adopt_hf_picture(board: Board, principal_id: int, username: str) -> bool:
67
  """Use the Hugging Face profile picture as this account's picture, unless it already has one
68
  (an uploaded picture always wins). Best effort: any failure just keeps the generated pattern."""
 
107
  host = os.environ.get("SPACE_HOST")
108
  enabled = bool(client_id and client_secret and host)
109
  redirect_uri = f"https://{host}/login/callback"
110
+ pending: dict[str, tuple] = {} # state -> (created, mode, principal to link or invite code)
111
+ # ticket -> (created, invite code, HF username, HF name): an HF join whose username was taken here
112
+ tickets: dict[str, tuple[float, str, str, str | None]] = {}
113
 
114
+ def prune(entries: dict) -> None:
115
  now = time.time()
116
+ for s, entry in list(entries.items()):
117
  if now - entry[0] > 600:
118
+ del entries[s]
119
+ if len(entries) > 5000:
120
  raise ApiError(429, "busy", "too many sign-ins in progress; try again shortly")
121
+
122
+ def start(mode: str, target: int | str | None) -> str:
123
+ prune(pending)
124
  state = secrets.token_urlsafe(24)
125
+ pending[state] = (time.time(), mode, target)
126
  return f"{provider}/oauth/authorize?" + urlencode({
127
  "client_id": client_id, "redirect_uri": redirect_uri, "scope": "openid profile",
128
  "state": state, "response_type": "code"})
 
132
  return {"hf_login": enabled}
133
 
134
  @app.get("/login")
135
+ async def login(invite: str | None = None):
136
  if not enabled:
137
  return _page("Hugging Face sign-in is not set up", "<p>Use an invite link or a token.</p>", 404)
138
+ return RedirectResponse(start("join", invite) if invite else start("signin", None))
139
+
140
+ @app.post("/v1/join/hf")
141
+ async def join_after_name_taken(request: Request):
142
+ """Finish an HF join with a name the person picked, because their HF username was taken here."""
143
+ body = await request.json()
144
+ if not isinstance(body, dict):
145
+ raise ApiError(400, "invalid_request", "expected a JSON object")
146
+ ticket = body.get("ticket") if isinstance(body.get("ticket"), str) else ""
147
+ entry = tickets.pop(ticket, None)
148
+ if entry is None or time.time() - entry[0] > 600:
149
+ raise ApiError(410, "hf_join_expired", "the Hugging Face sign-in expired; join with Hugging Face again")
150
+ _, code, username, hf_name = entry
151
+ try:
152
+ result = await board.db.write(join_with_hf, code, body.get("name"), body.get("display_name") or hf_name,
153
+ username, time.time())
154
+ except ApiError as exc:
155
+ if exc.status in (400, 409) and exc.code != "hf_linked_elsewhere":
156
+ tickets[ticket] = entry # let them try another name
157
+ raise
158
+ await adopt_hf_picture(board, result["principal"]["id"], username)
159
+ return JSONResponse(result, status_code=201, headers={"Cache-Control": "no-store"})
160
 
161
  @app.post("/v1/me/hf-link")
162
  async def link_start(request: Request):
 
173
  await board.db.write(store.set_hf_username, p.id, None, time.time())
174
  return {"hf_username": None}
175
 
176
+ async def hf_join(code: str, username: str, hf_name: str | None) -> dict | str:
177
+ """Sign in if this HF account is linked already (the invite stays unused), else join with it.
178
+ Returns the join result, or where to send the person to pick another name."""
179
+ try:
180
+ return await board.db.write(store.sign_in_with_hf, username, time.time())
181
+ except ApiError as exc:
182
+ if exc.status != 404:
183
+ raise
184
+ display = hf_name.strip()[:128] if isinstance(hf_name, str) and hf_name.strip() else None
185
+ try:
186
+ return await board.db.write(join_with_hf, code, username, display, username, time.time())
187
+ except ApiError as exc:
188
+ if exc.code != "name_taken":
189
+ raise
190
+ prune(tickets)
191
+ ticket = secrets.token_urlsafe(24)
192
+ tickets[ticket] = (time.time(), code, username, display)
193
+ return "/?" + urlencode({"invite": code, "hf": ticket, "hf_user": username})
194
+
195
  @app.get("/login/callback")
196
  async def callback(request: Request):
197
  entry = pending.pop(request.query_params.get("state", ""), None)
 
211
  username = info.get("preferred_username")
212
  if not username:
213
  return _page("Sign-in failed", "<p>No username in the Hugging Face profile.</p>", 502)
214
+ _, mode, target = entry
215
  try:
216
  if mode == "link":
217
+ await board.db.write(store.set_hf_username, target, username, time.time())
218
+ await adopt_hf_picture(board, target, username)
219
  return _page("Hugging Face account linked",
220
  f"<p>You can now sign in as <b>@{html.escape(username)}</b> on any device.</p>"
221
  '<p><a href="/">Back to the board</a></p>')
222
+ if mode == "join":
223
+ result = await hf_join(target, username, info.get("name"))
224
+ if isinstance(result, str):
225
+ return RedirectResponse(result, status_code=303)
226
+ else:
227
+ result = await board.db.write(store.sign_in_with_hf, username, time.time())
228
  if result.get("principal", {}).get("id"):
229
  await adopt_hf_picture(board, result["principal"]["id"], username)
230
  except ApiError as exc:
231
+ if exc.status == 404 and mode != "join":
232
  return _page("No account linked",
233
  f"<p>No board account is linked to <b>@{html.escape(username)}</b>.</p>"
234
  "<p>Join with an invite link first, then link your Hugging Face account from your "
{hfspace → msgboard/space}/app.py RENAMED
@@ -5,7 +5,10 @@ Environment (Space secrets/variables):
5
  HF_TOKEN secret; write access to the replica bucket
6
  MSGBOARD_REPLICA hf://buckets/<ns>/<bucket>[/<prefix>]
7
  MSGBOARD_SNAPSHOT_INTERVAL seconds between snapshots (default 15)
8
- MSGBOARD_DEMO_BOTS "1" to run a few slow demo agents
 
 
 
9
 
10
  Restarts overlap on Spaces: the new container starts before the old one gets
11
  SIGTERM. So this app opens its port at once but answers 503 (Retry-After) until
@@ -13,8 +16,6 @@ the old container has pushed its final snapshot and released the lease. Only
13
  then does it restore and serve. Clients retry with the same request IDs.
14
  """
15
 
16
- from __future__ import annotations
17
-
18
  import asyncio
19
  import hashlib
20
  import json
@@ -37,7 +38,7 @@ logging.getLogger("httpx2").setLevel(logging.WARNING)
37
  log = logging.getLogger("msgboard.space")
38
 
39
  DATA_DIR = Path(os.environ.get("MSGBOARD_DATA_DIR", "/home/user/board-data"))
40
- PAGE = Path(__file__).resolve().parent / "dashboard.html"
41
 
42
 
43
  def ensure_board(data_dir: Path, operator_token: str) -> None:
@@ -102,7 +103,7 @@ class Dispatcher:
102
  try:
103
  board = await asyncio.to_thread(self._prepare)
104
  app = create_app(board)
105
- from accounts import adopt_hf_pictures, import_shared_invite, install as install_accounts
106
 
107
  install_accounts(app, board)
108
  self._inner_lifespan = app.router.lifespan_context(app)
@@ -115,9 +116,13 @@ class Dispatcher:
115
  # linked accounts without a picture get their Hugging Face one (in the background, best effort)
116
  self._pictures = asyncio.get_running_loop().create_task(adopt_hf_pictures(board))
117
  if os.environ.get("MSGBOARD_DEMO_BOTS") == "1":
118
- from demo_bots import start_bots
119
-
120
- start_bots(f"http://127.0.0.1:{os.environ.get('PORT', '7860')}", os.environ["MSGBOARD_OPERATOR_TOKEN"].strip())
 
 
 
 
121
  except Exception as exc:
122
  self.error = f"{type(exc).__name__}: {exc}"
123
  log.exception("board failed to start")
 
5
  HF_TOKEN secret; write access to the replica bucket
6
  MSGBOARD_REPLICA hf://buckets/<ns>/<bucket>[/<prefix>]
7
  MSGBOARD_SNAPSHOT_INTERVAL seconds between snapshots (default 15)
8
+ MSGBOARD_INVITE_CODE optional secret; kept working as a standing member invite link
9
+ MSGBOARD_DEMO_BOTS "1" to run the demo's bots (hfspace/demo_bots.py, uploaded by hfspace/deploy.py)
10
+
11
+ The Space runs `python -m msgboard.space.app`; msgboard.space.deploy() uploads this package to it.
12
 
13
  Restarts overlap on Spaces: the new container starts before the old one gets
14
  SIGTERM. So this app opens its port at once but answers 503 (Retry-After) until
 
16
  then does it restore and serve. Clients retry with the same request IDs.
17
  """
18
 
 
 
19
  import asyncio
20
  import hashlib
21
  import json
 
38
  log = logging.getLogger("msgboard.space")
39
 
40
  DATA_DIR = Path(os.environ.get("MSGBOARD_DATA_DIR", "/home/user/board-data"))
41
+ PAGE = Path(__file__).resolve().parents[1] / "dashboard.html"
42
 
43
 
44
  def ensure_board(data_dir: Path, operator_token: str) -> None:
 
103
  try:
104
  board = await asyncio.to_thread(self._prepare)
105
  app = create_app(board)
106
+ from msgboard.space.accounts import adopt_hf_pictures, import_shared_invite, install as install_accounts
107
 
108
  install_accounts(app, board)
109
  self._inner_lifespan = app.router.lifespan_context(app)
 
116
  # linked accounts without a picture get their Hugging Face one (in the background, best effort)
117
  self._pictures = asyncio.get_running_loop().create_task(adopt_hf_pictures(board))
118
  if os.environ.get("MSGBOARD_DEMO_BOTS") == "1":
119
+ try: # not part of the package: only the demo Space has it, next to the package
120
+ from demo_bots import start_bots
121
+ except ImportError:
122
+ log.warning("MSGBOARD_DEMO_BOTS=1 but demo_bots.py is not in the Space; no bots")
123
+ else:
124
+ start_bots(f"http://127.0.0.1:{os.environ.get('PORT', '7860')}",
125
+ os.environ["MSGBOARD_OPERATOR_TOKEN"].strip())
126
  except Exception as exc:
127
  self.error = f"{type(exc).__name__}: {exc}"
128
  log.exception("board failed to start")
msgboard/space/hub.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deploy a board to a Hugging Face Space: `msgboard.space.deploy()`. Needs the `hf` extra.
2
+
3
+ The Space runs `msgboard.space.app` from the files of the msgboard install that calls deploy(),
4
+ keeps its board in SQLite on its own disk and pushes snapshots to a private bucket through the
5
+ Hub API (DEPLOY_SPACES.md explains why it is not a bucket mount).
6
+ """
7
+
8
+ import json
9
+ import logging
10
+ import re
11
+ from dataclasses import dataclass, field
12
+ from importlib import metadata
13
+ from pathlib import Path
14
+
15
+ from .. import auth
16
+
17
+ log = logging.getLogger("msgboard.space")
18
+
19
+ TAG = "msgboard" # deploy() puts it in the Space card, and reuses only Spaces that have it
20
+ SNAPSHOT_INTERVAL = "15" # MSGBOARD_SNAPSHOT_INTERVAL, in seconds
21
+ _HERE = Path(__file__).resolve().parent
22
+ _PACKAGE = _HERE.parent # the installed msgboard package, uploaded as-is
23
+
24
+
25
+ class DeployError(Exception):
26
+ """deploy() refused, before changing anything on the Hub."""
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Deployment:
31
+ """What deploy() set up."""
32
+
33
+ space_id: str # "namespace/name"; a bare name gets the logged-in account
34
+ url: str # the board's base URL, https://<namespace>-<name>.hf.space
35
+ bucket_id: str # "namespace/name" of the private bucket that holds the snapshots
36
+ created: bool # True if this call created the Space, False if it reused one
37
+ private: bool # the Space's visibility; a reused Space keeps its own
38
+ commit: str # the Space repo commit that holds this deployment
39
+ # The admin token deploy() made when called without operator_token (None if the caller passed one).
40
+ # It's left out of repr() so printing or logging a Deployment never shows it.
41
+ operator_token: str | None = field(default=None, repr=False)
42
+
43
+
44
+ def _resolve_space_id(space_id: str, *, token: str | None = None) -> str:
45
+ """Return `space_id` as "namespace/name". A bare name goes in the logged-in account, as in Trackio."""
46
+ return _Names(_hf_api(_hf_token(token))).full(space_id)
47
+
48
+
49
+ def deploy(space_id: str, *, token: str | None = None, operator_token: str | None = None,
50
+ bucket_id: str | None = None, private: bool | None = None, title: str | None = None) -> Deployment:
51
+ """Create or update the board Space `space_id` and return a `Deployment`.
52
+
53
+ `space_id` is "namespace/name" or a bare name for the logged-in account. A missing Space is
54
+ created (Docker SDK, CPU Basic) with `private` as its visibility (None: the namespace's default).
55
+ An existing Space is reused, and keeps its visibility, only if its card has the `msgboard` tag
56
+ that deploy() puts there. Any other Space raises DeployError without being changed, including one
57
+ left by a first deploy() that failed before its upload: delete that one and deploy again.
58
+
59
+ A reused board keeps its bucket, the one its MSGBOARD_REPLICA names. A new board's is `bucket_id`,
60
+ else "<space_id>-bucket", or -2, -3 ... if that exists, so it never restores the snapshots a
61
+ deleted Space left behind. The bucket is always private, whatever `private` says: it holds every
62
+ message, token hash and invite. An existing public bucket is refused. So is anything that would
63
+ restart a board against an empty bucket: a `bucket_id` other than the board's, a MSGBOARD_REPLICA
64
+ that isn't the hf://buckets/<namespace>/<bucket> deploy() set, or a bucket that is missing
65
+ (deleted or not visible to this token). All checks run before the first write.
66
+
67
+ The Space gets the secrets MSGBOARD_OPERATOR_TOKEN (`operator_token`, from
68
+ `msgboard.auth.new_token()`; the app makes it the admin credential on every boot) and HF_TOKEN
69
+ (`token`, default: the logged-in token), and the variables MSGBOARD_REPLICA=hf://buckets/<bucket>
70
+ and MSGBOARD_SNAPSHOT_INTERVAL=15. That one HF token makes deploy()'s Hub calls and is what the
71
+ Space writes the bucket with, so it needs write access to both the Space and its bucket.
72
+
73
+ Without `operator_token`, deploy() makes one with new_token() and returns it as
74
+ `Deployment.operator_token` (None when you pass one). On a reused board that rotates the admin
75
+ token: the new one replaces the secret, and the old one stops working once the Space restarts.
76
+ So omit it only if you'll keep the returned one; a deploy() that raises returns no token, and the
77
+ next call makes another.
78
+
79
+ The Space's files become the installed msgboard package, LICENSE, requirements.txt, the Dockerfile
80
+ and the card, whose title is `title` (default: the Space's name); anything else in the Space repo
81
+ is deleted.
82
+
83
+ The Space then builds or restarts, which takes a few minutes: wait with `Client.wait_ready()`.
84
+ A reused Space keeps answering with its previous container for a while; wait_ready() with the
85
+ operator token waits until the board accepts that token. A restart or rebuild can still follow
86
+ after wait_ready() returns: if `operator_token` is the one the Space already has, the old healthy
87
+ container satisfies wait_ready() before the pending restart. Keep retrying through 503 after it.
88
+ """
89
+ from huggingface_hub import CommitOperationAdd, CommitOperationDelete
90
+ from huggingface_hub.errors import RepositoryNotFoundError
91
+
92
+ generated = operator_token is None
93
+ if generated:
94
+ operator_token = auth.new_token()[1]
95
+ elif auth.parse_token(operator_token) is None:
96
+ raise DeployError("operator_token is not a board token; make one with msgboard.auth.new_token()")
97
+ token = _hf_token(token)
98
+ api = _hf_api(token)
99
+ names = _Names(api)
100
+ space_id = names.full(space_id)
101
+ bucket_id = names.full(bucket_id) if bucket_id else None
102
+ try:
103
+ info = api.space_info(space_id)
104
+ except RepositoryNotFoundError:
105
+ info = None
106
+ variables: dict[str, str] = {}
107
+ if info is not None:
108
+ if TAG not in (info.tags or []):
109
+ raise DeployError(f"{space_id} exists but is not a msgboard board (no {TAG!r} tag in its card), so it "
110
+ "was left alone; choose another Space ID")
111
+ # A restart boots a reused board from its bucket, so never let it come back against an empty one.
112
+ variables = {k: v.value for k, v in api.get_space_variables(space_id).items()}
113
+ replica = variables.get("MSGBOARD_REPLICA")
114
+ current = _bucket_of(replica)
115
+ if current is None:
116
+ raise DeployError(f"{space_id} has MSGBOARD_REPLICA={replica!r}, not hf://buckets/<namespace>/<bucket> "
117
+ "as deploy() sets it; set it back to the bucket that holds the board's snapshots")
118
+ if bucket_id and bucket_id != current:
119
+ raise DeployError(f"{space_id} keeps its board in bucket {current}, not {bucket_id}; "
120
+ "leave bucket_id out to keep using it")
121
+ bucket_id = current
122
+ bucket_id = bucket_id or _free_bucket_id(api, f"{space_id}-bucket")
123
+ bucket = _bucket_info(api, bucket_id)
124
+ if bucket is None and info is not None:
125
+ raise DeployError(f"{space_id} is a deployed board, and its bucket {bucket_id} was not found (deleted, "
126
+ "or not visible to this token); refusing to restart the board against an empty bucket")
127
+ if bucket is not None and not bucket.private:
128
+ raise DeployError(f"bucket {bucket_id} is public; a board's bucket must be private, because its "
129
+ "snapshots hold every message, token hash and invite")
130
+ dist = _distribution()
131
+ files = _space_files(space_id, dist, title)
132
+
133
+ secrets = {"MSGBOARD_OPERATOR_TOKEN": operator_token, "HF_TOKEN": token}
134
+ wanted = {"MSGBOARD_REPLICA": f"hf://buckets/{bucket_id}", "MSGBOARD_SNAPSHOT_INTERVAL": SNAPSHOT_INTERVAL}
135
+ created = info is None
136
+ if created: # secrets and variables come with the Space; nothing runs before the first commit
137
+ api.create_repo(space_id, repo_type="space", private=private, space_sdk="docker",
138
+ space_hardware="cpu-basic",
139
+ space_secrets=[{"key": k, "value": v} for k, v in secrets.items()],
140
+ space_variables=[{"key": k, "value": v} for k, v in wanted.items()])
141
+ if bucket is None:
142
+ api.create_bucket(bucket_id, private=True, exist_ok=True)
143
+ if not created: # each of these restarts the board
144
+ for key, value in secrets.items():
145
+ api.add_space_secret(space_id, key, value)
146
+ for key, value in wanted.items():
147
+ if variables.get(key) != value:
148
+ api.add_space_variable(space_id, key, value)
149
+ stale = set(api.list_repo_files(space_id, repo_type="space")) - set(files) - {".gitattributes"}
150
+ operations = [CommitOperationAdd(path, data) for path, data in files.items()]
151
+ operations += [CommitOperationDelete(path) for path in sorted(stale)]
152
+ commit = api.create_commit(space_id, repo_type="space", operations=operations,
153
+ commit_message=f"Deploy msgboard {dist.version}")
154
+ info = api.space_info(space_id)
155
+ return Deployment(space_id=space_id, url=(info.host or f"https://{info.subdomain}.hf.space").rstrip("/"),
156
+ bucket_id=bucket_id, created=created, private=bool(info.private), commit=commit.oid,
157
+ operator_token=operator_token if generated else None)
158
+
159
+
160
+ def _hf_token(token: str | None) -> str:
161
+ from huggingface_hub import get_token
162
+
163
+ token = token or get_token()
164
+ if not token:
165
+ raise DeployError("no Hugging Face token: log in with `hf auth login` or set HF_TOKEN")
166
+ return token
167
+
168
+
169
+ def _hf_api(token: str):
170
+ from huggingface_hub import HfApi
171
+
172
+ return HfApi(token=token)
173
+
174
+
175
+ class _Names:
176
+ """Fills in the logged-in account for bare repo names, asking the Hub at most once."""
177
+
178
+ def __init__(self, api):
179
+ self.api = api
180
+ self._namespace = None
181
+
182
+ def full(self, repo_id: str) -> str:
183
+ from huggingface_hub.utils import validate_repo_id
184
+
185
+ if "/" not in repo_id:
186
+ self._namespace = self._namespace or self.api.whoami()["name"]
187
+ repo_id = f"{self._namespace}/{repo_id}"
188
+ validate_repo_id(repo_id)
189
+ return repo_id
190
+
191
+
192
+ def _bucket_of(replica: str | None) -> str | None:
193
+ """The bucket ID in the MSGBOARD_REPLICA deploy() sets, `hf://buckets/<namespace>/<bucket>`."""
194
+ match = re.fullmatch(r"hf://buckets/([^/]+/[^/]+)", replica or "")
195
+ return match[1] if match else None
196
+
197
+
198
+ def _bucket_info(api, bucket_id: str):
199
+ from huggingface_hub.errors import BucketNotFoundError
200
+
201
+ try:
202
+ return api.bucket_info(bucket_id)
203
+ except BucketNotFoundError:
204
+ return None
205
+
206
+
207
+ def _free_bucket_id(api, preferred: str) -> str:
208
+ """`preferred`, or the first of preferred-2, -3 ... that doesn't exist, as Trackio's resolve_auto_bucket_id."""
209
+ candidate, n = preferred, 1
210
+ while _bucket_info(api, candidate) is not None:
211
+ n += 1
212
+ candidate = f"{preferred}-{n}"
213
+ if candidate != preferred:
214
+ log.info("bucket %s already exists; using %s", preferred, candidate)
215
+ return candidate
216
+
217
+
218
+ def _distribution():
219
+ try:
220
+ return metadata.distribution("msgboard")
221
+ except metadata.PackageNotFoundError:
222
+ raise DeployError("msgboard is not installed; deploy() uploads the installed package "
223
+ "(pip install 'msgboard[hf]', or pip install -e '.[hf]' in a checkout)") from None
224
+
225
+
226
+ def _space_files(space_id: str, dist, title: str | None = None) -> dict[str, bytes]:
227
+ """The Space repo's files by path: card, Dockerfile, requirements.txt, LICENSE and the package."""
228
+ # A JSON string is a quoted YAML string, so `true`, `null`, `2024`, ':' or '#' stay the title as written.
229
+ # ensure_ascii=False keeps an emoji whole (YAML reads JSON's surrogate pair as two lone halves). YAML
230
+ # reads U+0085/U+2028/U+2029 as line breaks and refuses DEL and C1 controls, so those stay escaped.
231
+ title = re.sub(r"[\x7f-\x9f\u2028\u2029]", lambda m: f"\\u{ord(m[0]):04x}",
232
+ json.dumps(title or space_id.split("/")[1], ensure_ascii=False))
233
+ card = (_HERE / "README.md").read_text().replace("title: msgboard\n", f"title: {title}\n", 1)
234
+ files = {"README.md": card.encode(), "Dockerfile": (_HERE / "Dockerfile").read_bytes(),
235
+ "requirements.txt": _requirements(dist).encode(), "LICENSE": _license(dist)}
236
+ # An allowlist, so stray files in an editable install's src/msgboard (a test board's token, say)
237
+ # never reach a public Space. Keep it in step with [tool.setuptools.package-data] in pyproject.toml.
238
+ for path in sorted(_PACKAGE.rglob("*")):
239
+ if (path.suffix in (".py", ".html") and "__pycache__" not in path.parts and path.is_file()
240
+ and path.resolve().is_relative_to(_PACKAGE)): # no symlinks out of the package
241
+ files["msgboard/" + path.relative_to(_PACKAGE).as_posix()] = path.read_bytes()
242
+ return files
243
+
244
+
245
+ def _requirements(dist) -> str:
246
+ """The install's own dependencies plus the hf extra (bucket snapshots); other extras are left out."""
247
+ lines = []
248
+ for req in dist.requires or []:
249
+ spec, _, marker = req.partition(";")
250
+ marker = marker.strip()
251
+ if not marker or re.fullmatch(r"""extra\s*==\s*["']hf["']""", marker):
252
+ lines.append(spec.strip())
253
+ elif "extra" not in marker:
254
+ lines.append(req.strip())
255
+ return "\n".join(lines) + "\n"
256
+
257
+
258
+ def _license(dist) -> bytes:
259
+ """LICENSE from the install's dist-info, in licenses/ as setuptools 77+ (PEP 639) puts it."""
260
+ for name in dist.metadata.get_all("License-File") or []:
261
+ text = dist.read_text(f"licenses/{name}")
262
+ if text:
263
+ return text.encode()
264
+ raise DeployError("the installed msgboard has no LICENSE in its metadata; reinstall it with setuptools>=77")
{src/msgboard → msgboard}/store.py RENAMED
File without changes
msgboard/tasks.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Personal task operations, run on the existing reader or single writer.
2
+
3
+ Answers and notifications are ordinary messages. Functions do not open or commit
4
+ transactions: the server runs each mutation in one Database.write transaction.
5
+ Live references become NULL on deletion; original IDs retain destination intent.
6
+ """
7
+
8
+ from dataclasses import replace
9
+ from contextlib import contextmanager
10
+ import hashlib
11
+ import json
12
+ import time
13
+
14
+ from . import auth, store
15
+ from .errors import ApiError, bad_request, conflict, forbidden, not_found, unauthorized
16
+
17
+
18
+ NOTICE_DELAY = 5.0
19
+ MAX_SOURCES = 20
20
+ MAX_OPTIONS = 20
21
+ MAX_BLOCKS = 40
22
+
23
+
24
+ def _digest(value):
25
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"),
26
+ ensure_ascii=False).encode()).hexdigest()
27
+
28
+
29
+ def _integer(value, name, *, optional=False):
30
+ if optional and value is None:
31
+ return None
32
+ if not isinstance(value, int) or isinstance(value, bool) or value < 1:
33
+ raise bad_request(f"{name} must be a positive integer")
34
+ return value
35
+
36
+
37
+ def _object(payload, allowed):
38
+ if not isinstance(payload, dict) or set(payload) - allowed:
39
+ raise bad_request("unsupported task fields or invalid request body")
40
+
41
+
42
+ def _text(value, name, limit, *, empty=False):
43
+ if not isinstance(value, str) or len(value) > limit or (not empty and not value.strip()):
44
+ raise bad_request(f"{name} must be {'at most' if empty else 'nonempty and at most'} {limit} characters")
45
+ return value
46
+
47
+
48
+ def _current(conn, principal_id):
49
+ row = conn.execute("SELECT * FROM principals WHERE id = ?", (principal_id,)).fetchone()
50
+ if row is None or row["disabled"]:
51
+ raise unauthorized("identity is no longer active")
52
+ p = store._principal_obj(row)
53
+ if not p.is_human:
54
+ owner = conn.execute("SELECT * FROM principals WHERE id = ?", (p.owner_id,)).fetchone()
55
+ # Ownership is normalized to a person by the existing identity migration.
56
+ # Refuse malformed chains rather than allowing an agent to own a task.
57
+ if (owner is None or owner["identity_type"] != "user" or owner["disabled"]
58
+ or owner["role"] not in auth.owner_roles_for(p.role)):
59
+ raise unauthorized("agent no longer has an active human owner")
60
+ return p
61
+
62
+
63
+ def _principal(conn, p, now, *, write=False):
64
+ cred = conn.execute("SELECT * FROM credentials WHERE id = ? AND principal_id = ?",
65
+ (p.credential_id, p.id)).fetchone()
66
+ if (cred is None or cred["revoked_at"] is not None
67
+ or (cred["expires_at"] is not None and cred["expires_at"] <= now)):
68
+ raise unauthorized("credential is no longer active")
69
+ fresh = replace(_current(conn, p.id), credential_id=p.credential_id)
70
+ if write and not fresh.is_human and not fresh.may_post:
71
+ raise forbidden("read-only agents cannot change tasks")
72
+ return fresh
73
+
74
+
75
+ def _owner(p):
76
+ return p.id if p.is_human else p.owner_id
77
+
78
+
79
+ def _channel_visible(conn, p, channel_id):
80
+ ch = conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone()
81
+ return ch is not None and store.can_see(conn, p, ch)
82
+
83
+
84
+ def _sources(conn, item_id):
85
+ return conn.execute("SELECT * FROM task_sources WHERE item_id = ? ORDER BY position", (item_id,)).fetchall()
86
+
87
+
88
+ def _visible(conn, p, row):
89
+ if row["owner_id"] != _owner(p):
90
+ return False
91
+ if row["channel_id"] is not None and not _channel_visible(conn, p, row["channel_id"]):
92
+ return False
93
+ if not p.is_human and row["original_channel_id"] is not None and row["channel_id"] is None:
94
+ return False
95
+ for source in _sources(conn, row["id"]):
96
+ if source["channel_id"] is not None and not _channel_visible(conn, p, source["channel_id"]):
97
+ return False
98
+ # Only the owner retains a card with deleted evidence, to close it safely.
99
+ if not p.is_human and (source["message_id"] is None or source["channel_id"] is None):
100
+ return False
101
+ return True
102
+
103
+
104
+ def _row(conn, p, item_id):
105
+ _integer(item_id, "item id")
106
+ row = conn.execute("SELECT * FROM task_items WHERE id = ? AND owner_id = ?",
107
+ (item_id, _owner(p))).fetchone()
108
+ if row is None or not _visible(conn, p, row):
109
+ raise not_found("task not found")
110
+ return row
111
+
112
+
113
+ def _message(conn, p, message_id):
114
+ if message_id is None:
115
+ return None
116
+ row = conn.execute(store.MESSAGE_SELECT + " WHERE m.id = ?", (message_id,)).fetchone()
117
+ if row is None or not _channel_visible(conn, p, row["channel_id"]):
118
+ return None
119
+ out = store._message_json(row)
120
+ store._attach_mentions(conn, [out])
121
+ store._attach_reactions(conn, [out], p.id)
122
+ return out
123
+
124
+
125
+ def _item(conn, p, row):
126
+ refs = []
127
+ for source in _sources(conn, row["id"]):
128
+ message = _message(conn, p, source["message_id"])
129
+ refs.append({"message_id": source["original_message_id"],
130
+ "channel_id": source["original_channel_id"], "message": message,
131
+ "unavailable": message is None})
132
+ channel = None
133
+ if row["channel_id"] is not None:
134
+ ch = conn.execute("SELECT id, name, kind, archived FROM channels WHERE id = ?",
135
+ (row["channel_id"],)).fetchone()
136
+ if ch is not None:
137
+ channel = dict(ch)
138
+ specified = row["original_channel_id"] is not None
139
+ unavailable = specified and (row["channel_id"] is None
140
+ or (row["original_anchor_id"] is not None and row["anchor_id"] is None))
141
+ if specified and channel is not None and not store.can_post(conn, p, channel):
142
+ unavailable = True
143
+ if not specified:
144
+ try:
145
+ agent = _current(conn, row["agent_id"])
146
+ unavailable = agent.is_human or agent.owner_id != row["owner_id"] or not agent.may_post
147
+ except ApiError:
148
+ unavailable = True
149
+ out = {"id": row["id"], "key": row["item_key"], "title": row["title"],
150
+ "description": row["description"], "blocks": json.loads(row["blocks"]),
151
+ "agent": store._brief(conn, row["agent_id"]),
152
+ "channel_id": row["original_channel_id"], "anchor_id": row["original_anchor_id"],
153
+ "channel": channel, "sources": refs, "options": json.loads(row["options"]),
154
+ "multiple": bool(row["multiple"]), "version": row["version"], "state": row["state"],
155
+ "closed_reason": row["closed_reason"], "closed_at": row["closed_at"],
156
+ "answer": _message(conn, p, row["answer_id"]),
157
+ "answer_message_id": row["original_answer_id"],
158
+ "created_at": row["created_at"], "updated_at": row["updated_at"], "rank": row["rank"],
159
+ "destination_unavailable": bool(unavailable),
160
+ "destination": {"kind": "thread" if row["original_anchor_id"] is not None else "channel" if specified else "dm",
161
+ "channel_id": row["original_channel_id"], "anchor_id": row["original_anchor_id"],
162
+ "agent_id": row["agent_id"]}}
163
+ return out
164
+
165
+
166
+ def _order_version(conn, owner_id):
167
+ row = conn.execute("SELECT version FROM task_orders WHERE owner_id = ?", (owner_id,)).fetchone()
168
+ return row[0] if row is not None else 0
169
+
170
+
171
+ def _bump_order(conn, owner_id):
172
+ conn.execute("""INSERT INTO task_orders(owner_id, version) VALUES (?, 1)
173
+ ON CONFLICT(owner_id) DO UPDATE SET version = version + 1""", (owner_id,))
174
+
175
+
176
+ def _listing(conn, p, include_archived, sort, direction):
177
+ if not isinstance(include_archived, bool):
178
+ raise bad_request("include_archived must be a boolean")
179
+ if sort not in ("manual", "latest", "channel", "agent") or direction not in ("asc", "desc"):
180
+ raise bad_request("sort must be manual/latest/channel/agent; direction must be asc/desc")
181
+ rows = conn.execute("SELECT * FROM task_items WHERE owner_id = ? ORDER BY rank, id", (_owner(p),)).fetchall()
182
+ visible = [r for r in rows if _visible(conn, p, r)]
183
+ counts = {"open": sum(r["state"] == "open" for r in visible),
184
+ "archived": sum(r["state"] == "closed" for r in visible)}
185
+ items = [_item(conn, p, r) for r in visible if include_archived or r["state"] == "open"]
186
+ if sort == "manual":
187
+ key = lambda i: (i["rank"], i["id"])
188
+ elif sort == "latest":
189
+ key = lambda i: (i["created_at"], i["id"])
190
+ elif sort == "channel":
191
+ key = lambda i: ((i["channel"] or {}).get("name", "").casefold(), i["rank"], i["id"])
192
+ else:
193
+ key = lambda i: ((i["agent"] or {}).get("display_name") or (i["agent"] or {}).get("external_id", ""),
194
+ i["rank"], i["id"])
195
+ items.sort(key=key, reverse=direction == "desc")
196
+ return {"items": items, "counts": counts, "order_version": _order_version(conn, _owner(p))}
197
+
198
+
199
+ @contextmanager
200
+ def _snapshot(conn):
201
+ # SQLite autocommit would otherwise pair an old title/options row with a
202
+ # newer set of public source references during an agent's concurrent edit.
203
+ # Visibility and the content it protects must use the same read snapshot.
204
+ own = not conn.in_transaction
205
+ if own:
206
+ conn.execute("BEGIN")
207
+ try:
208
+ yield
209
+ finally:
210
+ if own:
211
+ conn.execute("ROLLBACK")
212
+
213
+
214
+ def list_items(conn, p, include_archived=False, sort="manual", direction="asc"):
215
+ with _snapshot(conn):
216
+ return _listing(conn, _principal(conn, p, time.time()), include_archived, sort, direction)
217
+
218
+
219
+ def get_item(conn, p, item_id):
220
+ with _snapshot(conn):
221
+ p = _principal(conn, p, time.time())
222
+ return _item(conn, p, _row(conn, p, item_id))
223
+
224
+
225
+ def _notice(conn, owner_id, agent_id, now):
226
+ pending = conn.execute("SELECT id FROM task_notices WHERE owner_id = ? AND agent_id = ? AND state = 'pending'",
227
+ (owner_id, agent_id)).fetchone()
228
+ if pending is None:
229
+ conn.execute("INSERT INTO task_notices(owner_id, agent_id, due_at, updated_at) VALUES (?, ?, ?, ?)",
230
+ (owner_id, agent_id, now + NOTICE_DELAY, now))
231
+ else:
232
+ conn.execute("UPDATE task_notices SET changes = changes + 1, updated_at = ? WHERE id = ?", (now, pending[0]))
233
+
234
+
235
+ def _content(conn, p, payload):
236
+ _object(payload, {"title", "description", "blocks", "channel_id", "anchor_id", "sources", "options", "multiple", "base_version"})
237
+ if "base_version" in payload:
238
+ _integer(payload["base_version"], "base_version")
239
+ title = _text(payload.get("title"), "title", 240)
240
+ description = _text(payload.get("description", ""), "description", 16000, empty=True)
241
+ channel_id = _integer(payload.get("channel_id"), "channel_id", optional=True)
242
+ anchor_id = _integer(payload.get("anchor_id"), "anchor_id", optional=True)
243
+ owner = _current(conn, p.owner_id)
244
+ if anchor_id is not None:
245
+ anchor = conn.execute("SELECT channel_id, thread_id FROM messages WHERE id = ?", (anchor_id,)).fetchone()
246
+ if anchor is None:
247
+ raise bad_request("anchor_id must reference an existing message")
248
+ if channel_id is not None and channel_id != anchor["channel_id"]:
249
+ raise bad_request("anchor_id must belong to channel_id")
250
+ channel_id = anchor["channel_id"]
251
+ # Keep the exact source anchor. Normal post_message resolves its root.
252
+ if channel_id is not None:
253
+ store.channel_for(conn, p, channel_id)
254
+ store.channel_for(conn, owner, channel_id)
255
+ sources = payload.get("sources", [])
256
+ if not isinstance(sources, list) or len(sources) > MAX_SOURCES:
257
+ raise bad_request(f"sources must be at most {MAX_SOURCES} message IDs")
258
+ sources = list(dict.fromkeys(_integer(s, "source message id") for s in sources))
259
+ blocks = payload.get("blocks", [])
260
+ if not isinstance(blocks, list) or len(blocks) > MAX_BLOCKS:
261
+ raise bad_request(f"blocks must be a list of at most {MAX_BLOCKS} text or quote blocks")
262
+ ordered, text_length = [], len(description)
263
+ for block in blocks:
264
+ if not isinstance(block, dict):
265
+ raise bad_request("blocks must contain text or quote objects")
266
+ if block.get("type") == "text":
267
+ _object(block, {"type", "text"})
268
+ text = _text(block.get("text"), "block text", 16000, empty=True)
269
+ text_length += len(text)
270
+ ordered.append({"type": "text", "text": text})
271
+ elif block.get("type") == "quote":
272
+ _object(block, {"type", "message_id"})
273
+ message_id = _integer(block.get("message_id"), "quote message_id")
274
+ ordered.append({"type": "quote", "message_id": message_id})
275
+ if message_id not in sources:
276
+ sources.append(message_id)
277
+ else:
278
+ raise bad_request("block type must be text or quote")
279
+ if text_length > 16000:
280
+ raise bad_request("description and text blocks together must be at most 16000 characters")
281
+ if len(sources) > MAX_SOURCES:
282
+ raise bad_request(f"sources and quotes must reference at most {MAX_SOURCES} unique messages")
283
+ refs = []
284
+ for message_id in sources:
285
+ source = conn.execute("SELECT channel_id FROM messages WHERE id = ?", (message_id,)).fetchone()
286
+ if source is None:
287
+ raise bad_request("sources must reference existing messages")
288
+ store.channel_for(conn, p, source["channel_id"])
289
+ store.channel_for(conn, owner, source["channel_id"])
290
+ refs.append((message_id, source["channel_id"]))
291
+ options = payload.get("options", [])
292
+ if not isinstance(options, list) or len(options) > MAX_OPTIONS:
293
+ raise bad_request(f"options must be at most {MAX_OPTIONS} choices")
294
+ choices, seen = [], set()
295
+ for option in options:
296
+ _object(option, {"id", "label"})
297
+ option_id = option.get("id")
298
+ if not isinstance(option_id, str) or not store.CLIENT_ID.fullmatch(option_id) or option_id in seen:
299
+ raise bad_request("options need unique valid string IDs")
300
+ choices.append({"id": option_id, "label": _text(option.get("label"), "option label", 8000)})
301
+ seen.add(option_id)
302
+ multiple = payload.get("multiple", False)
303
+ if not isinstance(multiple, bool):
304
+ raise bad_request("multiple must be a boolean")
305
+ content = {"title": title, "description": description, "channel_id": channel_id,
306
+ "anchor_id": anchor_id, "sources": sources, "options": choices, "multiple": multiple}
307
+ # Omitting empty blocks preserves the exact v30 content fingerprint, so an
308
+ # old stable-key retry remains a no-op after the feature/table rename.
309
+ if ordered:
310
+ content["blocks"] = ordered
311
+ return content, refs
312
+
313
+
314
+ def put_item(conn, p, key, payload, now):
315
+ p = _principal(conn, p, now, write=True)
316
+ if p.is_human or p.identity_type not in ("agent", "system"):
317
+ raise forbidden("only your own agents can add tasks")
318
+ if not isinstance(key, str) or not store.CLIENT_ID.fullmatch(key):
319
+ raise bad_request("task key must be a valid client ID")
320
+ content, refs = _content(conn, p, payload)
321
+ digest = _digest(content)
322
+ row = conn.execute("SELECT * FROM task_items WHERE owner_id = ? AND agent_id = ? AND item_key = ?",
323
+ (p.owner_id, p.id, key)).fetchone()
324
+ if row is not None and row["content_hash"] == digest:
325
+ # Exact retry is safe, including a retry after the human closed the item.
326
+ return _item(conn, p, _row(conn, p, row["id"]))
327
+ if row is not None:
328
+ _row(conn, p, row["id"])
329
+ base = _integer(payload.get("base_version"), "base_version")
330
+ if base != row["version"]:
331
+ raise conflict("task_version_conflict", "task changed; reload before updating")
332
+ conn.execute("""UPDATE task_items SET title = ?, description = ?, channel_id = ?, original_channel_id = ?,
333
+ anchor_id = ?, original_anchor_id = ?, options = ?, multiple = ?, content_hash = ?, blocks = ?,
334
+ version = version + 1, updated_at = ? WHERE id = ?""",
335
+ (content["title"], content["description"], content["channel_id"], content["channel_id"],
336
+ content["anchor_id"], content["anchor_id"], json.dumps(content["options"]), int(content["multiple"]),
337
+ digest, json.dumps(content.get("blocks", [])), now, row["id"]))
338
+ item_id = row["id"]
339
+ conn.execute("DELETE FROM task_sources WHERE item_id = ?", (item_id,))
340
+ else:
341
+ if "base_version" in payload:
342
+ raise conflict("task_version_conflict", "task does not exist; omit base_version to create")
343
+ rank = conn.execute("SELECT COALESCE(MAX(rank), 0) + 1 FROM task_items WHERE owner_id = ?", (p.owner_id,)).fetchone()[0]
344
+ item_id = conn.execute("""INSERT INTO task_items
345
+ (owner_id, agent_id, item_key, title, description, channel_id, original_channel_id, anchor_id,
346
+ original_anchor_id, options, multiple, content_hash, blocks, created_at, updated_at, rank)
347
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
348
+ (p.owner_id, p.id, key, content["title"], content["description"], content["channel_id"], content["channel_id"],
349
+ content["anchor_id"], content["anchor_id"], json.dumps(content["options"]), int(content["multiple"]), digest,
350
+ json.dumps(content.get("blocks", [])), now, now, rank)).lastrowid
351
+ _bump_order(conn, p.owner_id)
352
+ conn.executemany("""INSERT INTO task_sources(item_id, position, message_id, original_message_id, channel_id,
353
+ original_channel_id) VALUES (?, ?, ?, ?, ?, ?)""",
354
+ [(item_id, i, mid, mid, cid, cid) for i, (mid, cid) in enumerate(refs)])
355
+ _notice(conn, p.owner_id, p.id, now)
356
+ store.audit(conn, p.id, "task.put", f"task:{item_id}", {"key": key}, now)
357
+ return _item(conn, p, _row(conn, p, item_id))
358
+
359
+
360
+ def _answer_destination(conn, p, row, now):
361
+ if row["original_channel_id"] is not None:
362
+ if row["channel_id"] is None or (row["original_anchor_id"] is not None and row["anchor_id"] is None):
363
+ raise conflict("task_destination_unavailable", "the specified destination was deleted")
364
+ return row["channel_id"], row["anchor_id"]
365
+ try:
366
+ agent = _current(conn, row["agent_id"])
367
+ except ApiError:
368
+ raise conflict("task_destination_unavailable", "the proposing agent is no longer active")
369
+ if agent.is_human or agent.owner_id != p.id or not agent.may_post:
370
+ raise conflict("task_destination_unavailable", "the proposing agent is no longer available to you")
371
+ channel, _ = store.open_dm(conn, p, agent.id, now)
372
+ return channel["id"], None
373
+
374
+
375
+ def _replay(conn, p, receipt):
376
+ row = _row(conn, p, receipt["item_id"])
377
+ recorded = json.loads(receipt["result"])
378
+ item = _item(conn, p, row)
379
+ # Preserve the operation's outcome but never replay cached source/message text.
380
+ for name in ("version", "state", "closed_reason", "closed_at"):
381
+ item[name] = recorded[name]
382
+ message = _message(conn, p, recorded["message_id"])
383
+ if recorded["action"] == "answer":
384
+ item["answer"] = message
385
+ item["answer_message_id"] = recorded["message_id"]
386
+ return {"item": item, "message": message}, None, True
387
+
388
+
389
+ def action(conn, p, item_id, payload, request_key, now):
390
+ p = _principal(conn, p, now, write=True)
391
+ _integer(item_id, "item id")
392
+ _object(payload, {"action", "version", "body", "option_ids"})
393
+ kind = payload.get("action")
394
+ if kind not in ("answer", "done", "dismiss", "restore"):
395
+ raise bad_request("action must be answer/done/dismiss/restore")
396
+ version = _integer(payload.get("version"), "version")
397
+ if not isinstance(request_key, str) or not store.CLIENT_ID.fullmatch(request_key):
398
+ raise bad_request("a valid Idempotency-Key is required")
399
+ if kind == "answer" and not p.is_human:
400
+ raise forbidden("only the human owner can answer a task")
401
+ if kind != "answer" and ("body" in payload or "option_ids" in payload):
402
+ raise bad_request("body and option_ids are only valid for answer")
403
+ fingerprint = _digest({"item_id": item_id, "payload": payload})
404
+ prior = conn.execute("SELECT * FROM task_receipts WHERE actor_id = ? AND request_key = ?",
405
+ (p.id, request_key)).fetchone()
406
+ if prior is not None:
407
+ if prior["payload_hash"] != fingerprint:
408
+ raise conflict("idempotency_conflict", "this key was already used with different content")
409
+ return _replay(conn, p, prior)
410
+ row = _row(conn, p, item_id)
411
+ if version != row["version"]:
412
+ raise conflict("task_version_conflict", "task changed; reload before acting")
413
+ if kind == "restore":
414
+ if row["state"] != "closed":
415
+ raise conflict("task_state_conflict", "task is already open")
416
+ elif row["state"] != "open":
417
+ raise conflict("task_closed", "task is already closed")
418
+ message, created_message = None, None
419
+ if kind == "answer":
420
+ body = _text(payload.get("body", ""), "body", 65536, empty=True)
421
+ selected = payload.get("option_ids", [])
422
+ if (not isinstance(selected, list) or len(selected) > MAX_OPTIONS
423
+ or any(not isinstance(s, str) for s in selected) or len(set(selected)) != len(selected)):
424
+ raise bad_request("option_ids must be a list of distinct option IDs")
425
+ choices = {o["id"]: o["label"] for o in json.loads(row["options"])}
426
+ if any(s not in choices for s in selected) or (not row["multiple"] and len(selected) > 1):
427
+ raise bad_request("unknown option or multiple selections are not allowed")
428
+ parts = [choices[s] for s in selected]
429
+ if body:
430
+ parts.append(body)
431
+ text = "\n".join(parts)
432
+ if not text.strip():
433
+ raise bad_request("choose an answer or write a message")
434
+ cid, anchor = _answer_destination(conn, p, row, now)
435
+ normalized, digest = store.normalize_payload(cid, {"body": text, "reply_to": anchor})
436
+ # Legacy internal prefixes are stable retry identities, not product labels.
437
+ # Keep them across the Tasks rename to preserve existing message receipts.
438
+ internal_key = "#queue-answer:" + str(p.id) + ":" + request_key
439
+ message, created = store.post_message(conn, p, cid, internal_key, normalized, digest, now)
440
+ if created:
441
+ created_message = message
442
+ conn.execute("UPDATE task_items SET answer_id = ?, original_answer_id = ? WHERE id = ?",
443
+ (message["id"], message["id"], item_id))
444
+ state = "open" if kind == "restore" else "closed"
445
+ reason = None if kind == "restore" else "answered" if kind == "answer" else "dismissed" if kind == "dismiss" else "done"
446
+ closed_at = None if kind == "restore" else now
447
+ conn.execute("""UPDATE task_items SET state = ?, closed_reason = ?, closed_at = ?,
448
+ version = version + 1, updated_at = ? WHERE id = ?""", (state, reason, closed_at, now, item_id))
449
+ row = _row(conn, p, item_id)
450
+ recorded = {"action": kind, "version": row["version"], "state": state, "closed_reason": reason,
451
+ "closed_at": closed_at, "message_id": message["id"] if message else None}
452
+ conn.execute("""INSERT INTO task_receipts(actor_id, request_key, item_id, payload_hash, result, created_at)
453
+ VALUES (?, ?, ?, ?, ?, ?)""", (p.id, request_key, item_id, fingerprint, json.dumps(recorded), now))
454
+ store.audit(conn, p.id, "task." + kind, f"task:{item_id}", {"message_id": recorded["message_id"]}, now)
455
+ if not p.is_human:
456
+ _notice(conn, row["owner_id"], p.id, now)
457
+ return {"item": _item(conn, p, row), "message": message}, created_message, False
458
+
459
+
460
+ def move_item(conn, p, item_id, payload, now):
461
+ p = _principal(conn, p, now, write=True)
462
+ row = _row(conn, p, item_id)
463
+ _object(payload, {"order_version", "before_id", "after_id"})
464
+ version = payload.get("order_version")
465
+ if not isinstance(version, int) or isinstance(version, bool) or version < 0:
466
+ raise bad_request("order_version must be a nonnegative integer")
467
+ if version != _order_version(conn, _owner(p)):
468
+ raise conflict("task_order_conflict", "task order changed; reload before moving")
469
+ before = _integer(payload.get("before_id"), "before_id", optional=True)
470
+ after = _integer(payload.get("after_id"), "after_id", optional=True)
471
+ if before is not None and after is not None:
472
+ raise bad_request("specify only before_id or after_id")
473
+ neighbor = before if before is not None else after
474
+ if neighbor == item_id:
475
+ raise bad_request("an item cannot be its own neighbor")
476
+ if neighbor is not None:
477
+ _row(conn, p, neighbor)
478
+ ids = [r[0] for r in conn.execute("SELECT id FROM task_items WHERE owner_id = ? ORDER BY rank, id", (_owner(p),))]
479
+ old = list(ids)
480
+ ids.remove(item_id)
481
+ index = len(ids) if neighbor is None else ids.index(neighbor) + (1 if after is not None else 0)
482
+ ids.insert(index, item_id)
483
+ if ids != old:
484
+ conn.executemany("UPDATE task_items SET rank = ? WHERE id = ?", [(i + 1, mid) for i, mid in enumerate(ids)])
485
+ _bump_order(conn, _owner(p))
486
+ store.audit(conn, p.id, "task.move", f"task:{row['id']}", {"before_id": before, "after_id": after}, now)
487
+ return _listing(conn, p, True, "manual", "asc")
488
+
489
+
490
+ def notice_due(conn, now):
491
+ return conn.execute("SELECT 1 FROM task_notices WHERE state = 'pending' AND due_at <= ? LIMIT 1", (now,)).fetchone() is not None
492
+
493
+
494
+ def deliver_notice(conn, now):
495
+ notice = conn.execute("SELECT * FROM task_notices WHERE state = 'pending' AND due_at <= ? ORDER BY due_at, id LIMIT 1",
496
+ (now,)).fetchone()
497
+ if notice is None:
498
+ return None
499
+ try:
500
+ agent = _current(conn, notice["agent_id"])
501
+ owner = _current(conn, notice["owner_id"])
502
+ if agent.is_human or not owner.is_human or agent.owner_id != owner.id or not agent.may_post:
503
+ raise forbidden("task notice is no longer authorized")
504
+ except ApiError:
505
+ conn.execute("UPDATE task_notices SET state = 'suppressed' WHERE id = ?", (notice["id"],))
506
+ return None
507
+ # A delivery error must not leave a newly created empty DM committed. Unexpected
508
+ # failures propagate, rolling back the outer write; expected access failures
509
+ # roll back this savepoint and suppress the permanently invalid batch.
510
+ conn.execute("SAVEPOINT task_notice_delivery")
511
+ try:
512
+ channel, _ = store.open_dm(conn, agent, owner.id, now)
513
+ n = notice["changes"]
514
+ body = f"I updated your tasks ({n} {'change' if n == 1 else 'changes'}). [Open Tasks](#tasks)"
515
+ normalized, digest = store.normalize_payload(channel["id"], {"body": body})
516
+ # Retain the historical internal idempotency prefix for existing batches.
517
+ message, created = store.post_message(conn, agent, channel["id"], "#queue-notice:" + str(notice["id"]),
518
+ normalized, digest, now)
519
+ conn.execute("UPDATE task_notices SET state = 'sent', message_id = ? WHERE id = ?",
520
+ (message["id"], notice["id"]))
521
+ conn.execute("RELEASE task_notice_delivery")
522
+ return message if created else None
523
+ except ApiError as exc:
524
+ conn.execute("ROLLBACK TO task_notice_delivery")
525
+ conn.execute("RELEASE task_notice_delivery")
526
+ if exc.code == "channel_archived":
527
+ # Archival is reversible; retain the durable batch and avoid a hot
528
+ # retry loop while leaving other agents' batches free to deliver.
529
+ conn.execute("UPDATE task_notices SET due_at = ? WHERE id = ?", (now + NOTICE_DELAY, notice["id"]))
530
+ return None
531
+ if exc.status in (401, 403, 404):
532
+ conn.execute("UPDATE task_notices SET state = 'suppressed' WHERE id = ?", (notice["id"],))
533
+ return None
534
+ raise
{src/msgboard → msgboard}/transfer.py RENAMED
@@ -5,8 +5,6 @@ files are installed before their rows commit; a failed transaction may leave an
5
  unreferenced object, but never publishes a row whose bytes are incomplete.
6
  """
7
 
8
- from __future__ import annotations
9
-
10
  import hashlib
11
  import json
12
  import math
 
5
  unreferenced object, but never publishes a row whose bytes are incomplete.
6
  """
7
 
 
 
8
  import hashlib
9
  import json
10
  import math
pyproject.toml DELETED
@@ -1,30 +0,0 @@
1
- [build-system]
2
- requires = ["setuptools>=77"]
3
- build-backend = "setuptools.build_meta"
4
-
5
- [project]
6
- name = "msgboard"
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",
15
- "uvicorn>=0.29",
16
- "httpx>=0.27",
17
- ]
18
-
19
- [project.optional-dependencies]
20
- test = ["pytest>=8"]
21
- hf = ["huggingface_hub>=1.31"]
22
-
23
- [tool.setuptools.packages.find]
24
- where = ["src"]
25
-
26
- [tool.pytest.ini_options]
27
- testpaths = ["tests"]
28
-
29
- [tool.setuptools.package-data]
30
- msgboard = ["dashboard.html"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastapi>=0.110
2
+ uvicorn>=0.29
3
+ httpx>=0.27
4
+ huggingface_hub>=1.31