EnergyVenom commited on
Commit
bf49cd0
·
verified ·
1 Parent(s): ac62d72

Deploy 035e2c0: state keeps screens and library; Telegram details

Browse files
coworker/channels/core.py CHANGED
@@ -47,6 +47,7 @@ class Button:
47
  class OutMessage:
48
  text: str # plain text: the adapter escapes it for its platform
49
  buttons: list[list[Button]] = field(default_factory=list)
 
50
 
51
 
52
  @dataclass
 
47
  class OutMessage:
48
  text: str # plain text: the adapter escapes it for its platform
49
  buttons: list[list[Button]] = field(default_factory=list)
50
+ html: bool = False # the text is Telegram HTML already (a notification laid out by notify.telegram_text)
51
 
52
 
53
  @dataclass
coworker/channels/telegram.py CHANGED
@@ -70,7 +70,8 @@ class TelegramAdapter(Adapter):
70
  return self._me or None
71
 
72
  def send(self, chat_id: str, msg: OutMessage) -> str | None:
73
- body: dict = {"chat_id": chat_id, "text": escape(msg.text), "parse_mode": "HTML", "disable_web_page_preview": True}
 
74
  rows = [[_button(b) for b in row if b.callback or (b.url or "").startswith("https://")] for row in msg.buttons]
75
  rows = [r for r in rows if r]
76
  if rows:
