ai_co_discuss 0.5.33 → 0.5.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1 -0
  2. package/README.zh-CN.md +1 -0
  3. package/backend/analytics.py +584 -0
  4. package/backend/free_room.py +105 -12
  5. package/backend/schema.sql +8 -0
  6. package/backend/server.py +44 -13
  7. package/docs/en/guide/README.md +1 -0
  8. package/docs/en/guide/admin.md +2 -2
  9. package/docs/en/guide/analytics.md +43 -0
  10. package/docs/en/guide/members.md +2 -2
  11. package/docs/en/guide/rooms.md +3 -1
  12. package/docs/en/guide/workflows.md +1 -1
  13. package/docs/en/guide/working.md +2 -2
  14. package/docs/guide/README.md +1 -0
  15. package/docs/guide/admin.md +2 -2
  16. package/docs/guide/analytics.md +43 -0
  17. package/docs/guide/members.md +2 -2
  18. package/docs/guide/rooms.md +3 -1
  19. package/docs/guide/workflows.md +1 -1
  20. package/docs/guide/working.md +2 -2
  21. package/frontend/locales/en/admin.json +16 -0
  22. package/frontend/locales/en/analytics.json +127 -0
  23. package/frontend/locales/en/backend.json +2 -0
  24. package/frontend/locales/en/discussion.json +29 -3
  25. package/frontend/locales/en/room.json +3 -1
  26. package/package.json +1 -1
  27. package/runner/adapters/claude.mjs +12 -2
  28. package/runner/adapters/codex_bridge.mjs +19 -4
  29. package/runner/adapters/index.mjs +1 -0
  30. package/runner/admin_cli.mjs +3 -1
  31. package/runner/admin_maintenance.mjs +95 -0
  32. package/runner/admin_panel.mjs +4 -3
  33. package/runner/analytics.mjs +25 -0
  34. package/runner/codiscuss.mjs +2 -1
  35. package/runner/discussion_service.mjs +108 -22
  36. package/runner/free_runner.mjs +10 -1
  37. package/runner/i18n_en.mjs +11 -1
  38. package/runner/relay_channel.mjs +1 -1
  39. package/runner/share_shared.mjs +31 -3
  40. package/runner/storage_guard.mjs +19 -4
  41. package/runner/tts.mjs +3 -3
  42. package/web/admin.css +1 -1
  43. package/web/admin.js +8 -8
  44. package/web/app.js +255 -104
  45. package/web/i18n.js +4 -4
  46. package/web/modern.css +1 -1
  47. package/web/modern.js +71 -70
package/README.md CHANGED
@@ -33,6 +33,7 @@ The [User Guide](docs/en/guide/README.md) covers each of these in full.
33
33
  - **Structured discussions** — set a goal and round or time limits; the host schedules speakers and follow-ups, and you can produce a sourced report. See [Discussions](docs/en/guide/discussion.md).
34
34
  - **Goal** — give the host an objective; it keeps going, stops when it needs your confirmation and can remind you on WeChat. See [Goal](docs/en/guide/goal.md).
35
35
  - **Workflows** — save a fixed division of work among several agents and start it in a room with one click. See [Workflows](docs/en/guide/workflows.md).
36
+ - **Cross-room analytics** — review unassisted rates, folder activity, parallel room peaks, member scorecards and bottlenecks for today, the last 7 or 30 days, or all time, and export a local summary PNG. See [Analytics](docs/en/guide/analytics.md).
36
37
  - **Smart Scheduling** — optionally let a decision model handle routine routing instead of waking the host; it uses your own key, and the room title and recent messages are sent to the provider. See [Smart Scheduling](docs/en/guide/scheduling.md).
37
38
  - **Mix any participant** — local CLIs and desktop apps, model APIs and manually connected sessions in one room; resume existing agent sessions and give each member read-only or writable access. See [Members](docs/en/guide/members.md).
38
39
  - **Shared projects and records** — point a room at project folders and browse them; attachments, export and import between sites, and branching; destroy a room, with its members’ AI sessions, at any time or after a set idle period. See [Rooms](docs/en/guide/rooms.md).
package/README.zh-CN.md CHANGED
@@ -33,6 +33,7 @@
33
33
  - **结构化讨论**:设定目标与轮次或时长上限,主持人安排发言与追问,可生成带来源的报告。见[讨论](docs/guide/discussion.md)。
34
34
  - **Goal**:交给主持人一个目标,它持续推进,需要你确认时停下,可发微信提醒。见 [Goal](docs/guide/goal.md)。
35
35
  - **工作流**:把固定的多人分工存成工作流,在房间里一键启用。见[工作流](docs/guide/workflows.md)。
36
+ - **全房间统计**:按今日、近 7 天、近 30 天或全部时间复盘免介入率、文件夹精力分布、同时推进的房间数、成员表现与卡点,并本地导出汇总分享图。见[统计](docs/guide/analytics.md)。
36
37
  - **智能调度**:可选由决策模型处理日常分派,不必每次唤醒主持人;使用你自己的密钥,房间标题与最近消息会发给所选供应商。见[智能调度](docs/guide/scheduling.md)。
