fsanyoto commited on
Commit
6ccba1e
·
verified ·
1 Parent(s): 3a021ea

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "7aaf8b12c2",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "bd9cb6aad",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 7aaf8b12c2
 
1
+ bd9cb6aad
api/sync_worker.py CHANGED
@@ -12,6 +12,8 @@ import importlib
12
  import os
13
  import sys
14
  import threading
 
 
15
  from pathlib import Path
16
 
17
  API_DIR = Path(__file__).resolve().parent
@@ -115,6 +117,50 @@ def boot_app_migrations(app_main):
115
  job.join()
116
 
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  def main(argv=None):
119
  # Enable before app imports so native failures include every Python thread's stack.
120
  faulthandler.enable(all_threads=True)
@@ -166,5 +212,31 @@ def main(argv=None):
166
  pass
167
 
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  if __name__ == "__main__":
170
- main()
 
12
  import os
13
  import sys
14
  import threading
15
+ import time
16
+ import traceback
17
  from pathlib import Path
18
 
19
  API_DIR = Path(__file__).resolve().parent
 
117
  job.join()
118
 
119
 
120
+ #: Seconds a job exit waits, in total, for the Sheet warm and desk threads.
121
+ EXIT_JOIN_SECONDS = 20.0
122
+
123
+
124
+ def warm_threads(warm):
125
+ """The live Sheet warm, desk and desk-run threads of a loaded sheet_warm module."""
126
+ found = [warm._STATE.get("thread"), warm._DESK.get("thread")]
127
+ found += [desk_run.get("thread") for desk_run in list(warm._TENANT_RUNS.values())]
128
+ return [t for t in found if isinstance(t, threading.Thread) and t.is_alive()
129
+ and t is not threading.current_thread()]
130
+
131
+
132
+ def stop_background(join_seconds=EXIT_JOIN_SECONDS):
133
+ """Stop the Sheet warm, log its shutdown line, join its threads; return the names still alive."""
134
+ warm = sys.modules.get("sheet_warm")
135
+ if warm is None:
136
+ return []
137
+ # os._exit skips atexit, so the shutdown line is logged here.
138
+ warm._on_exit()
139
+ threads = warm_threads(warm)
140
+ deadline = time.monotonic() + join_seconds
141
+ for thread in threads:
142
+ thread.join(max(0.0, deadline - time.monotonic()))
143
+ return [t.name for t in threads if t.is_alive()]
144
+
145
+
146
+ def exit_job(code, *, join_seconds=EXIT_JOIN_SECONDS):
147
+ """End a job process with `code` and never enter interpreter finalization."""
148
+ # Finalization while a daemon thread is inside DuckDB aborts the process (D-13315).
149
+ try:
150
+ left = stop_background(join_seconds)
151
+ if left:
152
+ print(f"[sync-worker] exit code={code} still running: {', '.join(left)}", flush=True)
153
+ except Exception: # noqa: BLE001
154
+ traceback.print_exc()
155
+ finally:
156
+ for stream in (sys.stdout, sys.stderr):
157
+ try:
158
+ stream.flush()
159
+ except Exception: # noqa: BLE001
160
+ pass
161
+ os._exit(code)
162
+
163
+
164
  def main(argv=None):
165
  # Enable before app imports so native failures include every Python thread's stack.
166
  faulthandler.enable(all_threads=True)
 
212
  pass
213
 
214
 
215
+ def exit_code(exc):
216
+ """The process exit code for an exception that ended a job run."""
217
+ if isinstance(exc, SystemExit):
218
+ if isinstance(exc.code, str):
219
+ print(exc.code, file=sys.stderr, flush=True)
220
+ return exc.code if isinstance(exc.code, int) else (0 if exc.code is None else 1)
221
+ traceback.print_exception(exc)
222
+ return 1
223
+
224
+
225
+ def run(argv=None):
226
+ """The process entry. A job run ends in exit_job, never in interpreter finalization."""
227
+ faulthandler.enable(all_threads=True)
228
+ import sync_runtime
229
+ args = sys.argv[1:] if argv is None else argv
230
+ if not any(flag in sync_runtime.JOB_FLAGS for flag in args):
231
+ return main(args)
232
+ try:
233
+ main(args)
234
+ except BaseException as exc: # noqa: BLE001
235
+ code = exit_code(exc)
236
+ else:
237
+ code = 0
238
+ exit_job(code)
239
+
240
+
241
  if __name__ == "__main__":
242
+ run()
api/usage_activity.py CHANGED
@@ -2,6 +2,9 @@
2
 
3
  from calendar import monthrange
4
  from collections import Counter
 
 
 
5
  from datetime import date, datetime, time, timedelta, timezone
6
  import base64
7
  import binascii
@@ -22,6 +25,10 @@ SOURCE_KINDS = {
22
  "turn_audit": ("ai_turn",),
23
  }
24
  PAGE = 200
 
 
 
 
25
  UTC = timezone.utc
26
 
27
 
@@ -60,9 +67,9 @@ def date_range(from_=None, to=None, *, now=None):
60
  return start, end, now
61
 
62
 
63
- def _unlimited_prefix(reader):
64
  """Expand readers without a cursor until a short result proves exhaustion."""
65
- limit = PAGE
66
  while True:
67
  rows = reader(limit)
68
  if len(rows) < limit:
@@ -115,7 +122,8 @@ def _activity(session, start, stop, now, source):
115
  with activity_log.read_scope(session.runtime):
116
  while True:
117
  page = activity_log.read(session.runtime, can_read_object=lambda obj: True,
118
- since=start, until=min(stop, now), cursor=cursor, limit=PAGE)
 
119
  for row in page["records"]:
120
  if _tenant_row(row, session.tenant) and row["kind"] in {"record", "field"}:
121
  yield _timestamp(row["occurred_at"]), row.get("by") or "", row["kind"] + "_edit"
@@ -146,41 +154,82 @@ def _history_tables(rt, now):
146
  return sorted(tables)
147
 
148
 