@@ -234,8 +235,7 @@ def _deliver_one(svc, adapter: TelegramAdapter, conv: Conversation, chat: Inboun
234
  d = {"attempts": 0}
235
  attempts = int(d.get("attempts") or 0) + 1
236
  try:
237
- text = f"{e.get('coworker') or 'Patchwise'}\n{e.get('title') or ''}" + (f"\n{e['body']}" if e.get("body") else "")
238
- adapter.send(chat.chat_id, OutMessage(text, notification_buttons(conv, chat, user, e)))
239
  svc.db.x("UPDATE channel_deliveries SET delivered_at=?, attempts=?, last_error=NULL WHERE event_id=? AND channel=? AND chat_id=?",
240
  (now_iso(), attempts, *key))
241
  svc.audit.append("notify.delivered", actor="system", run_id=e.get("run_id"), summary=f"{e['kind']} #{e['id']} -> telegram (linked)",
 
70
  return self._me or None
71
 
72
  def send(self, chat_id: str, msg: OutMessage) -> str | None:
73
+ body: dict = {"chat_id": chat_id, "text": msg.text if msg.html else escape(msg.text), "parse_mode": "HTML",
74
+ "disable_web_page_preview": True}
75
  rows = [[_button(b) for b in row if b.callback or (b.url or "").startswith("https://")] for row in msg.buttons]
76
  rows = [r for r in rows if r]
77
  if rows:
 
235
  d = {"attempts": 0}
236
  attempts = int(d.get("attempts") or 0) + 1
237
  try:
238
+ adapter.send(chat.chat_id, OutMessage(notify.telegram_text(e), notification_buttons(conv, chat, user, e), html=True))
 
239
  svc.db.x("UPDATE channel_deliveries SET delivered_at=?, attempts=?, last_error=NULL WHERE event_id=? AND channel=? AND chat_id=?",
240
  (now_iso(), attempts, *key))
241
  svc.audit.append("notify.delivered", actor="system", run_id=e.get("run_id"), summary=f"{e['kind']} #{e['id']} -> telegram (linked)",
coworker/graph/nodes/ai_scenarios.py CHANGED
@@ -149,7 +149,9 @@ def _read_missing_screens(state, svc, reg, pod_id: int, areas: list[str]) -> Non
149
  pod = reg.get(pod_id)
150
  read = (pod.get("screens") or {}).get("areas") or {}
151
  release = pod.get("release")
152
- missing = [a for a in areas if not (read.get(a) or {}).get("captured") or (release and (read.get(a) or {}).get("release") not in (None, release))]
 
 
153
  if not missing:
154
  return
155
  run_id = state["run_id"]
 
149
  pod = reg.get(pod_id)
150
  read = (pod.get("screens") or {}).get("areas") or {}
151
  release = pod.get("release")
152
+ # an area counts as read only when its screen files are there too (an old restart could lose them, the row stayed)
153
+ missing = [a for a in areas if not (read.get(a) or {}).get("captured") or not reg.area_screens(pod_id, a)
154
+ or (release and (read.get(a) or {}).get("release") not in (None, release))]
155
  if not missing:
156
  return
157
  run_id = state["run_id"]
coworker/platform/notify.py CHANGED
@@ -115,12 +115,43 @@ def _hide(token: str, text: str) -> str:
115
  return text.replace(token, "(hidden)") if token else text
116
 
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  def telegram_text(row: dict) -> str:
119
- """The message as Telegram shows it (HTML parse mode): the coworker in bold, then the title and the body."""
120
- parts = [f"<b>{escape(str(row.get('coworker') or 'Patchwise'))}</b>", escape(str(row.get("title") or ""))]
121
- if row.get("body"):
122
- parts.append(escape(str(row["body"])))
123
- return "\n".join(parts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
 
126
  def telegram_message(chat_id: str, row: dict) -> dict:
@@ -147,6 +178,18 @@ def _run_title(run: dict) -> str:
147
  return run_name(run) or run.get("run_id", "Test run")
148
 
149
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  def _decisions(run: dict) -> dict:
151
  d = run.get("decisions") or {}
152
  if isinstance(d, str):
@@ -198,7 +241,8 @@ class Notifier:
198
  base = (self.cfg.public_url or "").rstrip("/")
199
  link = f"{base}{path}" if base else path
200
  row = {"kind": kind, "run_id": (run or {}).get("run_id"), "title": title, "body": body,
201
- "coworker": COWORKER.get(kind, "Patchwise"), "link": link, "created_at": now_iso()}
 
202
  with self.db.tx() as c:
203
  cur = c.execute("INSERT INTO notify_events (kind, run_id, title, body, coworker, link, payload_json, created_at, next_attempt_at) "
204
  "VALUES (?,?,?,?,?,?,?,?,?)",
@@ -209,6 +253,79 @@ class Notifier:
209
  log.exception("could not record notification %s", kind)
210
  return None
211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  def _clean(self, text: str) -> str:
213
  """Error sentences can quote what a system answered: take out anything that looks like a secret or a name."""
214
  try:
 
115
  return text.replace(token, "(hidden)") if token else text
116
 
117
 
118
+ TG_ICON = {"run.waiting_approval": "\U0001F4DD", "run.waiting_decision": "\u26A0\uFE0F", "run.failed": "\U0001F6D1",
119
+ "run.stopped": "\u23F9\uFE0F", "defect.created": "\U0001F41E", "test": "\U0001F514", "channel.telegram": "\U0001F517"}
120
+ TG_VERDICT_ICON = {"Ready": "\u2705", "Not ready": "\u274C", "Held": "\u23F8\uFE0F"}
121
+ FLOW_NOTE = re.compile(r"^(.+?): (\d+) end-to-end flow\(s\) designed across (.+?)\.?$")
122
+ TG_MAX = 3900 # Telegram takes 4096 characters; the rest is the button
123
+
124
+
125
+ def _details(row: dict) -> dict:
126
+ d = row.get("details")
127
+ if d is None:
128
+ try:
129
+ d = json.loads(row.get("payload_json") or "{}").get("details")
130
+ except (ValueError, AttributeError):
131
+ d = None
132
+ return d if isinstance(d, dict) else {}
133
+
134
+
135
  def telegram_text(row: dict) -> str:
136
+ """The message as Telegram shows it (HTML parse mode), laid out for a phone: an icon and the title in bold; the run's
137
+ facts (environment, release, areas, run type, time); a section per kind of result (each area's verdict, the AI's
138
+ scenarios and their dry run, the counts); what to do next; and the coworker who speaks, in italics."""
139
+ d = _details(row)
140
+ icon = d.get("icon") or TG_ICON.get(str(row.get("kind") or ""), "")
141
+ out = [f"{icon} <b>{escape(str(d.get('headline') or row.get('title') or ''))}</b>".strip()]
142
+ facts = [f"<b>{escape(str(k))}:</b> {escape(str(v))}" for k, v in d.get("facts") or [] if v not in (None, "")]
143
+ if facts:
144
+ out += ["", *facts]
145
+ for sec in d.get("sections") or []:
146
+ lines = [str(x) for x in sec.get("lines") or [] if x]
147
+ if lines:
148
+ out += ["", f"<b>{escape(str(sec.get('title') or ''))}</b>", *(f"\u2022 {escape(x)}" for x in lines)]
149
+ nxt = d.get("next", row.get("body"))
150
+ if nxt:
151
+ out += ["", f"\U0001F449 {escape(str(nxt))}"]
152
+ out += ["", f"<i>\u2014 {escape(str(row.get('coworker') or 'Patchwise'))}</i>"]
153
+ text = "\n".join(out)
154
+ return text if len(text) <= TG_MAX else text[:TG_MAX].rsplit("\n", 1)[0] + "\n\u2026"
155
 
156
 
157
  def telegram_message(chat_id: str, row: dict) -> dict:
 
178
  return run_name(run) or run.get("run_id", "Test run")
179
 
180
 
181
+ def _duration(start: Any) -> str:
182
+ """"1 h 19 min" from the run's start to now."""
183
+ try:
184
+ t = datetime.fromisoformat(str(start or "").replace("Z", "+00:00"))
185
+ except ValueError:
186
+ return ""
187
+ if t.tzinfo is None:
188
+ t = t.replace(tzinfo=timezone.utc)
189
+ mins = max(0, int((datetime.now(timezone.utc) - t).total_seconds() // 60))
190
+ return f"{mins // 60} h {mins % 60} min" if mins >= 60 else f"{mins} min"
191
+
192
+
193
  def _decisions(run: dict) -> dict:
194
  d = run.get("decisions") or {}
195
  if isinstance(d, str):
 
241
  base = (self.cfg.public_url or "").rstrip("/")
242
  link = f"{base}{path}" if base else path
243
  row = {"kind": kind, "run_id": (run or {}).get("run_id"), "title": title, "body": body,
244
+ "coworker": COWORKER.get(kind, "Patchwise"), "link": link, "created_at": now_iso(),
245
+ "details": self._run_details(kind, run or {}, extra)}
246
  with self.db.tx() as c:
247
  cur = c.execute("INSERT INTO notify_events (kind, run_id, title, body, coworker, link, payload_json, created_at, next_attempt_at) "
248
  "VALUES (?,?,?,?,?,?,?,?,?)",
 
253
  log.exception("could not record notification %s", kind)
254
  return None
255
 
256
+ def _area_name(self, code: str) -> str:
257
+ from . import fusion_catalog
258
+ a = fusion_catalog.by_code(code, self.cfg.home) if code else None
259
+ return a["name"] if a else _area(code)
260
+
261
+ def _run_details(self, kind: str, run: dict, extra: dict) -> dict:
262
+ """What a person wants to see about the run without opening the app: where it ran, on which release, which
263
+ areas, how long it took, and the results so far. Names and counts only: never test data values or secrets.
264
+ Never raises: a message without details is better than no message."""
265
+ try:
266
+ return self._details_of(kind, run, extra)
267
+ except Exception: # noqa: BLE001
268
+ log.exception("could not gather the details of %s", kind)
269
+ return {}
270
+
271
+ def _details_of(self, kind: str, run: dict, extra: dict) -> dict:
272
+ rid = run.get("run_id")
273
+ if not rid or kind in ("test", "channel.telegram"):
274
+ return {}
275
+ pod = self.db.one("SELECT name, kind FROM pods WHERE id=?", (run["pod_id"],)) if run.get("pod_id") else None
276
+ mods = [str(m) for m in run.get("modules") or []]
277
+ facts: list[list[str]] = [
278
+ ["Environment", f"{pod['name']} ({'Oracle Fusion' if pod['kind'] == 'fusion' else 'practice app'})" if pod else ""],
279
+ ["Release", str(run.get("patch_id") or "")],
280
+ ["Areas", ", ".join(self._area_name(m) for m in mods) if mods else "All areas"],
281
+ ["Run type", "Full browser run" if run.get("playwright_mode", "live") == "live" else "Quick simulation"],
282
+ ]
283
+ took = _duration(run.get("created_at"))
284
+ if took:
285
+ facts.append(["Took" if kind in ("run.finished", "run.failed", "run.stopped") else "Running for", took])
286
+ sections: list[dict] = []
287
+ notes = [e.get("summary") or {} for e in self.db.q("SELECT summary FROM run_events WHERE run_id=? AND kind='ai_scenarios' "
288
+ "ORDER BY seq", (rid,))]
289
+ per_area = [n for n in notes if isinstance(n, dict) and n.get("module") and "written" in n]
290
+ if per_area:
291
+ sections.append({"title": "AI-written scenarios (dry run on the pod)",
292
+ "lines": [f"{self._area_name(n['module'])}: {n['written']} written, {n.get('passed', 0)} passed"
293
+ for n in per_area]})
294
+ found = [FLOW_NOTE.match(str(n.get("message") or "")) for n in notes if isinstance(n, dict)]
295
+ flows = [f"{f[1]}: {f[2]} designed (" + " \u2192 ".join(self._area_name(a.strip()) for a in f[3].split(",")) + ")"
296
+ for f in found if f]
297
+ if flows:
298
+ sections.append({"title": "End-to-end flows", "lines": flows})
299
+ out: dict = {"facts": facts, "sections": sections}
300
+ # the run's name is in the facts already: the headline says only what happened
301
+ headline = {"run.waiting_approval": "Scenarios are ready for your approval",
302
+ "run.waiting_decision": "Failures need your decision",
303
+ "run.failed": "The test run stopped with a problem",
304
+ "run.stopped": "The test run was stopped"}.get(kind)
305
+ icon = None
306
+ if kind == "run.finished":
307
+ d = _decisions(run)
308
+ headline = "The test run has finished"
309
+ if d:
310
+ sections.insert(0, {"title": "Readiness per area",
311
+ "lines": [f"{TG_VERDICT_ICON.get(DECISION_WORDS.get(v, v), '')} {self._area_name(m)}: "
312
+ f"{DECISION_WORDS.get(v, v)}".strip() for m, v in d.items()]})
313
+ icon = "\u274C" if "NO-GO" in d.values() else "\u23F8\uFE0F" if "HELD" in d.values() else "\u2705"
314
+ headline = "Test run finished: " + ("Not ready" if "NO-GO" in d.values() else "Held" if "HELD" in d.values() else "Ready")
315
+ out["next"] = "Sign-off is yours: open the report to review and sign it."
316
+ c = run.get("counts") if isinstance(run.get("counts"), dict) else {}
317
+ if c.get("total") is not None:
318
+ parts = [f"{c.get('total', 0)} in scope", f"{c.get('executed', 0)} run", f"{c.get('passed', 0)} passed",
319
+ f"{c.get('failed', 0)} failed"]
320
+ parts += [f"{c[k]} {w}" for k, w in (("flaky", "passed on retry"), ("skipped", "skipped"), ("deferred", "deferred"))
321
+ if c.get(k)]
322
+ sections.insert(1 if d else 0, {"title": "Scenarios", "lines": [", ".join(parts)]})
323
+ if icon:
324
+ out["icon"] = icon
325
+ if headline:
326
+ out["headline"] = headline
327
+ return out
328
+
329
  def _clean(self, text: str) -> str:
330
  """Error sentences can quote what a system answered: take out anything that looks like a secret or a name."""
331
  try:
coworker/platform/statesync.py CHANGED
@@ -31,7 +31,10 @@ OBJECT, META = "state/latest.bin", "state/meta.json"
31
  PREVIOUS = "state/previous.bin" # the archive that was in the bucket when this process made its first save
32
  FAILED_MARKER = ".state-restore-failed" # written at boot when the saved state could not be read; blocks saving
33
  DATABASES = ("fpt.sqlite", "checkpoints.sqlite")
34
- FOLDERS = ("secrets", "runs", "evidence", "tickets")
 
 
 
35
  MAX_BYTES = 45 * 1024 * 1024 # Supabase's free plan rejects objects above 50 MB
36
 
37
 
@@ -89,9 +92,9 @@ def build_archive(home: Path, include_evidence: bool = True, skip_runs: set[str]
89
  tar.add(str(child), arcname=f"runs/{child.name}")
90
  elif p.is_dir():
91
  tar.add(str(p), arcname=folder)
92
- anchors = home / "logs" / "audit-anchors.jsonl"
93
- if anchors.is_file():
94
- tar.add(str(anchors), arcname="logs/audit-anchors.jsonl")
95
  return buf.getvalue()
96
 
97
 
 
31
  PREVIOUS = "state/previous.bin" # the archive that was in the bucket when this process made its first save
32
  FAILED_MARKER = ".state-restore-failed" # written at boot when the saved state could not be read; blocks saving
33
  DATABASES = ("fpt.sqlite", "checkpoints.sqlite")
34
+ # screens: what the scout read on each pod; library: the approved scenarios (the regression pack). Both are written next
35
+ # to a database row that says they exist, so leaving them out made a restart forget them while the rows still claimed them
36
+ FOLDERS = ("secrets", "runs", "evidence", "tickets", "screens", "library")
37
+ FILES = ("logs/audit-anchors.jsonl", "fusion_areas.json")
38
  MAX_BYTES = 45 * 1024 * 1024 # Supabase's free plan rejects objects above 50 MB
39
 
40
 
 
92
  tar.add(str(child), arcname=f"runs/{child.name}")
93
  elif p.is_dir():
94
  tar.add(str(p), arcname=folder)
95
+ for name in FILES:
96
+ if (home / name).is_file():
97
+ tar.add(str(home / name), arcname=name)
98
  return buf.getvalue()
99
 
100
 
coworker/tests/test_any_screen_steps.py CHANGED
@@ -120,6 +120,18 @@ class TestTheRunReadsTheScreensItNeeds(unittest.TestCase):
120
  self.read("live", ["AP", "PO"]) # nothing missing now: no browser
121
  self.assertEqual(len(FakeExplorer.calls), 1)
122
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  def test_a_new_release_reads_them_again(self):
124
  self.read("live", ["AP"])
125
  self.c.patch(f"/api/pods/{self.pod['id']}", json={"release": "26D"}, headers=bearer(self.c, "admin"))
 
120
  self.read("live", ["AP", "PO"]) # nothing missing now: no browser
121
  self.assertEqual(len(FakeExplorer.calls), 1)
122
 
123
+ def test_screens_whose_files_are_gone_are_read_again_and_a_restart_keeps_them(self):
124
+ import io
125
+ import shutil
126
+ import tarfile
127
+ from coworker.platform import statesync
128
+ self.read("live", ["AP"])
129
+ names = tarfile.open(fileobj=io.BytesIO(statesync.build_archive(self.svc.cfg.home)), mode="r:gz").getnames()
130
+ self.assertTrue(any(n.startswith(f"screens/{self.pod['id']}/") for n in names)) # saved with the state
131
+ shutil.rmtree(self.reg.screens_dir(self.pod["id"])) # the files are gone, the row still says AP was read
132
+ self.read("live", ["AP"])
133
+ self.assertEqual(len(FakeExplorer.calls), 2)
134
+
135
  def test_a_new_release_reads_them_again(self):
136
  self.read("live", ["AP"])
137
  self.c.patch(f"/api/pods/{self.pod['id']}", json={"release": "26D"}, headers=bearer(self.c, "admin"))
coworker/tests/test_notify_telegram.py CHANGED
@@ -75,7 +75,7 @@ class TestTelegram(unittest.TestCase):
75
  msg = next(m for t, m in msgs.items() if "Ready" in t)
76
  self.assertEqual(msg["chat_id"], "4242")
77
  self.assertEqual(msg["parse_mode"], "HTML")
78
- self.assertIn("<b>Patchwise</b>", msg["text"])
79
  self.assertIn("Ready &lt;now&gt; &amp; done", msg["text"])
80
  self.assertEqual(msg["reply_markup"]["inline_keyboard"][0][0], {"text": "Open in Patchwise", "url": "https://patchwise.example/"})
81
  self.assertIsNotNone(tg_row(svc, nid)["tg_delivered_at"])
@@ -86,7 +86,25 @@ class TestTelegram(unittest.TestCase):
86
  def test_no_button_without_an_https_link(self):
87
  msg = notify.telegram_message("1", {"coworker": "Triage", "title": "t", "body": "", "link": "/runs/x"})
88
  self.assertNotIn("reply_markup", msg)
89
- self.assertEqual(msg["text"], "<b>Triage</b>\nt")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  def test_channels_are_independent(self):
92
  tg = FakeTelegram([500] * 10)
 
75
  msg = next(m for t, m in msgs.items() if "Ready" in t)
76
  self.assertEqual(msg["chat_id"], "4242")
77
  self.assertEqual(msg["parse_mode"], "HTML")
78
+ self.assertIn("<i>— Patchwise</i>", msg["text"])
79
  self.assertIn("Ready &lt;now&gt; &amp; done", msg["text"])
80
  self.assertEqual(msg["reply_markup"]["inline_keyboard"][0][0], {"text": "Open in Patchwise", "url": "https://patchwise.example/"})
81
  self.assertIsNotNone(tg_row(svc, nid)["tg_delivered_at"])
 
86
  def test_no_button_without_an_https_link(self):
87
  msg = notify.telegram_message("1", {"coworker": "Triage", "title": "t", "body": "", "link": "/runs/x"})
88
  self.assertNotIn("reply_markup", msg)
89
+ self.assertEqual(msg["text"], "<b>t</b>\n\n<i>— Triage</i>")
90
+
91
+ def test_a_run_message_carries_the_runs_details(self):
92
+ tg = FakeTelegram()
93
+ svc, _ = make(tg)
94
+ svc.db.create_run({"run_id": "R1", "modules": json.dumps(["AP", "GL"]), "patch_id": "26B", "status": "completed",
95
+ "decisions": json.dumps({"AP": "GO", "GL": "NO-GO"}),
96
+ "counts": json.dumps({"total": 9, "executed": 8, "passed": 6, "failed": 2, "flaky": 0, "skipped": 1})})
97
+ svc.db.add_event("R1", "test_generator", "ai_scenarios", {"message": "x", "module": "AP", "written": 4, "passed": 3})
98
+ svc.db.add_event("R1", "test_generator", "ai_scenarios",
99
+ {"message": "Record-to-Report: 2 end-to-end flow(s) designed across AP, GL."})
100
+ n = notify.get(svc)
101
+ text = notify.telegram_text(tg_row(svc, n.emit("run.finished", svc.db.get_run("R1"))))
102
+ self.assertTrue(text.startswith("❌ <b>Test run finished: Not ready</b>"))
103
+ for part in ("<b>Release:</b> 26B", "<b>Areas:</b> Payables, General Ledger", "✅ Payables: Ready",
104
+ "❌ General Ledger: Not ready", "9 in scope, 8 run, 6 passed, 2 failed, 1 skipped",
105
+ "Payables: 4 written, 3 passed", "Record-to-Report: 2 designed (Payables → General Ledger)",
106
+ "Sign-off is yours", "<i>— Triage</i>"):
107
+ self.assertIn(part, text)
108
 
109
  def test_channels_are_independent(self):
110
  tg = FakeTelegram([500] * 10)