37
38
  - **混合接入**:本地 CLI 与桌面 App、模型 API、手动接入的会话同房协作;可续接已有的 AI 会话,为每位成员设置只读或可写。见[成员](docs/guide/members.md)。
38
39
  - **共享项目与记录**:为房间指定项目目录并在“文件”页浏览;附件、跨站点导出导入与分支;房间可随时或按设定期限销毁,连同成员的 AI 会话记录一起删除。见[房间目录与建房](docs/guide/rooms.md)。
@@ -0,0 +1,584 @@
1
+ """Owner-only weekly reports over the current rooms of one Python site."""
2
+ import hashlib
3
+ import json
4
+ import subprocess
5
+ from bisect import bisect_right
6
+ from collections import Counter, defaultdict
7
+ from datetime import date, datetime, time, timedelta, timezone
8
+ from functools import lru_cache
9
+ from math import floor
10
+ from time import monotonic
11
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
12
+
13
+ from .texts import Text
14
+
15
+ CACHE_SECONDS = 60
16
+ CACHE_ENTRIES = 32
17
+
18
+
19
+ # A standard Windows Python installation may have no IANA database. Node ships ICU.
20
+ NODE_CALENDAR = """
21
+ const [zone, ...dates] = process.argv.slice(1);
22
+ const calendar = new Intl.DateTimeFormat('en-CA', {timeZone: zone, year:'numeric', month:'2-digit', day:'2-digit'});
23
+ process.env.TZ = calendar.resolvedOptions().timeZone;
24
+ const result = dates.length === 1 && !dates[0].includes("-", 1) ? calendar.format(new Date(Number(dates[0]) * 60000)) :
25
+ dates.map(day => new Date(day + 'T00:00:00').getTime() / 1000);
26
+ process.stdout.write(JSON.stringify(result));
27
+ """
28
+
29
+
30
+ @lru_cache(maxsize=128)
31
+ def node_calendar(zone, *dates):
32
+ """Use bundled ICU when the host Python has no timezone files."""
33
+ try:
34
+ run = subprocess.run(["node", "-e", NODE_CALENDAR, "--", zone, *dates], capture_output=True,
35
+ text=True, timeout=5, check=True)
36
+ return json.loads(run.stdout)
37
+ except (OSError, subprocess.SubprocessError, ValueError):
38
+ raise ValueError(Text("统计日期范围或时区无效")) from None
39
+
40
+
41
+ def report_zone(name):
42
+ """Resolve the requested zone, falling back to ICU only when Python lacks a zone database."""
43
+ if name == "UTC":
44
+ return timezone.utc
45
+ try:
46
+ return ZoneInfo(name)
47
+ except ZoneInfoNotFoundError:
48
+ try:
49
+ ZoneInfo("Etc/UTC")
50
+ except ZoneInfoNotFoundError:
51
+ return None
52
+ raise
53
+
54
+
55
+ ROLLING_DAYS = {"today": 1, "7d": 7, "30d": 30}
56
+
57
+
58
+ def period(params, now, earliest=None):
59
+ """Return local calendar boundaries and their UTC timestamps.
60
+
61
+ `today`, `7d` and `30d` end tomorrow and compare with the same number of days before; `all` starts on the local
62
+ date of `earliest` (the oldest recorded activity, Unix seconds) and has an empty previous period.
63
+ """
64
+ name = params.get("tz", "UTC")
65
+ try:
66
+ zone = report_zone(name)
67
+ today = (datetime.fromtimestamp(now, zone).date() if zone is not None
68
+ else date.fromisoformat(node_calendar(name, str(int(now)//60))))
69
+ mode = params.get("range", "7d")
70
+ if mode not in ("week", "month", "all", *ROLLING_DAYS):
71
+ raise ValueError
72
+ if "from" in params or "to" in params:
73
+ start, end = (date.fromisoformat(params[key]) for key in ("from", "to"))
74
+ previous = start - (end - start)
75
+ if start.day == end.day == 1 and (end - start).days <= 31:
76
+ previous = (start - timedelta(days=1)).replace(day=1)
77
+ elif mode in ROLLING_DAYS:
78
+ end = today + timedelta(days=1)
79
+ start = end - timedelta(days=ROLLING_DAYS[mode])
80
+ previous = start - timedelta(days=ROLLING_DAYS[mode])
81
+ elif mode == "all":
82
+ end = today + timedelta(days=1)
83
+ first = (datetime.fromtimestamp(earliest, zone).date() if zone is not None and earliest
84
+ else date.fromisoformat(node_calendar(name, str(int(earliest) // 60))) if earliest else today)
85
+ start = previous = min(first, today)
86
+ elif mode == "month":
87
+ start = today.replace(day=1)
88
+ end = (start + timedelta(days=32)).replace(day=1)
89
+ previous = (start - timedelta(days=1)).replace(day=1)
90
+ else:
91
+ start = today - timedelta(days=today.weekday())
92
+ end, previous = start + timedelta(days=7), start - timedelta(days=7)
93
+ if end <= start:
94
+ raise ValueError
95
+ days = (previous, start, end)
96
+ stamps = (tuple(int(datetime.combine(day, time.min, zone).timestamp()) for day in days)
97
+ if zone is not None else tuple(node_calendar(name, *map(str, days))))
98
+ return {"tz": name, "from": str(start), "to": str(end), "previous_from": str(previous),
99
+ "previous_to": str(start)}, stamps
100
+ except (KeyError, OverflowError, ValueError, ZoneInfoNotFoundError):
101
+ raise ValueError(Text("统计日期范围或时区无效")) from None
102
+
103
+
104
+ def distribution(values, histogram=None):
105
+ """Combine exact observations with weighted anonymous bucket midpoints."""
106
+ counts = Counter(values)
107
+ for bucket, count in (histogram or {}).items():
108
+ low = int(bucket)
109
+ midpoint = (3 * low - 1) / 2 if low else 0
110
+ counts[midpoint] += count
111
+ ordered = sorted(counts.items())
112
+ total = sum(counts.values())
113
+
114
+ def sample(rank):
115
+ for seconds, weight in ordered:
116
+ if rank < weight:
117
+ return seconds
118
+ rank -= weight
119
+
120
+ def quantile(fraction):
121
+ if not total:
122
+ return None
123
+ index = (total - 1) * fraction
124
+ low = floor(index)
125
+ first = sample(low)
126
+ return round(first + (sample(min(low + 1, total - 1)) - first) * (index - low), 2)
127
+
128
+ return {"p50": quantile(.5), "p90": quantile(.9), "samples": total, "approximate": bool(histogram)}
129
+
130
+
131
+ REQUESTS = """
132
+ WITH prior AS (SELECT rr.request_id,min(e.created_at) AS dispatched
133
+ FROM retried_requests rr JOIN member_executions e ON e.id=rr.execution_id GROUP BY rr.request_id)
134
+ SELECT r.room_id,r.message_id,r.chain_id,r.created_at,r.status,mbr.name,mbr.adapter,
135
+ coalesce(l.label,mbr.name) AS label,coalesce(e.model,'') AS model,coalesce(e.effort,'') AS effort,
136
+ (m.author='用户' AND NOT EXISTS(SELECT 1 FROM message_relays l WHERE l.message_id=m.id)
137
+ AND NOT EXISTS(SELECT 1 FROM internal_task_messages i WHERE i.message_id=m.id)) AS initiated,
138
+ CAST(strftime('%s',m.created_at) AS INTEGER) AS sent,CAST(strftime('%s',a.created_at) AS INTEGER) AS answered,
139
+ coalesce(w.kind,aw.kind) AS withdrawal,e.result,c.reason,coalesce(prior.dispatched,e.created_at) AS dispatched,
140
+ CASE WHEN c.reason='user_stop' AND e.id IS NULL THEN EXISTS(
141
+ SELECT 1 FROM room_events stop JOIN room_events cancelled ON cancelled.room_id=stop.room_id
142
+ AND cancelled.kind='request.cancel_reason'
143
+ AND cancelled.at BETWEEN stop.at AND stop.at+json_extract(stop.data,'$.elapsed_ms')+1
144
+ WHERE stop.room_id=r.room_id AND stop.kind='api.write' AND json_extract(stop.data,'$.path')='/stop'
145
+ AND json_extract(cancelled.data,'$.request_id')=r.id) END AS stopped_pending
146
+ FROM member_requests r LEFT JOIN prior ON prior.request_id=r.id JOIN messages m ON m.id=r.message_id
147
+ JOIN room_members mbr ON mbr.id=r.member_id LEFT JOIN member_labels l ON l.room_id=r.room_id AND l.name=mbr.name
148
+ LEFT JOIN messages a ON a.id=r.answer_id LEFT JOIN member_executions e ON e.id=r.execution_id
149
+ LEFT JOIN request_cancel_reasons c ON c.request_id=r.id
150
+ LEFT JOIN message_withdrawals w ON w.message_id=m.id LEFT JOIN message_withdrawals aw ON aw.message_id=a.id
151
+ """
152
+
153
+
154
+ def user_stopped(row):
155
+ """Separate owner interventions from host cancellations and send-now follow-ups."""
156
+ return row["reason"] == "user_stop" and (row["stopped_pending"] or row["result"] in ("用户打断", "用户停止全部", "用户回退了对话"))
157
+
158
+
159
+ def overview_facts(rows):
160
+ """Yield additive facts with their original message or chain cohort timestamp."""
161
+ messages, chains = defaultdict(list), defaultdict(list)
162
+ for row in rows:
163
+ if row["initiated"]:
164
+ messages[row["message_id"]].append(row)
165
+ chains[row["room_id"], row["chain_id"] or row["message_id"]].append(row)
166
+ for group in messages.values():
167
+ sent = group[0]["sent"]
168
+ yield sent, "initiated", 1
169
+ if any(row["answered"] is not None for row in group):
170
+ yield sent, "answered", 1
171
+ for group in chains.values():
172
+ if any(r["status"] in ("pending", "delivering") for r in group):
173
+ continue
174
+ first = min(row["created_at"] for row in group)
175
+ yield first, "ended", 1
176
+ if not any(r["withdrawal"] or user_stopped(r) for r in group):
177
+ yield first, "unassisted", 1
178
+ answers = [r["answered"] for r in group if r["answered"] is not None]
179
+ if answers and all(r["status"] == "completed" for r in group):
180
+ yield first, "delivery", max(0, max(answers) - first)
181
+
182
+
183
+ def overview(facts, start, end, sealed):
184
+ counts, histograms = sealed
185
+ result = {key: counts[key] for key in ("initiated", "answered", "ended", "unassisted")}
186
+ durations = []
187
+ for stamp, key, value in facts:
188
+ if start <= stamp < end:
189
+ if key == "delivery":
190
+ durations.append(value)
191
+ else:
192
+ result[key] += value
193
+ delivery = distribution(durations, histograms["delivery"])
194
+ return {**result, "delivery": delivery, "coverage": {"numerator": delivery["samples"], "denominator": result["ended"]}}
195
+
196
+
197
+ def peak_concurrent(intervals):
198
+ """Union each key's intervals, then return the most keys active at once and the first moment it happened."""
199
+ events = Counter()
200
+ for spans in intervals.values():
201
+ merged = []
202
+ for start, end in sorted(spans):
203
+ if merged and start <= merged[-1][1]:
204
+ merged[-1][1] = max(merged[-1][1], end)
205
+ else:
206
+ merged.append([start, end])
207
+ for start, end in merged:
208
+ events[start] += 1
209
+ events[end] -= 1
210
+ count = peak = 0
211
+ at = None
212
+ for stamp, change in sorted(events.items()):
213
+ count += change
214
+ if count > peak:
215
+ peak, at = count, stamp
216
+ return peak, at
217
+
218
+
219
+ EXECUTIONS = """
220
+ WITH attempts AS (
221
+ SELECT request_id,execution_id FROM retried_requests
222
+ UNION ALL SELECT id,execution_id FROM member_requests WHERE execution_id IS NOT NULL
223
+ ), failed_attempts AS (
224
+ SELECT rr.request_id,min(rr.execution_id) AS first_failed FROM retried_requests rr
225
+ JOIN member_executions e ON e.id=rr.execution_id WHERE e.status='failed' GROUP BY rr.request_id
226
+ ), rework AS (
227
+ SELECT DISTINCT a.execution_id FROM attempts a JOIN failed_attempts f ON f.request_id=a.request_id
228
+ WHERE a.execution_id>f.first_failed
229
+ )
230
+ SELECT e.id,e.room_id,e.created_at,e.finished_at,e.status,e.result,e.model,e.effort,m.name,m.adapter,
231
+ coalesce(l.label,m.name) AS label,f.failure_class,
232
+ EXISTS(SELECT 1 FROM execution_denials d WHERE d.execution_id=e.id AND d.denials NOT IN ('','[]','{}')) AS denied,
233
+ (e.status='failed' AND EXISTS(SELECT 1 FROM retried_requests rr WHERE rr.execution_id=e.id)) AS retried,
234
+ (rework.execution_id IS NOT NULL) AS rework
235
+ FROM member_executions e LEFT JOIN rework ON rework.execution_id=e.id JOIN room_members m ON m.id=e.member_id
236
+ LEFT JOIN member_labels l ON l.room_id=e.room_id AND l.name=m.name
237
+ LEFT JOIN execution_failures f ON f.execution_id=e.id
238
+ WHERE e.created_at<? AND (e.created_at>=? OR e.finished_at>=? OR e.finished_at=0)
239
+ """
240
+
241
+
242
+ def member_stats(rows, requests, revived, by_model=False):
243
+ """Aggregate the underlying requests and executions, including pooled model duration samples."""
244
+ groups = {}
245
+ identity = ("adapter", "model", "effort") if by_model else ("room_id", "name", "adapter", "model", "effort")
246
+
247
+ def bucket(row):
248
+ key = tuple(row[field] for field in identity)
249
+ if key not in groups:
250
+ item = {field: row[field] for field in ("adapter", "model", "effort")}
251
+ if not by_model:
252
+ item.update(room_id=row["room_id"], member=row["name"], label=row["label"])
253
+ item.update(accepted=0, executions=0, completed=0, failed=0, cancelled=0, interrupted=0,
254
+ retries=0, denied=0, revived=0, failures=Counter(), durations=[])
255
+ groups[key] = item
256
+ return groups[key]
257
+
258
+ for row in requests:
259
+ bucket(row)["accepted"] += 1
260
+ for r in rows:
261
+ item = bucket(r)
262
+ item["executions"] += 1
263
+ if r["status"] in ("completed", "failed", "cancelled"):
264
+ item[r["status"]] += 1
265
+ if r["failure_class"] and r["status"] == "failed":
266
+ item["failures"][r["failure_class"]] += 1
267
+ item["interrupted"] += r["status"] == "cancelled" and r["result"] in ("用户打断", "用户停止全部")
268
+ item["retries"] += r["retried"]
269
+ item["denied"] += r["denied"]
270
+ item["revived"] += r["id"] in revived and r["status"] == "completed"
271
+ if r["finished_at"] >= r["created_at"] and r["finished_at"]:
272
+ item["durations"].append(r["finished_at"] - r["created_at"])
273
+ for item in groups.values():
274
+ item["duration"] = distribution(item.pop("durations"))
275
+ return list(groups.values())
276
+
277
+
278
+ def workflow_stats(connection, rows):
279
+ """Executions run under a room workflow, grouped by workflow ID (current rooms only).
280
+
281
+ The runner reports each delivery's workflow binding into the execution's diagnostics; an execution that reported
282
+ several keeps its last one. Card and sub-workflow counts say which parts of the workflow actually ran.
283
+ """
284
+ ids = [r["id"] for r in rows]
285
+ bound = {}
286
+ for offset in range(0, len(ids), 500):
287
+ chunk = ids[offset:offset + 500]
288
+ marks = ",".join("?" * len(chunk))
289
+ for execution_id, details in connection.execute(
290
+ f"SELECT execution_id,details FROM execution_diagnostics WHERE execution_id IN ({marks})", chunk):
291
+ try:
292
+ bindings = [item for item in json.loads(details).get("workflow_bindings") or [] if item]
293
+ except (TypeError, ValueError, AttributeError):
294
+ continue
295
+ if bindings:
296
+ bound[execution_id] = bindings[-1]
297
+ groups = {}
298
+ for r in rows:
299
+ binding = bound.get(r["id"])
300
+ if not binding:
301
+ continue
302
+ item = groups.setdefault(binding["id"], dict(id=binding["id"], executions=0, completed=0, failed=0, cancelled=0,
303
+ interrupted=0, rooms=set(), cards=Counter(), sub_workflows=Counter(),
304
+ durations=[]))
305
+ item["executions"] += 1
306
+ if r["status"] in ("completed", "failed", "cancelled"):
307
+ item[r["status"]] += 1
308
+ item["interrupted"] += r["status"] == "cancelled" and r["result"] in ("用户打断", "用户停止全部")
309
+ item["rooms"].add(r["room_id"])
310
+ if binding.get("card"):
311
+ item["cards"][binding["card"]] += 1
312
+ if binding.get("sub_workflow"):
313
+ item["sub_workflows"][binding["sub_workflow"]] += 1
314
+ if r["finished_at"] >= r["created_at"] and r["finished_at"]:
315
+ item["durations"].append(r["finished_at"] - r["created_at"])
316
+ result = []
317
+ for item in groups.values():
318
+ item["rooms"] = len(item["rooms"])
319
+ item["cards"], item["sub_workflows"] = dict(item["cards"]), dict(item["sub_workflows"])
320
+ item["duration"] = distribution(item.pop("durations"))
321
+ result.append(item)
322
+ return sorted(result, key=lambda item: (-item["executions"], item["id"]))
323
+
324
+
325
+ def insights(connection, members, start, end):
326
+ """Return observed counts with denominators and drill-down keys."""
327
+ result = []
328
+ def add(rule, count, total, params, target):
329
+ if count >= 3 and total >= 10:
330
+ result.append(dict(rule=rule, numerator=count, denominator=total, params=params, target=target))
331
+ for item in members:
332
+ target = {k: item[k] for k in ("room_id", "member", "adapter", "model", "effort")}
333
+ for kind, count in item["failures"].items():
334
+ add("failure_cluster", count, item["executions"], {"failure_class": kind}, target)
335
+ for rule, key in (("permission_denial", "denied"), ("late_recovery", "revived")):
336
+ add(rule, item[key], item["executions"], {}, target)
337
+ for room, bad, total in connection.execute("""SELECT d.room_id,sum(f.rating='bad'),count(*)
338
+ FROM scheduler_feedback f JOIN scheduler_decisions d ON d.id=f.decision_id
339
+ WHERE CAST(strftime('%s',f.created_at) AS INTEGER)>=? AND CAST(strftime('%s',f.created_at) AS INTEGER)<? GROUP BY d.room_id""", (start, end)):
340
+ add("scheduler_feedback", bad, total, {}, {"room_id": room})
341
+ return result
342
+
343
+
344
+ def time_stats(connection, requests, executions, bounds, now, sealed):
345
+ """Summarize folder activity, observed waiting and the current message queue."""
346
+ start, end = bounds
347
+ counts, histograms = sealed
348
+ folders, room_folder, room_rows = {}, {}, {}
349
+ for room, title, folder, name in connection.execute("""SELECT r.id,r.title,f.id,f.name FROM rooms r
350
+ LEFT JOIN room_folder_assignments a ON a.room_id=r.id LEFT JOIN topic_folders f ON f.id=a.folder_id"""):
351
+ room_folder[room] = folder
352
+ folders.setdefault(folder, dict(folder_id=folder, name=name, initiated=0, execution_seconds=0))
353
+ room_rows[room] = dict(room_id=room, title=title, folder_id=folder, initiated=0, execution_seconds=0)
354
+ seen, waits = set(), []
355
+ for r in requests:
356
+ if r["initiated"] and start <= r["sent"] < end and r["message_id"] not in seen:
357
+ folders[room_folder[r["room_id"]]]["initiated"] += 1
358
+ room_rows[r["room_id"]]["initiated"] += 1
359
+ seen.add(r["message_id"])
360
+ if start <= r["created_at"] < end and r["dispatched"] is not None and r["dispatched"] >= r["created_at"]:
361
+ waits.append(r["dispatched"] - r["created_at"])
362
+ spans, member_spans = defaultdict(list), defaultdict(list)
363
+ elapsed, rework = [], []
364
+ for r in executions:
365
+ left, right = max(start, r["created_at"]), min(end, r["finished_at"] or now, now)
366
+ if left < right:
367
+ spans[r["room_id"]].append((left, right))
368
+ member_spans[(r["room_id"], r["name"])].append((left, right))
369
+ folders[room_folder[r["room_id"]]]["execution_seconds"] += right-left
370
+ room_rows[r["room_id"]]["execution_seconds"] += right-left
371
+ if start <= r["created_at"] and r["finished_at"] >= r["created_at"] and r["finished_at"]:
372
+ duration = r["finished_at"] - r["created_at"]
373
+ elapsed.append(duration)
374
+ if r["rework"]:
375
+ rework.append(duration)
376
+ count, oldest = connection.execute("SELECT count(*),min(created_at) FROM queued_messages").fetchone()
377
+ rooms, rooms_at = peak_concurrent(spans)
378
+ members, members_at = peak_concurrent(member_spans)
379
+ peak = {"rooms": rooms, "at": rooms_at, "members": members, "members_at": members_at}
380
+ active_rooms = [room for room in room_rows.values() if room["initiated"] or room["execution_seconds"]]
381
+ return {"folders": list(folders.values()), "rooms": active_rooms, "peak": peak, "sealed_execution_seconds": counts["execution_seconds"],
382
+ "execution_seconds": sum(f["execution_seconds"] for f in folders.values()) + counts["execution_seconds"],
383
+ "waiting": distribution(waits, histograms["waiting"]),
384
+ "execution": distribution(elapsed, histograms["execution"]), "rework": distribution(rework, histograms["rework"]),
385
+ "queue": {"count": count, "oldest_seconds": max(0, now-oldest) if count else None}}
386
+
387
+
388
+ def actions(connection, start, end):
389
+ """Count corrections by operation and rewound requests separately."""
390
+ def count(sql):
391
+ return connection.execute(sql, (start, end)).fetchone()[0]
392
+ rewind = count("SELECT count(*) FROM room_rewinds WHERE created_at>=? AND created_at<?")
393
+ affected = count("""WITH window(lo,hi) AS (VALUES(?,?))
394
+ SELECT count(*) FROM member_requests r CROSS JOIN window
395
+ LEFT JOIN member_executions e ON e.id=r.execution_id
396
+ WHERE (e.result='用户回退了对话' AND e.status='cancelled' AND e.finished_at>=lo AND e.finished_at<hi)
397
+ OR EXISTS(SELECT 1 FROM message_withdrawals w WHERE w.message_id IN (r.message_id,r.answer_id)
398
+ AND w.kind='rewound' AND w.created_at>=lo AND w.created_at<hi)""")
399
+ retract = count("SELECT count(*) FROM message_withdrawals WHERE kind='retracted' AND created_at>=? AND created_at<?")
400
+ stops = count("""SELECT count(*) FROM room_events WHERE at>=?*1000 AND at<?*1000 AND kind='api.write'
401
+ AND json_extract(data,'$.path')='/stop'""")
402
+ stops += count("""SELECT count(*) FROM room_events WHERE at>=?*1000 AND at<?*1000 AND kind='execution.changed'
403
+ AND json_extract(data,'$.status')='cancelled' AND json_extract(data,'$.result')='用户打断'""")
404
+ extra = count("""SELECT count(*) FROM execution_interjections i LEFT JOIN interjection_authors a ON a.interjection_id=i.id
405
+ WHERE a.interjection_id IS NULL AND i.created_at>=? AND i.created_at<?""")
406
+ return {"corrections": {"stops": stops, "withdrawals": retract, "rewinds": rewind, "affected_requests": affected},
407
+ "additions": {"interjections": extra}}
408
+
409
+
410
+ DAY_SECONDS = 86400
411
+ SEALED_DISTRIBUTIONS = ("delivery", "waiting", "execution", "rework")
412
+ SEALED_COUNTS = ("initiated", "answered", "ended", "unassisted", "execution_seconds", "rewinds",
413
+ "withdrawals", "stops", "interjections")
414
+
415
+
416
+ def archive_key(room_id, secret):
417
+ """Compute a private join key for idempotence and same-ID restores."""
418
+ return hashlib.blake2b(room_id.encode(), key=bytes.fromhex(secret), digest_size=20).hexdigest()
419
+
420
+
421
+ def room_time_facts(connection, room_id, rows, now):
422
+ for row in rows:
423
+ sent, dispatched = row["created_at"], row["dispatched"]
424
+ if dispatched is not None and dispatched >= sent:
425
+ yield sent, "waiting", dispatched - sent
426
+ query = EXECUTIONS + " AND e.room_id=?"
427
+ for row in connection.execute(query, (now+1, 0, 0, room_id)):
428
+ start, end = row["created_at"], row["finished_at"]
429
+ if end and end >= start:
430
+ yield start, "execution", end - start
431
+ if row["rework"]:
432
+ yield start, "rework", end - start
433
+ limit = min(end or now, now)
434
+ while start < limit:
435
+ boundary = min((start // DAY_SECONDS + 1) * DAY_SECONDS, limit)
436
+ yield start, "execution_seconds", boundary - start
437
+ start = boundary
438
+
439
+
440
+ ARCHIVE_ACTIONS = """
441
+ SELECT created_at,'rewinds',1 FROM room_rewinds WHERE room_id=:room
442
+ UNION ALL SELECT w.created_at,'withdrawals',1 FROM message_withdrawals w JOIN messages m ON m.id=w.message_id
443
+ WHERE m.room_id=:room AND w.kind='retracted'
444
+ UNION ALL SELECT i.created_at,'interjections',1 FROM execution_interjections i
445
+ LEFT JOIN interjection_authors a ON a.interjection_id=i.id WHERE i.room_id=:room AND a.interjection_id IS NULL
446
+ UNION ALL SELECT at/1000,'stops',1 FROM room_events WHERE room_id=:room AND
447
+ ((kind='api.write' AND json_extract(data,'$.path')='/stop') OR (kind='execution.changed'
448
+ AND json_extract(data,'$.status')='cancelled' AND json_extract(data,'$.result')='用户打断'))
449
+ """
450
+
451
+
452
+ def seal_room(connection, room_id, now):
453
+ """Replace this room's anonymous daily contribution within the destruction transaction."""
454
+ connection.execute("INSERT OR IGNORE INTO site_preferences VALUES ('analytics_salt',hex(randomblob(32)))")
455
+ secret = connection.execute("SELECT value FROM site_preferences WHERE key='analytics_salt'").fetchone()[0]
456
+ key = archive_key(room_id, secret)
457
+ rows = connection.execute(REQUESTS + " WHERE r.room_id=?", (room_id,)).fetchall()
458
+ days = defaultdict(lambda: (Counter(), defaultdict(Counter)))
459
+ for facts in (overview_facts(rows), room_time_facts(connection, room_id, rows, now),
460
+ connection.execute(ARCHIVE_ACTIONS, {"room": room_id})):
461
+ for stamp, metric, value in facts:
462
+ if stamp is None:
463
+ continue
464
+ day = datetime.fromtimestamp(stamp, timezone.utc).date().isoformat()
465
+ counts, histograms = days[day]
466
+ if metric in SEALED_DISTRIBUTIONS:
467
+ bucket = 1 << (int(value).bit_length() - 1) if value else 0
468
+ histograms[metric][bucket] += 1
469
+ else:
470
+ counts[metric] += value
471
+ # An empty room contributes only to the total number of retained rooms.
472
+ if not days:
473
+ days[datetime.fromtimestamp(now, timezone.utc).date().isoformat()]
474
+ connection.execute("""INSERT INTO site_preferences VALUES ('analytics_revision','1')
475
+ ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1""")
476
+ connection.execute("DELETE FROM analytics_sealed_days WHERE archive_key=?", (key,))
477
+ connection.executemany("INSERT INTO analytics_sealed_days VALUES (?,?,?,?)",
478
+ [(key, day, json.dumps(counts), json.dumps(hist)) for day, (counts, hist) in days.items()])
479
+
480
+
481
+ def sealed_periods(connection, mode, rooms, dates):
482
+ periods = [(Counter(), defaultdict(Counter)) for _ in range(2)]
483
+ daily = defaultdict(Counter)
484
+ if mode == "current":
485
+ return periods, 0, daily
486
+ salt = connection.execute("SELECT value FROM site_preferences WHERE key='analytics_salt'").fetchone()
487
+ if not salt:
488
+ return periods, 0, daily
489
+ live = {archive_key(room_id, salt[0]) for room_id in rooms}
490
+ retained = {r[0] for r in connection.execute("SELECT DISTINCT archive_key FROM analytics_sealed_days")} - live
491
+ for key, day, counts, hist in connection.execute("""SELECT archive_key,day,counts,histograms
492
+ FROM analytics_sealed_days WHERE day>=? AND day<?""", (dates["previous_from"], dates["to"])):
493
+ if key not in retained:
494
+ continue
495
+ totals, bins = periods[int(day >= dates["from"])]
496
+ counts = json.loads(counts)
497
+ totals.update(counts)
498
+ if day >= dates["from"]:
499
+ daily[day].update(counts)
500
+ for name, weights in json.loads(hist).items():
501
+ bins[name].update(weights)
502
+ return periods, len(retained), daily
503
+
504
+
505
+ def daily_overview(dates, facts, executions, sealed_days, now):
506
+ """Split running intervals at local midnight, including 23- and 25-hour days."""
507
+ first, end = map(date.fromisoformat, (dates["from"], dates["to"]))
508
+ days = [first + timedelta(days=i) for i in range((end-first).days + 1)]
509
+ zone = report_zone(dates["tz"])
510
+ if zone is not None:
511
+ bounds = [int(datetime.combine(day, time.min, zone).timestamp()) for day in days]
512
+ else:
513
+ # Limit each ICU subprocess command line on Windows.
514
+ bounds = []
515
+ for offset in range(0, len(days), 100):
516
+ bounds.extend(node_calendar(dates["tz"], *map(str, days[offset:offset+100])))
517
+ rows = []
518
+ for day in days[:-1]:
519
+ label = str(day)
520
+ counts = sealed_days.get(label, {})
521
+ rows.append({"date": label, **{k: counts.get(k, 0) for k in ("initiated", "ended", "unassisted", "execution_seconds")}})
522
+ for stamp, key, value in facts:
523
+ if key in ("initiated", "ended", "unassisted") and bounds[0] <= stamp < bounds[-1]:
524
+ rows[bisect_right(bounds, stamp)-1][key] += value
525
+ for row in executions:
526
+ left = max(bounds[0], row["created_at"])
527
+ right = min(bounds[-1], row["finished_at"] or now, now)
528
+ index = bisect_right(bounds, left)-1
529
+ while left < right:
530
+ boundary = min(right, bounds[index+1])
531
+ rows[index]["execution_seconds"] += boundary-left
532
+ left, index = boundary, index+1
533
+ return rows
534
+
535
+
536
+ def snapshot(connection, params, cache, now):
537
+ """Build one SQLite read snapshot, caching only within the same server and room scope."""
538
+ earliest = None
539
+ if params.get("range") == "all" and "from" not in params and "to" not in params:
540
+ first = connection.execute("SELECT MIN(created_at) FROM member_requests").fetchone()[0]
541
+ sealed_first = connection.execute("SELECT MIN(day) FROM analytics_sealed_days").fetchone()[0]
542
+ candidates = [int(first)] if first else []
543
+ if sealed_first:
544
+ candidates.append(int(datetime.combine(date.fromisoformat(sealed_first), time.min, timezone.utc).timestamp()))
545
+ earliest = min(candidates) if candidates else None
546
+ dates, (previous, start, end) = period(params, now, earliest)
547
+ mode = params.get("scope", "all")
548
+ if mode not in ("all", "current"):
549
+ raise ValueError("scope ∈ {all, current}")
550
+ connection.execute("BEGIN")
551
+ rooms = tuple(r[0] for r in connection.execute("SELECT id FROM rooms ORDER BY id"))
552
+ revision = connection.execute("SELECT value FROM site_preferences WHERE key='analytics_revision'").fetchone()
553
+ key = (tuple(dates.values()), rooms, mode, revision[0] if revision else None)
554
+ hit = cache.get(key)
555
+ if hit and monotonic() < hit[0]:
556
+ return hit[1]
557
+ requests = connection.execute(REQUESTS).fetchall()
558
+ executions = connection.execute(EXECUTIONS, (end, start, start)).fetchall()
559
+ revived = {r[0] for r in connection.execute("""SELECT DISTINCT json_extract(data,'$.execution_id') FROM room_events
560
+ WHERE kind='execution.changed' AND json_extract(data,'$.from_status')='failed' AND json_extract(data,'$.status')='started'""")}
561
+ attempts = [r for r in executions if r["created_at"] >= start]
562
+ assigned = [r for r in requests if start <= r["created_at"] < end]
563
+ members = member_stats(attempts, assigned, revived)
564
+ models = member_stats(attempts, assigned, revived, by_model=True)
565
+ (prior, sealed), retained, sealed_days = sealed_periods(connection, mode, rooms, dates)
566
+ facts = list(overview_facts(requests))
567
+ activity = actions(connection, start, end)
568
+ for group in activity.values():
569
+ for name in group:
570
+ group[name] += sealed[0][name]
571
+ scope = {"mode": mode, "rooms": len(rooms), "sealed_rooms": retained, "included_rooms": len(rooms) + retained,
572
+ "includes_archived": True, "sealed_day_tz": "UTC", "sealed_counts": SEALED_COUNTS,
573
+ "sealed_distributions": SEALED_DISTRIBUTIONS,
574
+ "current_only": ["folders", "rooms", "peak", "queue", "affected_requests", "members", "models", "workflows", "insights"]}
575
+ result = dict(range=dates, scope=scope,
576
+ overview=overview(facts, start, end, sealed), previous=overview(facts, previous, start, prior),
577
+ time={**time_stats(connection, requests, executions, (start, end), now, sealed), **activity},
578
+ members=members, models=models, workflows=workflow_stats(connection, attempts),
579
+ insights=insights(connection, members, start, end))
580
+ result["overview"]["daily"] = daily_overview(dates, facts, executions, sealed_days, now)
581
+ if len(cache) >= CACHE_ENTRIES:
582
+ cache.clear()
583
+ cache[key] = (monotonic() + CACHE_SECONDS, result)
584
+ return result