149
- def _cells(session, start, stop, now, source):
 
 
 
 
 
 
 
 
 
 
150
  source["retention"] = {"days": history_rows.RETENTION_DAYS}
151
- for table in _history_tables(session.runtime, now):
152
- if table == activity_log.DATABASE_KEY:
153
- continue
154
- history = user_tables.value_history(table, st=session.runtime,
155
- retention_days=history_rows.RETENTION_DAYS, extended_entitled=True)
156
- for row in history["events"]:
157
- if _tenant_row(row, session.tenant) and row.get("kind") in {"edit", "restore"}:
158
- for _ in row.get("changes", {}):
159
- yield _timestamp(row["at"]), row.get("actor") or "", "cell_edit"
160
 
161
 
162
- def _views(session, start, stop, now, source):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  source["retention"] = {"days": None, "documentRowsPerTable": view_audit.RING_CAP}
164
  from core.view_templates import _WS_KEYS
165
- keys = set(_WS_KEYS.values()) | {key for key in session.runtime.list_keys("ut_")
166
- if key.endswith("_table_workspace")}
167
- for table in sorted(keys):
168
- home = view_audit.home(session.runtime, table)
169
- data = None
170
- if home == view_audit.DOCUMENT:
171
- # Read outside rows(), whose legacy document fallback swallows store failures.
172
- data = session.runtime.get(table) or {}
173
- ring = data.get(view_audit.AUDIT_KEY) or []
174
- if len(ring) >= view_audit.RING_CAP:
175
- held = min(_timestamp(row["ts"]) for row in ring).isoformat()
176
- source["heldFrom"] = max(source["heldFrom"], held)
177
- source["limitations"].append({"code": "view_ring", "cause":
178
- "A view document retains only its newest 2000 audit rows."})
179
- rows = _unlimited_prefix(lambda limit: view_audit.rows(session.runtime,
180
- table_key=table, since=math.nextafter(start.timestamp(), -math.inf), limit=limit, data=data))
181
- for row in rows:
182
- if _tenant_row(row, session.tenant):
183
- yield _timestamp(row["ts"]), row.get("actor") or "", "view_edit"
184
 
185
 
186
  def _turns(session, start, stop, now, source):
@@ -219,6 +268,135 @@ def _turns(session, start, stop, now, source):
219
 
220
  READERS = {"security_events": _security, "activity_events": _activity,
221
  "value_history": _cells, "view_audit": _views, "turn_audit": _turns}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
 
224
  def _source_error(exc):
@@ -412,6 +590,7 @@ def read(session, *, from_=None, to=None, user=None, kind=None, now=None):
412
  "view_audit": start, "turn_audit": start}
413
  sources, counts = [], Counter()
414
  totals = {key: 0 for key in selected}
 
415
  for name, reader in READERS.items():
416
  kinds = [key for key in SOURCE_KINDS[name] if key in selected]
417
  if not kinds:
@@ -421,33 +600,38 @@ def read(session, *, from_=None, to=None, user=None, kind=None, now=None):
421
  if floors[name] > start:
422
  source["limitations"].append({"code": "retention", "cause":
423
  "This source no longer holds the beginning of the requested range."})
424
- local = Counter()
425
- try:
426
- for at, actor, event_kind in reader(session, start, stop, now, source):
427
- if (start <= at < stop and at <= now and event_kind in kinds
428
- and (user is None or actor == user)):
429
- local[(at.date().isoformat(), actor, event_kind)] += 1
430
- except Exception as exc:
431
  source.update(status="error", error=_source_error(exc))
432
  for key in kinds:
433
  totals[key] = None
434
  else:
435
  source["total"] = sum(local.values())
436
- source["byKind"] = {key: sum(n for (_, _, k), n in local.items() if k == key) for key in kinds}
 
 
 
437
  source["status"] = "partial" if source["limitations"] else "ok"
438
  counts.update(local)
439
  totals.update(source["byKind"])
440
  sources.append(source)
441
  complete = all(source["status"] == "ok" for source in sources)
442
- users = sorted({actor for _, actor, _ in counts})
 
 
 
 
 
443
  by_user = [{"user": actor, "byKind": {
444
- key: None if totals[key] is None else sum(n for (_, a, k), n in counts.items() if a == actor and k == key)
445
  for key in selected}} for actor in users]
446
  by_day = []
447
  day = first
448
  while day <= last:
449
- values = {key: None if totals[key] is None else sum(
450
- n for (d, _, k), n in counts.items() if d == day.isoformat() and k == key) for key in selected}
451
  for source in sources:
452
  if day < _timestamp(source["heldFrom"]).date():
453
  for key in source["kinds"]:
 
2
 
3
  from calendar import monthrange
4
  from collections import Counter
5
+ from concurrent.futures import Future
6
+ import contextvars
7
+ from functools import partial
8
  from datetime import date, datetime, time, timedelta, timezone
9
  import base64
10
  import binascii
 
25
  "turn_audit": ("ai_turn",),
26
  }
27
  PAGE = 200
28
+ # A first prefix this large ends most reads in one round trip. A full prefix still doubles.
29
+ FIRST_PREFIX = 1 << 20
30
+ # Sources and their per-table reads run concurrently. Five of the eight pooled connections, at most.
31
+ READ_WORKERS = 5
32
  UTC = timezone.utc
33
 
34
 
 
67
  return start, end, now
68
 
69
 
70
+ def _unlimited_prefix(reader, first=FIRST_PREFIX):
71
  """Expand readers without a cursor until a short result proves exhaustion."""
72
+ limit = first
73
  while True:
74
  rows = reader(limit)
75
  if len(rows) < limit:
 
122
  with activity_log.read_scope(session.runtime):
123
  while True:
124
  page = activity_log.read(session.runtime, can_read_object=lambda obj: True,
125
+ since=start, until=min(stop, now), cursor=cursor,
126
+ limit=activity_log.MAX_PAGE)
127
  for row in page["records"]:
128
  if _tenant_row(row, session.tenant) and row["kind"] in {"record", "field"}:
129
  yield _timestamp(row["occurred_at"]), row.get("by") or "", row["kind"] + "_edit"
 
154
  return sorted(tables)
155
 
156
 
157
+ def _cell_table(session, table, source):
158
+ history = user_tables.value_history(table, st=session.runtime,
159
+ retention_days=history_rows.RETENTION_DAYS, extended_entitled=True)
160
+ for row in history["events"]:
161
+ if _tenant_row(row, session.tenant) and row.get("kind") in {"edit", "restore"}:
162
+ for _ in row.get("changes", {}):
163
+ yield _timestamp(row["at"]), row.get("actor") or "", "cell_edit"
164
+
165
+
166
+ def _cells_units(session, start, stop, now, source):
167
+ """Return one independent read per history table, in table order."""
168
  source["retention"] = {"days": history_rows.RETENTION_DAYS}
169
+ return [partial(_cell_table, session, table) for table in _history_tables(session.runtime, now)
170
+ if table != activity_log.DATABASE_KEY]
 
 
 
 
 
 
 
171
 
172
 
173
+ def _cells(session, start, stop, now, source):
174
+ for unit in _cells_units(session, start, stop, now, source):
175
+ yield from unit(source)
176
+
177
+
178
+ def _view_table(session, start, table, source):
179
+ home = view_audit.home(session.runtime, table)
180
+ data = None
181
+ if home == view_audit.DOCUMENT:
182
+ # Read outside rows(), whose legacy document fallback swallows store failures.
183
+ data = session.runtime.get(table) or {}
184
+ ring = data.get(view_audit.AUDIT_KEY) or []
185
+ if len(ring) >= view_audit.RING_CAP:
186
+ held = min(_timestamp(row["ts"]) for row in ring).isoformat()
187
+ source["heldFrom"] = max(source["heldFrom"], held)
188
+ source["limitations"].append({"code": "view_ring", "cause":
189
+ "A view document retains only its newest 2000 audit rows."})
190
+ rows = _unlimited_prefix(lambda limit: view_audit.rows(session.runtime,
191
+ table_key=table, since=math.nextafter(start.timestamp(), -math.inf), limit=limit, data=data))
192
+ for row in rows:
193
+ if _tenant_row(row, session.tenant):
194
+ yield _timestamp(row["ts"]), row.get("actor") or "", "view_edit"
195
+
196
+
197
+ def _prefetch_view_layouts(rt, tables):
198
+ """Seed this request's layout memo from one marker query instead of one query per workspace."""
199
+ from core import view_settings_rows
200
+ if callable(getattr(rt, "view_settings_rows", None)):
201
+ return
202
+ names = {}
203
+ for table in tables:
204
+ bound = view_settings_rows.bind(rt, table)
205
+ if isinstance(bound, view_settings_rows.PgRows):
206
+ names.setdefault(bound.tenant_slug, []).append(bound.name)
207
+ if not names:
208
+ return
209
+ from core import store_pg
210
+ layouts = store_pg._layout_memo()
211
+ if layouts is None:
212
+ return
213
+ for slug, keys in names.items():
214
+ migrated = store_pg._view_rows_many(keys, slug)
215
+ for key in keys:
216
+ # Same key and value _view_rows memoises. An entry this request already holds wins.
217
+ layouts.setdefault((store_pg._effective_slug(slug), str(key)), key in migrated)
218
+
219
+
220
+ def _views_units(session, start, stop, now, source):
221
+ """Return one independent read per view workspace, in key order."""
222
  source["retention"] = {"days": None, "documentRowsPerTable": view_audit.RING_CAP}
223
  from core.view_templates import _WS_KEYS
224
+ keys = sorted(set(_WS_KEYS.values()) | {key for key in session.runtime.list_keys("ut_")
225
+ if key.endswith("_table_workspace")})
226
+ _prefetch_view_layouts(session.runtime, keys)
227
+ return [partial(_view_table, session, start, table) for table in keys]
228
+
229
+
230
+ def _views(session, start, stop, now, source):
231
+ for unit in _views_units(session, start, stop, now, source):
232
+ yield from unit(source)
 
 
 
 
 
 
 
 
 
 
233
 
234
 
235
  def _turns(session, start, stop, now, source):
 
268
 
269
  READERS = {"security_events": _security, "activity_events": _activity,
270
  "value_history": _cells, "view_audit": _views, "turn_audit": _turns}
271
+ # A source listed here splits into per-table reads that share the request's worker pool.
272
+ UNITS = {"value_history": _cells_units, "view_audit": _views_units}
273
+
274
+
275
+ def _count(unit, source, start, stop, now, user, kinds):
276
+ """Count one read's in-range events, returning the counter or the exception that stopped it."""
277
+ from core import request_timing
278
+ local = Counter()
279
+ try:
280
+ with request_timing.thread_scope():
281
+ for at, actor, event_kind in unit(source):
282
+ if (start <= at < stop and at <= now and event_kind in kinds
283
+ and (user is None or actor == user)):
284
+ local[(at.date().isoformat(), actor, event_kind)] += 1
285
+ except Exception as exc:
286
+ return None, exc
287
+ return local, None
288
+
289
+
290
+ def _plan(splitter, session, start, stop, now, source):
291
+ try:
292
+ return splitter(session, start, stop, now, source), None
293
+ except Exception as exc:
294
+ return None, exc
295
+
296
+
297
+ def _enlisted():
298
+ """Whether a caller transaction is bound, whose one connection must not cross threads."""
299
+ import sys
300
+ store_pg = sys.modules.get("core.store_pg")
301
+ held = getattr(store_pg, "_CALLER_TRANSACTION", None)
302
+ return held is not None and held.get() is not None
303
+
304
+
305
+ class _Inline:
306
+ """Run a submitted call at once, for a caller whose transaction pins one thread."""
307
+
308
+ def submit(self, fn, *args):
309
+ done = Future()
310
+ done.set_result(fn(*args))
311
+ return done
312
+
313
+
314
+ class _Workers:
315
+ """A bounded request-scoped pool whose threads start through process_role."""
316
+
317
+ def __init__(self, size):
318
+ import queue
319
+ import process_role
320
+ self.jobs = queue.SimpleQueue()
321
+ self.threads = [process_role.thread(target=self._loop, name="usage-activity-read", kind="light")
322
+ for _ in range(size)]
323
+ if not all(process_role.admitted(job) for job in self.threads):
324
+ raise RuntimeError("Usage activity workers were refused.")
325
+ for job in self.threads:
326
+ job.start()
327
+
328
+ def _loop(self):
329
+ while (item := self.jobs.get()) is not None:
330
+ done, context, fn, args = item
331
+ try:
332
+ done.set_result(context.run(fn, *args))
333
+ except BaseException as exc: # noqa: BLE001
334
+ done.set_exception(exc)
335
+
336
+ def submit(self, fn, *args):
337
+ # A copied context carries the request deadline, its accumulator and any store binding.
338
+ done = Future()
339
+ self.jobs.put((done, contextvars.copy_context(), fn, args))
340
+ return done
341
+
342
+ def close(self):
343
+ for _ in self.threads:
344
+ self.jobs.put(None)
345
+ for job in self.threads:
346
+ job.join()
347
+
348
+
349
+ def _collect_all(session, start, stop, now, user, jobs):
350
+ """Read every source and its per-table units concurrently, then merge them in serial order.
351
+
352
+ Each call runs in a copy of the caller's context, so the request deadline, the accumulator
353
+ and any store binding carry. A unit writes limitations to its own scratch source, and the merge
354
+ replays them in table order, stopping at the first failed unit as a serial read would.
355
+ """
356
+ def run(pool):
357
+ units, plans = {}, {}
358
+ for index, (name, reader, source, kinds) in enumerate(jobs):
359
+ if name in UNITS:
360
+ plans[pool.submit(_plan, UNITS[name], session, start, stop, now, source)] = index
361
+ else:
362
+ whole = partial(reader, session, start, stop, now)
363
+ units[index] = [(source, pool.submit(_count, whole, source, start, stop, now, user, kinds))]
364
+ # Source order, so the slower cell units queue ahead of the view units.
365
+ for planned in list(plans):
366
+ index = plans[planned]
367
+ source, kinds = jobs[index][2], jobs[index][3]
368
+ parts, exc = planned.result()
369
+ if exc is not None:
370
+ units[index] = exc
371
+ continue
372
+ units[index] = []
373
+ for part in parts:
374
+ scratch = {"heldFrom": source["heldFrom"], "limitations": []}
375
+ units[index].append((scratch, pool.submit(_count, part, scratch, start, stop, now, user, kinds)))
376
+ results = []
377
+ for index, (_, _, source, _) in enumerate(jobs):
378
+ if isinstance(units[index], Exception):
379
+ results.append((None, units[index]))
380
+ continue
381
+ local, failure = Counter(), None
382
+ for scratch, future in units[index]:
383
+ counted, failure = future.result()
384
+ if scratch is not source:
385
+ source["limitations"].extend(scratch["limitations"])
386
+ source["heldFrom"] = max(source["heldFrom"], scratch["heldFrom"])
387
+ if failure is not None:
388
+ break
389
+ local.update(counted)
390
+ results.append((None, failure) if failure is not None else (local, None))
391
+ return results
392
+
393
+ if _enlisted():
394
+ return run(_Inline())
395
+ pool = _Workers(READ_WORKERS)
396
+ try:
397
+ return run(pool)
398
+ finally:
399
+ pool.close()
400
 
401
 
402
  def _source_error(exc):
 
590
  "view_audit": start, "turn_audit": start}
591
  sources, counts = [], Counter()
592
  totals = {key: 0 for key in selected}
593
+ jobs = []
594
  for name, reader in READERS.items():
595
  kinds = [key for key in SOURCE_KINDS[name] if key in selected]
596
  if not kinds:
 
600
  if floors[name] > start:
601
  source["limitations"].append({"code": "retention", "cause":
602
  "This source no longer holds the beginning of the requested range."})
603
+ jobs.append((name, reader, source, kinds))
604
+ for (_, _, source, kinds), (local, exc) in zip(jobs, _collect_all(
605
+ session, start, stop, now, user, jobs)):
606
+ if exc is not None:
 
 
 
607
  source.update(status="error", error=_source_error(exc))
608
  for key in kinds:
609
  totals[key] = None
610
  else:
611
  source["total"] = sum(local.values())
612
+ by_kind = Counter()
613
+ for (_, _, key), n in local.items():
614
+ by_kind[key] += n
615
+ source["byKind"] = {key: by_kind[key] for key in kinds}
616
  source["status"] = "partial" if source["limitations"] else "ok"
617
  counts.update(local)
618
  totals.update(source["byKind"])
619
  sources.append(source)
620
  complete = all(source["status"] == "ok" for source in sources)
621
+ # One pass over the cube. A per-day or per-user rescan is quadratic on a 13-month range.
622
+ user_kind, day_kind = Counter(), Counter()
623
+ for (day_iso, actor, key), n in counts.items():
624
+ user_kind[(actor, key)] += n
625
+ day_kind[(day_iso, key)] += n
626
+ users = sorted({actor for actor, _ in user_kind})
627
  by_user = [{"user": actor, "byKind": {
628
+ key: None if totals[key] is None else user_kind[(actor, key)]
629
  for key in selected}} for actor in users]
630
  by_day = []
631
  day = first
632
  while day <= last:
633
+ values = {key: None if totals[key] is None else day_kind[(day.isoformat(), key)]
634
+ for key in selected}
635
  for source in sources:
636
  if day < _timestamp(source["heldFrom"]).date():
637
  for key in source["kinds"]:
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 9289947cb4215581bb120c57efd62f49fb9ccf4e95e74d88ff2bba1b6edbd9c1
 
1
+ 2ebec5cef12686e0461bac2eb99f2ebf4964a4351a385fa76e28daa2c2dd02ea
web/src/connectors/ConnectorsPage.tsx CHANGED
@@ -443,6 +443,11 @@ async function dailySyncWarnings(connectorKey: string, signal: AbortSignal): Pro
443
  }
444
  }
445
 
 
 
 
 
 
446
  /** Keep the status line mounted while the drawer loads or refreshes its database page. */
447
  export function ConnectorSyncStatusLine({ status, problem = "" }: {
448
  status: ConnectorSyncReading | null; problem?: string;
@@ -460,8 +465,8 @@ export function ConnectorSyncStatusLine({ status, problem = "" }: {
460
  : readableSyncStamp(status.lastSyncAt)}</time>
461
  : "not recorded"}</> : problem || "Loading sync status…"}
462
  {showBudget ? <>{", "}<span data-sync-budget={status.provider}>
463
- {showDuration ? `${status.passMinutes} min of ${status.budgetMinutes} min budget`
464
- : `${status.budgetMinutes} min budget`}
465
  </span></> : null}
466
  {status && problem ? `, ${problem}` : ""}
467
  </p>;
 
443
  }
444
  }
445
 
446
+ /** A pass length as people read it: whole minutes, never the server's 3-decimal float. */
447
+ export function wholeMinutes(minutes: number): string {
448
+ return minutes > 0 && minutes < 1 ? "under 1" : String(Math.round(minutes));
449
+ }
450
+
451
  /** Keep the status line mounted while the drawer loads or refreshes its database page. */
452
  export function ConnectorSyncStatusLine({ status, problem = "" }: {
453
  status: ConnectorSyncReading | null; problem?: string;
 
465
  : readableSyncStamp(status.lastSyncAt)}</time>
466
  : "not recorded"}</> : problem || "Loading sync status…"}
467
  {showBudget ? <>{", "}<span data-sync-budget={status.provider}>
468
+ {showDuration ? `${wholeMinutes(status.passMinutes as number)} min of ${wholeMinutes(status.budgetMinutes as number)} min budget`
469
+ : `${wholeMinutes(status.budgetMinutes as number)} min budget`}
470
  </span></> : null}
471
  {status && problem ? `, ${problem}` : ""}
472
  </p>;
web/src/settings/UsagePane.tsx CHANGED
@@ -1,4 +1,5 @@
1
  import { useCallback, useEffect, useId, useRef, useState } from "react";
 
2
  import { Funnel, X } from "@phosphor-icons/react";
3
  import { createPortal } from "react-dom";
4
  import { AiUsageCard } from "../account/UsagePage";
@@ -186,14 +187,14 @@ function DailyActivityChart({ report, kinds }: { report: UsageActivity; kinds: U
186
  const chartRef = useRef<SVGSVGElement>(null);
187
  const titleId = useId();
188
  const descriptionId = useId();
189
- const enabled = kinds.filter(kind => !hiddenKinds.includes(kind));
 
 
 
190
  const days = report.byDay.map(row => {
191
- const values = enabled.map(kind => {
192
- const value = row.byKind[kind];
193
- return { kind, value: typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null };
194
- });
195
  return { day: row.day, values, knownTotal: values.reduce((total, item) => item.value === null ? total : total + item.value, 0),
196
- unknown: values.some(item => item.value === null) };
197
  });
198
  const retained = !report.complete;
199
  const valueLabel = (value: number | null) => value === null ? "Unavailable" : `${count(value)}${retained ? " retained" : ""}`;
@@ -212,31 +213,41 @@ function DailyActivityChart({ report, kinds }: { report: UsageActivity; kinds: U
212
  const slot = (width - left - 16) / Math.max(days.length, 1);
213
  const labelEvery = Math.max(7, Math.ceil(days.length / 12));
214
  const inspected = days[hoveredDay ?? focusedDay];
215
- const hasUnknown = days.some(row => row.unknown);
 
 
 
 
 
216
  const toggle = (kind: UsageKind) => setHiddenKinds(old => old.includes(kind) ? old.filter(item => item !== kind) : [...old, kind]);
217
 
218
  return <section className="set-usage-section set-usage-chart" aria-labelledby={titleId}>
219
  <h4 id={titleId} className="set-h4">Daily activity</h4>
220
  <div className="set-usage-chart-layout">
221
- <div className="set-usage-chart-legend" role="group" aria-label="Chart metrics">
222
  <span className="set-usage-chart-label">Metrics</span>
223
- {kinds.map(kind => <label key={kind} className="set-usage-chart-toggle">
224
- <input type="checkbox" checked={!hiddenKinds.includes(kind)} onChange={() => toggle(kind)} />
225
- <span className="set-usage-chart-swatch" style={{ background: activityColors[kind] }} aria-hidden="true" />
226
- <span>{USAGE_KIND_LABELS[kind]}</span>
227
- </label>)}
228
- {hasUnknown ? <span className="set-usage-meta"><span aria-hidden="true">? </span>Unavailable</span> : null}
 
 
 
 
 
229
  </div>
230
  <div className="set-usage-chart-main">
231
  <p className="set-help">{report.from} to {report.to} ({report.timezone}){retained ? " · Retained counts" : ""}</p>
232
- {!enabled.length ? <p className="set-help" role="status">Select a metric</p>
233
  : !days.length ? <p className="set-help" role="status">Daily counts unavailable</p> : <>
234
  <div className="set-usage-chart-scroll" role="region" aria-label="Daily columns" tabIndex={0}>
235
  <svg ref={chartRef} className="set-usage-chart-plot" width={width} height={248} viewBox={`0 0 ${width} 248`}
236
  role="group" aria-labelledby={titleId} aria-describedby={descriptionId}>
237
  <desc id={descriptionId}>Stacked daily event counts for the enabled metrics. Use the arrow keys to browse days, or open Daily values.
238
  {retained ? " Counts cover retained activity only." : ""}
239
- {hasUnknown ? " A question mark means a count is unavailable. Unknown counts have no segment." : ""}</desc>
240
  <g className="set-usage-chart-axis" aria-hidden="true">
241
  <text x={0} y={14}>Events</text>
242
  {[0, 1, 2, 3, 4].map(tick => {
@@ -271,8 +282,8 @@ function DailyActivityChart({ report, kinds }: { report: UsageActivity; kinds: U
271
  return <rect key={kind} x={x + slot * 0.16} y={bottom - stacked / ceiling * plotHeight}
272
  width={slot * 0.68} height={value / ceiling * plotHeight} fill={activityColors[kind]} aria-hidden="true" />;
273
  })}
274
- {row.unknown ? <text className="set-usage-chart-unknown" x={x + slot / 2} y={26} textAnchor="middle" aria-hidden="true">?</text>
275
- : row.knownTotal === 0 ? <circle className="set-usage-chart-zero" cx={x + slot / 2} cy={bottom} r={2} aria-hidden="true" /> : null}
276
  {(index === 0 || index === days.length - 1 || (index % labelEvery === 0 && index < days.length - 3))
277
  ? <text className="set-usage-chart-date" x={x + slot / 2} y={bottom + 24}
278
  textAnchor={index === 0 ? "start" : index === days.length - 1 ? "end" : "middle"} aria-hidden="true">{dayLabel(row.day, true)}</text> : null}
@@ -280,6 +291,7 @@ function DailyActivityChart({ report, kinds }: { report: UsageActivity; kinds: U
280
  })}
281
  </svg>
282
  </div>
 
283
  {inspected ? <div className="set-usage-chart-readout">
284
  <time dateTime={inspected.day}>{dayLabel(inspected.day)}</time>
285
  <dl>{inspected.values.map(({ kind, value }) => <div key={kind}>
@@ -323,15 +335,19 @@ function ActivityReport({ filters, tenant, onUsers }: {
323
  if (failed) return <ReadError onRetry={retry} />;
324
  if (!report) return <Skeleton />;
325
  const kinds = Object.keys(report.byKind) as UsageKind[];
326
- const metrics: Array<[string, number | null | undefined]> = [
327
- ["Total", report.total], ...kinds.map(kind => [USAGE_KIND_LABELS[kind], report.byKind[kind]] as [string, number | null | undefined]),
 
 
 
 
328
  ];
329
  const period = `${report.from} to ${report.to}`;
330
  return <>
331
  <dl className="set-usage-kpis" aria-label="Activity totals">
332
- {metrics.map(([label, value]) =>
333
  <div className="set-usage-kpi" key={label}><dt>{label}</dt>
334
- <dd>{count(value)}</dd><dd className="set-usage-meta">{report.complete ? "Selected range" : "Retained range"}</dd>
335
  </div>)}
336
  </dl>
337
  <DailyActivityChart report={report} kinds={kinds} />
 
1
  import { useCallback, useEffect, useId, useRef, useState } from "react";
2
+ import type { CSSProperties } from "react";
3
  import { Funnel, X } from "@phosphor-icons/react";
4
  import { createPortal } from "react-dom";
5
  import { AiUsageCard } from "../account/UsagePage";
 
187
  const chartRef = useRef<SVGSVGElement>(null);
188
  const titleId = useId();
189
  const descriptionId = useId();
190
+ const known = (value: number | null | undefined) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
191
+ // A kind with no range total cannot be read, so its rail row is disabled and it never joins the chart.
192
+ const readable = kinds.filter(kind => known(report.byKind[kind]) !== null);
193
+ const enabled = readable.filter(kind => !hiddenKinds.includes(kind));
194
  const days = report.byDay.map(row => {
195
+ const values = enabled.map(kind => ({ kind, value: known(row.byKind[kind]) }));
 
 
 
196
  return { day: row.day, values, knownTotal: values.reduce((total, item) => item.value === null ? total : total + item.value, 0),
197
+ anyKnown: values.some(item => item.value !== null) };
198
  });
199
  const retained = !report.complete;
200
  const valueLabel = (value: number | null) => value === null ? "Unavailable" : `${count(value)}${retained ? " retained" : ""}`;
 
213
  const slot = (width - left - 16) / Math.max(days.length, 1);
214
  const labelEvery = Math.max(7, Math.ceil(days.length / 12));
215
  const inspected = days[hoveredDay ?? focusedDay];
216
+ const unavailable = kinds.filter(kind => !readable.includes(kind)
217
+ || (enabled.includes(kind) && report.byDay.some(row => known(row.byKind[kind]) === null)));
218
+ const unavailableNames = unavailable.map(kind => USAGE_KIND_LABELS[kind]);
219
+ const unavailableNote = unavailableNames.length
220
+ ? `${unavailableNames.length > 1 ? `${unavailableNames.slice(0, -1).join(", ")} and ${unavailableNames[unavailableNames.length - 1]}` : unavailableNames[0]} unavailable`
221
+ : "";
222
  const toggle = (kind: UsageKind) => setHiddenKinds(old => old.includes(kind) ? old.filter(item => item !== kind) : [...old, kind]);
223
 
224
  return <section className="set-usage-section set-usage-chart" aria-labelledby={titleId}>
225
  <h4 id={titleId} className="set-h4">Daily activity</h4>
226
  <div className="set-usage-chart-layout">
227
+ <div className="set-usage-chart-rail" role="group" aria-label="Chart metrics">
228
  <span className="set-usage-chart-label">Metrics</span>
229
+ {kinds.map(kind => {
230
+ const total = known(report.byKind[kind]);
231
+ const on = total !== null && !hiddenKinds.includes(kind);
232
+ return <button key={kind} type="button" role="switch" aria-checked={on} disabled={total === null}
233
+ className={"set-usage-chart-metric" + (on ? " is-on" : "")} onClick={() => toggle(kind)}
234
+ style={{ "--set-usage-swatch": activityColors[kind] } as CSSProperties}>
235
+ <span className="set-usage-chart-swatch" aria-hidden="true" />
236
+ <span className="set-usage-chart-metric-name">{USAGE_KIND_LABELS[kind]}</span>
237
+ <span className="set-usage-chart-metric-count">{count(total)}</span>
238
+ </button>;
239
+ })}
240
  </div>
241
  <div className="set-usage-chart-main">
242
  <p className="set-help">{report.from} to {report.to} ({report.timezone}){retained ? " · Retained counts" : ""}</p>
243
+ {!enabled.length ? <p className="set-help" role="status">{readable.length ? "Select a metric" : "Daily counts unavailable"}</p>
244
  : !days.length ? <p className="set-help" role="status">Daily counts unavailable</p> : <>
245
  <div className="set-usage-chart-scroll" role="region" aria-label="Daily columns" tabIndex={0}>
246
  <svg ref={chartRef} className="set-usage-chart-plot" width={width} height={248} viewBox={`0 0 ${width} 248`}
247
  role="group" aria-labelledby={titleId} aria-describedby={descriptionId}>
248
  <desc id={descriptionId}>Stacked daily event counts for the enabled metrics. Use the arrow keys to browse days, or open Daily values.
249
  {retained ? " Counts cover retained activity only." : ""}
250
+ {unavailableNote ? ` ${unavailableNote}. Unavailable counts have no segment.` : ""}</desc>
251
  <g className="set-usage-chart-axis" aria-hidden="true">
252
  <text x={0} y={14}>Events</text>
253
  {[0, 1, 2, 3, 4].map(tick => {
 
282
  return <rect key={kind} x={x + slot * 0.16} y={bottom - stacked / ceiling * plotHeight}
283
  width={slot * 0.68} height={value / ceiling * plotHeight} fill={activityColors[kind]} aria-hidden="true" />;
284
  })}
285
+ {row.anyKnown && row.knownTotal === 0
286
+ ? <circle className="set-usage-chart-zero" cx={x + slot / 2} cy={bottom} r={2} aria-hidden="true" /> : null}
287
  {(index === 0 || index === days.length - 1 || (index % labelEvery === 0 && index < days.length - 3))
288
  ? <text className="set-usage-chart-date" x={x + slot / 2} y={bottom + 24}
289
  textAnchor={index === 0 ? "start" : index === days.length - 1 ? "end" : "middle"} aria-hidden="true">{dayLabel(row.day, true)}</text> : null}
 
291
  })}
292
  </svg>
293
  </div>
294
+ {unavailableNote ? <p className="set-usage-chart-note">{unavailableNote}</p> : null}
295
  {inspected ? <div className="set-usage-chart-readout">
296
  <time dateTime={inspected.day}>{dayLabel(inspected.day)}</time>
297
  <dl>{inspected.values.map(({ kind, value }) => <div key={kind}>
 
335
  if (failed) return <ReadError onRetry={retry} />;
336
  if (!report) return <Skeleton />;
337
  const kinds = Object.keys(report.byKind) as UsageKind[];
338
+ const rangeFoot = report.complete ? "Selected range" : "Retained range";
339
+ // A null total means one source failed. The sum of the kinds that were read still shows, labelled as partial.
340
+ const partialTotal = report.total == null && typeof report.availableTotal === "number";
341
+ const metrics: Array<[string, number | null | undefined, string]> = [
342
+ ["Total", partialTotal ? report.availableTotal : report.total, partialTotal ? "Excludes unavailable metrics" : rangeFoot],
343
+ ...kinds.map(kind => [USAGE_KIND_LABELS[kind], report.byKind[kind], rangeFoot] as [string, number | null | undefined, string]),
344
  ];
345
  const period = `${report.from} to ${report.to}`;
346
  return <>
347
  <dl className="set-usage-kpis" aria-label="Activity totals">
348
+ {metrics.map(([label, value, foot]) =>
349
  <div className="set-usage-kpi" key={label}><dt>{label}</dt>
350
+ <dd>{count(value)}</dd><dd className="set-usage-meta">{foot}</dd>
351
  </div>)}
352
  </dl>
353
  <DailyActivityChart report={report} kinds={kinds} />
web/src/styles/sdlc85/settings-usage.css CHANGED
@@ -99,21 +99,22 @@
99
 
100
  .set-usage-chart-layout {
101
  display: grid;
102
- grid-template-columns: 144px minmax(0, 1fr);
103
  align-items: start;
104
  gap: var(--lp-section-gap);
105
  min-width: 0;
106
  }
107
 
108
- .set-usage-chart-legend {
 
109
  display: grid;
110
  align-content: start;
111
- gap: var(--set-space-1);
112
  min-width: 0;
113
  }
114
 
115
  .set-usage-chart-label {
116
- padding-block: var(--set-space-2);
117
  color: var(--lp-muted);
118
  font-size: var(--lp-fs-2xs);
119
  font-weight: 500;
@@ -130,45 +131,77 @@
130
  overflow-wrap: anywhere;
131
  }
132
 
133
- .set-usage-chart-toggle {
134
  display: grid;
135
- grid-template-columns: max-content var(--set-space-2) minmax(0, 1fr);
136
  align-items: center;
137
  gap: var(--set-space-2);
 
 
138
  min-width: 0;
139
  min-height: var(--set-control-height);
140
- padding-block: var(--set-space-1);
141
- color: var(--lp-ink);
 
 
 
 
142
  font-size: var(--lp-fs-2xs);
143
- font-weight: 500;
 
144
  cursor: pointer;
145
  }
146
 
147
- .set-usage-chart-toggle > span:last-child {
148
- min-width: 0;
149
- overflow-wrap: break-word;
 
150
  }
151
 
152
- .set-usage-chart-toggle input {
153
- margin: 0;
154
- accent-color: var(--lp-blue-deep);
155
- cursor: pointer;
156
  }
157
 
158
- .set-usage-chart-toggle:has(input:not(:checked)) {
159
- color: var(--lp-muted);
160
- font-weight: 400;
161
  }
162
 
163
- .set-usage-chart-toggle:has(input:not(:checked)) .set-usage-chart-swatch {
164
- opacity: 0.4;
 
 
 
 
 
 
 
 
 
165
  }
166
 
167
  .set-usage-chart-swatch {
168
  display: inline-block;
 
169
  flex: 0 0 var(--set-space-2);
170
  width: var(--set-space-2);
171
  height: var(--set-space-2);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  }
173
 
174
  .set-usage-chart-scroll {
@@ -211,7 +244,6 @@
211
  stroke-width: 2;
212
  }
213
 
214
- .set-usage-chart-unknown,
215
  .set-usage-chart-zero {
216
  fill: var(--lp-ink);
217
  }
@@ -258,7 +290,6 @@
258
  white-space: nowrap;
259
  }
260
 
261
- .set-usage-chart-toggle input:focus-visible,
262
  .set-usage-chart-scroll:focus-visible,
263
  .set-usage-chart-values summary:focus-visible {
264
  outline: 2px solid var(--lp-blue-deep);
@@ -405,16 +436,25 @@
405
 
406
  @media (max-width: 600px) {
407
  .set-usage-chart-layout {
408
- grid-template-columns: 104px minmax(0, 1fr);
409
- gap: var(--set-space-2);
410
  }
411
 
412
- .set-usage-chart-toggle {
413
- gap: var(--set-space-1);
 
 
 
 
414
  }
415
  }
416
 
417
  @media (hover: hover) and (pointer: fine) {
 
 
 
 
 
418
  .set-usage-event:hover {
419
  text-decoration: underline;
420
  }
 
99
 
100
  .set-usage-chart-layout {
101
  display: grid;
102
+ grid-template-columns: 208px minmax(0, 1fr);
103
  align-items: start;
104
  gap: var(--lp-section-gap);
105
  min-width: 0;
106
  }
107
 
108
+ /* The metric rail: one full-width switch row per metric, styled like the Settings nav rail. */
109
+ .set-usage-chart-rail {
110
  display: grid;
111
  align-content: start;
112
+ gap: 2px;
113
  min-width: 0;
114
  }
115
 
116
  .set-usage-chart-label {
117
+ padding: 0 var(--set-space-2) var(--set-space-1);
118
  color: var(--lp-muted);
119
  font-size: var(--lp-fs-2xs);
120
  font-weight: 500;
 
131
  overflow-wrap: anywhere;
132
  }
133
 
134
+ .set-modal .set-usage .set-usage-chart-metric {
135
  display: grid;
136
+ grid-template-columns: var(--set-space-2) minmax(0, 1fr) max-content;
137
  align-items: center;
138
  gap: var(--set-space-2);
139
+ box-sizing: border-box;
140
+ width: 100%;
141
  min-width: 0;
142
  min-height: var(--set-control-height);
143
+ padding: var(--set-space-1) var(--set-space-2);
144
+ border: 0;
145
+ border-radius: var(--lp-r-sm);
146
+ background: transparent;
147
+ color: var(--lp-muted);
148
+ font: inherit;
149
  font-size: var(--lp-fs-2xs);
150
+ font-weight: 400;
151
+ text-align: left;
152
  cursor: pointer;
153
  }
154
 
155
+ .set-modal .set-usage .set-usage-chart-metric.is-on {
156
+ background: var(--lp-blue-tint);
157
+ color: var(--lp-ink);
158
+ font-weight: 500;
159
  }
160
 
161
+ .set-modal .set-usage .set-usage-chart-metric:disabled {
162
+ color: var(--lp-muted);
163
+ cursor: default;
164
+ opacity: 0.7;
165
  }
166
 
167
+ .set-modal .set-usage .set-usage-chart-metric:focus-visible {
168
+ outline: 2px solid var(--lp-blue-deep);
169
+ outline-offset: -2px;
170
  }
171
 
172
+ .set-usage-chart-metric-name {
173
+ min-width: 0;
174
+ overflow: hidden;
175
+ text-overflow: ellipsis;
176
+ white-space: nowrap;
177
+ }
178
+
179
+ .set-usage-chart-metric-count {
180
+ font-variant-numeric: tabular-nums;
181
+ text-align: right;
182
+ white-space: nowrap;
183
  }
184
 
185
  .set-usage-chart-swatch {
186
  display: inline-block;
187
+ box-sizing: border-box;
188
  flex: 0 0 var(--set-space-2);
189
  width: var(--set-space-2);
190
  height: var(--set-space-2);
191
+ border-radius: 2px;
192
+ background: var(--set-usage-swatch, currentColor);
193
+ }
194
+
195
+ /* An off metric keeps only the outline of its colour. */
196
+ .set-usage-chart-metric:not(.is-on) .set-usage-chart-swatch {
197
+ border: 1.5px solid var(--set-usage-swatch, currentColor);
198
+ background: transparent;
199
+ }
200
+
201
+ .set-usage-chart-note {
202
+ margin: 0;
203
+ color: var(--lp-muted);
204
+ font-size: var(--lp-fs-2xs);
205
  }
206
 
207
  .set-usage-chart-scroll {
 
244
  stroke-width: 2;
245
  }
246
 
 
247
  .set-usage-chart-zero {
248
  fill: var(--lp-ink);
249
  }
 
290
  white-space: nowrap;
291
  }
292
 
 
293
  .set-usage-chart-scroll:focus-visible,
294
  .set-usage-chart-values summary:focus-visible {
295
  outline: 2px solid var(--lp-blue-deep);
 
436
 
437
  @media (max-width: 600px) {
438
  .set-usage-chart-layout {
439
+ grid-template-columns: minmax(0, 1fr);
440
+ gap: var(--set-space-3);
441
  }
442
 
443
+ .set-usage-chart-rail {
444
+ grid-template-columns: repeat(2, minmax(0, 1fr));
445
+ }
446
+
447
+ .set-usage-chart-label {
448
+ grid-column: 1 / -1;
449
  }
450
  }
451
 
452
  @media (hover: hover) and (pointer: fine) {
453
+ .set-modal .set-usage .set-usage-chart-metric:not(:disabled):not(.is-on):hover {
454
+ background: var(--lp-surface-2);
455
+ color: var(--lp-ink);
456
+ }
457
+
458
  .set-usage-event:hover {
459
  text-decoration: underline;
460
  }