codee-agent 0.8.0__py3-none-any.whl → 0.9.0__py3-none-any.whl

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.
codee/admin.py CHANGED
@@ -22,6 +22,8 @@ RUNS_PAGE_SIZE = 20
22
22
  # The agents a skill can be run by, as the editor's picker lists them. Built
23
23
  # once: which agents exist is decided by this build, not by the settings.
24
24
  DEFAULT_AGENT_OPTION = "Default agent"
25
+ # How many of a running session's last steps the Peep dialog shows.
26
+ PEEP_STEPS = 10
25
27
  # The effort picker's value for "no effort set": a select item can't be empty.
26
28
  EFFORT_DEFAULT = "__default__"
27
29
  AGENT_NAMES = {agent["code"]: agent["name"] for agent in SERVICE.list_agents()}
@@ -192,6 +194,18 @@ class ActiveJob(BaseModel):
192
194
  model: str = ""
193
195
 
194
196
 
197
+ class PeepStep(BaseModel):
198
+ """One recent step of a running session in the Peep dialog.
199
+
200
+ ``kind`` is ``thinking``, ``text`` or ``tool``; ``timestamp`` is ISO, empty
201
+ when the agent logged none.
202
+ """
203
+
204
+ kind: str
205
+ text: str
206
+ timestamp: str = ""
207
+
208
+
195
209
  def _active_job(job: dict[str, Any]) -> ActiveJob:
196
210
  """One in-flight run as its dashboard row reads it.
197
211
 
@@ -394,6 +408,13 @@ class AdminState(rx.State):
394
408
  # row index can belong to another session by the time "Kill" is pressed.
395
409
  kill_job_id: int = 0
396
410
  kill_job_label: str = ""
411
+ # The session the Peep dialog shows, held for the same reason, with the
412
+ # last steps read from its transcript. ``peep_note`` says why there are
413
+ # none, or that the session has finished since.
414
+ peep_job_id: int = 0
415
+ peep_job_label: str = ""
416
+ peep_steps: list[PeepStep] = []
417
+ peep_note: str = ""
397
418
  paused: bool = False
398
419
  total_runs: int = 0
399
420
  last_24h_runs: int = 0
@@ -942,6 +963,48 @@ class AdminState(rx.State):
942
963
  self._refresh_dashboard()
943
964
  return rx.toast.success(f"Killed {label}")
944
965
 
966
+ def open_peep(self, job_id: int, label: str) -> None:
967
+ self.peep_job_id = job_id
968
+ self.peep_job_label = label
969
+ self.peep_steps = []
970
+ self._load_peep()
971
+
972
+ def set_peep_dialog_open(self, is_open: bool) -> None:
973
+ if not is_open:
974
+ self.peep_job_id = 0
975
+ self.peep_job_label = ""
976
+ self.peep_steps = []
977
+ self.peep_note = ""
978
+
979
+ def refresh_peep(self) -> None:
980
+ if self.peep_job_id:
981
+ self._load_peep()
982
+
983
+ def _load_peep(self) -> None:
984
+ """Read the session's last steps, or say why there are none.
985
+
986
+ A session that finished keeps the steps already on screen, so the
987
+ last look at it isn't wiped by the refresh that found it gone.
988
+ """
989
+ try:
990
+ peep = SERVICE.peep_job(self.peep_job_id, PEEP_STEPS)
991
+ except Exception as error:
992
+ self.peep_note = f"Could not read the session: {error}"
993
+ return
994
+ if peep is None:
995
+ self.peep_note = ("This session has finished. Its response is "
996
+ "under Runs.")
997
+ return
998
+ if peep["entries"] is None:
999
+ self.peep_steps = []
1000
+ self.peep_note = (f"Peep isn't available for {peep['agent']} "
1001
+ "sessions yet.")
1002
+ return
1003
+ self.peep_steps = [PeepStep(**entry) for entry in peep["entries"]]
1004
+ self.peep_note = ("" if self.peep_steps else
1005
+ "Nothing to show yet. The agent may still be "
1006
+ "starting up.")
1007
+
945
1008
  @rx.event(background=True)
946
1009
  async def poll_dashboard(self) -> None:
947
1010
  """Keep the dashboard live for as long as it is the page on screen.
@@ -2103,6 +2166,12 @@ def active_job_row(job: ActiveJob) -> rx.Component:
2103
2166
  aria_label="View session", color=ACCENT, display="flex",
2104
2167
  align_items="center"),
2105
2168
  ),
2169
+ rx.icon_button(
2170
+ rx.icon("eye", size=14),
2171
+ size="1", variant="ghost",
2172
+ aria_label="Peep at session", title="Peep at session",
2173
+ on_click=AdminState.open_peep(job.id, job.message),
2174
+ ),
2106
2175
  rx.icon_button(
2107
2176
  rx.icon("square", size=14),
2108
2177
  size="1", variant="ghost", color_scheme="red",
@@ -2146,6 +2215,70 @@ def kill_job_dialog() -> rx.Component:
2146
2215
  )
2147
2216
 
2148
2217
 
2218
+ def peep_step(step: PeepStep) -> rx.Component:
2219
+ """One step: what kind it is and when, then what the agent wrote or ran.
2220
+
2221
+ Thinking and replies are markdown, with raw HTML and math off as on the
2222
+ Runs page. A tool call is one line of code.
2223
+ """
2224
+ return rx.vstack(
2225
+ rx.hstack(
2226
+ rx.badge(
2227
+ rx.match(step.kind, ("thinking", "Thinking"),
2228
+ ("tool", "Tool call"), "Message"),
2229
+ color_scheme=rx.match(step.kind, ("thinking", "gray"),
2230
+ ("tool", "blue"), "green"),
2231
+ variant="soft"),
2232
+ rx.cond(step.timestamp != "",
2233
+ rx.text(local_datetime(step.timestamp), color=MUTED,
2234
+ font_size="0.75rem")),
2235
+ spacing="2", align="center"),
2236
+ rx.cond(
2237
+ step.kind == "tool",
2238
+ rx.code(step.text, font_family=MONO, font_size="0.8rem",
2239
+ white_space="pre-wrap", overflow_wrap="anywhere",
2240
+ width="100%", color_scheme="gray"),
2241
+ rx.box(rx.markdown(step.text, use_raw=False, use_math=False,
2242
+ use_katex=False),
2243
+ color=rx.cond(step.kind == "thinking", MUTED, TEXT),
2244
+ font_style=rx.cond(step.kind == "thinking", "italic",
2245
+ "normal"),
2246
+ font_size="0.88rem", width="100%", overflow_x="auto")),
2247
+ spacing="1", align="start", width="100%",
2248
+ padding_bottom="0.75rem", border_bottom=BORDER,
2249
+ )
2250
+
2251
+
2252
+ def peep_dialog() -> rx.Component:
2253
+ """The last steps of one running session, read again on Refresh."""
2254
+ return rx.dialog.root(
2255
+ rx.dialog.content(
2256
+ rx.dialog.title("Peep"),
2257
+ rx.dialog.description(
2258
+ rx.text(AdminState.peep_job_label, font_family=MONO,
2259
+ font_size="0.85rem", overflow="hidden",
2260
+ text_overflow="ellipsis", white_space="nowrap"),
2261
+ color=MUTED),
2262
+ rx.vstack(
2263
+ rx.foreach(AdminState.peep_steps, peep_step),
2264
+ rx.cond(AdminState.peep_note != "",
2265
+ rx.text(AdminState.peep_note, color=MUTED,
2266
+ font_size="0.85rem")),
2267
+ spacing="3", width="100%", max_height="60vh",
2268
+ overflow_y="auto", margin_top="1rem", padding_right="0.25rem"),
2269
+ rx.hstack(
2270
+ rx.button(rx.icon("refresh-cw", size=14), "Refresh",
2271
+ variant="soft", on_click=AdminState.refresh_peep),
2272
+ rx.dialog.close(rx.button("Close", variant="soft",
2273
+ color_scheme="gray")),
2274
+ spacing="3", justify="end", margin_top="1.25rem",
2275
+ width="100%"),
2276
+ max_width="48rem"),
2277
+ open=AdminState.peep_job_id != 0,
2278
+ on_open_change=AdminState.set_peep_dialog_open,
2279
+ )
2280
+
2281
+
2149
2282
  def running_tile() -> rx.Component:
2150
2283
  """Stat tile that lights up while sessions are in flight."""
2151
2284
  running = AdminState.active_jobs.length()
@@ -2215,6 +2348,7 @@ def running_panel() -> rx.Component:
2215
2348
  ),
2216
2349
  ),
2217
2350
  kill_job_dialog(),
2351
+ peep_dialog(),
2218
2352
  padding="1.25rem",
2219
2353
  background=SURFACE,
2220
2354
  border=rx.cond(is_running, f"1px solid {ACCENT}", BORDER),
@@ -2561,7 +2695,7 @@ def effort_picker() -> rx.Component:
2561
2695
  """Reasoning effort for the picked model, shown only when it takes one."""
2562
2696
  return rx.cond(
2563
2697
  AdminState.skill_effort_options.length() > 0,
2564
- field(
2698
+ rx.box(field(
2565
2699
  "Reasoning effort",
2566
2700
  rx.select.root(
2567
2701
  rx.select.trigger(width="100%"),
@@ -2587,7 +2721,8 @@ def effort_picker() -> rx.Component:
2587
2721
  rx.code("effort: ",
2588
2722
  AdminState.skill_effort),
2589
2723
  " in the skill frontmatter."))),
2590
- color=MUTED, font_size="0.82rem")))
2724
+ color=MUTED, font_size="0.82rem")),
2725
+ flex="1", min_width="0"))
2591
2726
 
2592
2727
 
2593
2728
  def delete_skill_dialog() -> rx.Component:
@@ -2629,7 +2764,13 @@ def skill_editor() -> rx.Component:
2629
2764
  field("Description", rx.text_area(value=AdminState.skill_description,
2630
2765
  on_change=AdminState.set_skill_description,
2631
2766
  width="100%", min_height="5rem")),
2632
- rx.grid(agent_picker(), model_picker(), effort_picker(),
2767
+ rx.grid(agent_picker(),
2768
+ # Effort shares the model's column; the model takes all of it
2769
+ # when the picked model has no effort levels.
2770
+ rx.flex(rx.box(model_picker(), flex="1", min_width="0"),
2771
+ effort_picker(),
2772
+ direction=rx.breakpoints(initial="column", sm="row"),
2773
+ gap="1rem", align="start", width="100%"),
2633
2774
  columns=rx.breakpoints(initial="1", md="2"), gap="1rem",
2634
2775
  align="start", width="100%"),
2635
2776
  rx.cond(AdminState.skill_type == "cron trigger",
codee/admin_service.py CHANGED
@@ -1022,7 +1022,11 @@ class AdminService:
1022
1022
  print(f"[admin] Failed to list models for "
1023
1023
  f"{agent_key.value}: {error}")
1024
1024
  models = []
1025
- self._models_cache[agent_key] = models
1025
+ # An empty catalog is usually a CLI that couldn't be started or
1026
+ # wasn't signed in yet, so it is asked again next time rather
1027
+ # than left empty until a restart.
1028
+ if models:
1029
+ self._models_cache[agent_key] = models
1026
1030
  return [{"id": model.id, "name": model.name,
1027
1031
  "efforts": list(model.efforts),
1028
1032
  "default_effort": model.default_effort}
@@ -2074,6 +2078,37 @@ class AdminService:
2074
2078
  """Stop a running session. False if it had already finished."""
2075
2079
  return runs_db.kill_job(job_id, main_context=self.context)
2076
2080
 
2081
+ def peep_job(self, job_id: int, limit: int = 10) -> dict[str, Any] | None:
2082
+ """The last ``limit`` steps of a running session. None once it finished.
2083
+
2084
+ ``entries`` is None rather than a list when the session's agent keeps
2085
+ no transcript Codee can read. A row that names no agent, from before
2086
+ the dashboard recorded one, is read as the default agent's.
2087
+ """
2088
+ job = next((job for job in runs_db.active_jobs(main_context=self.context)
2089
+ if job["id"] == job_id), None)
2090
+ if job is None:
2091
+ return None
2092
+ agent = (resolve_agent_code(job.get("agent") or "")
2093
+ or self.context.settings.coding_agent)
2094
+ implementation = CODING_AGENTS.get(agent)
2095
+ entries = None
2096
+ if implementation is not None:
2097
+ try:
2098
+ entries = implementation.peep(job["session_id"], self.root,
2099
+ limit)
2100
+ except Exception as error:
2101
+ print(f"[admin] Could not read job {job_id}'s transcript: "
2102
+ f"{error}")
2103
+ entries = []
2104
+ return {
2105
+ "agent": agent_label(agent),
2106
+ "entries": (None if entries is None else
2107
+ [{"kind": entry.kind, "text": entry.text,
2108
+ "timestamp": entry.timestamp}
2109
+ for entry in entries]),
2110
+ }
2111
+
2077
2112
  def set_paused(self, paused: bool) -> bool:
2078
2113
  """Allow or prevent future automated agent runs."""
2079
2114
  set_paused(self.context, paused)
@@ -0,0 +1,140 @@
1
+ import tempfile
2
+ import unittest
3
+ from email.message import EmailMessage
4
+ from pathlib import Path
5
+ from unittest.mock import MagicMock, patch
6
+
7
+ from codee_main_context.context import CodeeMainContext
8
+
9
+ from codee.lib import trigger_email_skills as module
10
+ from codee.lib.trigger_email_skills import trigger_email_skills
11
+
12
+ ADDRESS = "inbox@codee.example.com"
13
+
14
+
15
+ def _raw(sender="dev@example.com", to=ADDRESS, subject="Bug") -> bytes:
16
+ msg = EmailMessage()
17
+ msg["From"] = sender
18
+ msg["To"] = to
19
+ msg["Subject"] = subject
20
+ msg.set_content("Checkout fails with a 500.")
21
+ return msg.as_bytes()
22
+
23
+
24
+ class FakeMailpit:
25
+ """Just enough of the Mailpit API: search, raw message, delete."""
26
+
27
+ def __init__(self, messages):
28
+ # ID -> (Created, recipients, raw)
29
+ self.messages = dict(messages)
30
+ self.deleted = []
31
+ self.queries = []
32
+
33
+ def get(self, url, params=None, auth=None, timeout=None):
34
+ resp = MagicMock()
35
+ if url.endswith("/search"):
36
+ self.queries.append((params["query"], auth))
37
+ address = params["query"].split('"')[1]
38
+ hits = [{"ID": i, "Created": c}
39
+ for i, (c, rcpts, _) in self.messages.items() if address in rcpts]
40
+ hits.sort(key=lambda m: m["Created"], reverse=True) # newest first
41
+ resp.json.return_value = {"messages": hits}
42
+ else:
43
+ message_id = url.rsplit("/", 2)[-2]
44
+ resp.content = self.messages[message_id][2]
45
+ return resp
46
+
47
+ def delete(self, url, json=None, auth=None, timeout=None):
48
+ self.deleted.extend(json["IDs"])
49
+ for message_id in json["IDs"]:
50
+ self.messages.pop(message_id, None)
51
+ return MagicMock()
52
+
53
+
54
+ class EmailTriggerTests(unittest.TestCase):
55
+ def setUp(self):
56
+ self.tmp = Path(tempfile.mkdtemp())
57
+ skill_dir = self.tmp / "skills" / "inbox"
58
+ skill_dir.mkdir(parents=True)
59
+ (skill_dir / "SKILL.md").write_text(
60
+ "---\n"
61
+ "name: inbox\n"
62
+ "disable-model-invocation: true\n"
63
+ "x-codee-trigger: email\n"
64
+ f"x-codee-email-address: {ADDRESS}\n"
65
+ "---\n"
66
+ "Mail:\n\n{CONTENT}\n")
67
+ self.emails_dir = self.tmp / "emails"
68
+ self.prompts = []
69
+ patch.object(module, "ALLOWED_SENDER_DOMAINS", ("example.com",)).start()
70
+ patch.object(module.runs_db, "record_run").start()
71
+ self.addCleanup(patch.stopall)
72
+
73
+ def run_claude(self, prompt, session_id, model, agent, effort=""):
74
+ self.prompts.append(prompt)
75
+ return "ok"
76
+
77
+ def tick(self, env=None):
78
+ with patch.dict(module.os.environ, env or {}, clear=False):
79
+ if not env:
80
+ module.os.environ.pop("MAILPIT_API_URL", None)
81
+ trigger_email_skills(self.run_claude, skills_dir=self.tmp / "skills",
82
+ emails_dir=self.emails_dir,
83
+ main_context=CodeeMainContext(data_dir=self.tmp))
84
+
85
+ def test_directory_source_runs_skill_and_removes_file(self):
86
+ self.emails_dir.mkdir()
87
+ (self.emails_dir / "a.eml").write_bytes(_raw())
88
+
89
+ self.tick()
90
+
91
+ self.assertEqual(len(self.prompts), 1)
92
+ self.assertIn("Checkout fails with a 500.", self.prompts[0])
93
+ self.assertEqual(list(self.emails_dir.glob("*.eml")), [])
94
+
95
+ def test_mailpit_source_only_touches_skill_mail_oldest_first(self):
96
+ mailpit = FakeMailpit({
97
+ "new": ("2026-10-08T06:22:00Z", [ADDRESS], _raw(subject="second")),
98
+ "old": ("2026-10-08T06:17:00Z", [ADDRESS], _raw(subject="first")),
99
+ "qa": ("2026-10-08T05:00:00Z", ["qa@codee.example.com"],
100
+ _raw(to="qa@codee.example.com")),
101
+ })
102
+ env = {"MAILPIT_API_URL": "http://mailpit/api/v1/",
103
+ "MAILPIT_AUTH": "user:secret"}
104
+ with patch.object(module.requests, "get", mailpit.get), \
105
+ patch.object(module.requests, "delete", mailpit.delete):
106
+ self.tick(env)
107
+
108
+ self.assertEqual(mailpit.queries, [(f'addressed:"{ADDRESS}"', ("user", "secret"))])
109
+ self.assertEqual(["Subject: first" in p for p in self.prompts], [True, False])
110
+ self.assertEqual(mailpit.deleted, ["old", "new"])
111
+ self.assertIn("qa", mailpit.messages)
112
+
113
+ def test_mailpit_envelope_only_recipient_still_routes(self):
114
+ # Bcc'd: Mailpit matched the envelope, the raw headers don't name us.
115
+ mailpit = FakeMailpit({
116
+ "bcc": ("2026-10-08T06:00:00Z", [ADDRESS], _raw(to="someone@example.com")),
117
+ })
118
+ with patch.object(module.requests, "get", mailpit.get), \
119
+ patch.object(module.requests, "delete", mailpit.delete):
120
+ self.tick({"MAILPIT_API_URL": "http://mailpit/api/v1"})
121
+
122
+ self.assertEqual(len(self.prompts), 1)
123
+ self.assertEqual(mailpit.deleted, ["bcc"])
124
+
125
+ def test_mailpit_failed_run_keeps_message(self):
126
+ mailpit = FakeMailpit({"m": ("2026-10-08T06:00:00Z", [ADDRESS], _raw())})
127
+
128
+ def boom(*args, **kwargs):
129
+ raise RuntimeError("agent crashed")
130
+
131
+ self.run_claude = boom
132
+ with patch.object(module.requests, "get", mailpit.get), \
133
+ patch.object(module.requests, "delete", mailpit.delete):
134
+ self.tick({"MAILPIT_API_URL": "http://mailpit/api/v1"})
135
+
136
+ self.assertEqual(mailpit.deleted, [])
137
+
138
+
139
+ if __name__ == "__main__":
140
+ unittest.main()
@@ -7,6 +7,8 @@ from email.message import Message
7
7
  from pathlib import Path
8
8
  from typing import Callable
9
9
 
10
+ import requests
11
+
10
12
  from codee_main_context.context import CodeeMainContext
11
13
 
12
14
  from codee.lib import runs_db
@@ -30,6 +32,17 @@ ALLOWED_SENDER_DOMAINS = tuple(
30
32
  RunClaude = Callable[..., str]
31
33
 
32
34
 
35
+ @dataclass(frozen=True)
36
+ class QueuedEmail:
37
+ """One message waiting to be routed, wherever it is stored."""
38
+ name: str
39
+ read: Callable[[], bytes]
40
+ consume: Callable[[], None]
41
+ # Skill address the source already matched on, for recipients the raw
42
+ # headers don't show (Mailpit also matches the SMTP envelope, e.g. Bcc).
43
+ address: str = ""
44
+
45
+
33
46
  @dataclass(frozen=True)
34
47
  class EmailTriggeredSkill:
35
48
  key: str
@@ -49,38 +62,47 @@ def trigger_email_skills(
49
62
  emails_dir: Path = EMAILS_DIR,
50
63
  main_context: CodeeMainContext
51
64
  ) -> None:
52
- """Route up to MAX_EMAILS_PER_TICK queued emails to skills by recipient address."""
65
+ """Route up to MAX_EMAILS_PER_TICK queued emails to skills by recipient address.
66
+
67
+ Emails come from Mailpit when MAILPIT_API_URL is set, otherwise from .eml
68
+ files in emails_dir.
69
+ """
53
70
  skills_by_address = find_email_triggered_skills(skills_dir)
54
71
  if not skills_by_address:
55
72
  return
56
73
 
57
- emails_dir.mkdir(parents=True, exist_ok=True)
58
- files = sorted(p for p in emails_dir.glob("*.eml") if p.is_file())
59
- if not files:
60
- return
74
+ if _mailpit_api():
75
+ try:
76
+ queued = _mailpit_emails(skills_by_address)
77
+ except Exception as exc:
78
+ print(f"[email_skills] Failed to list Mailpit messages: {exc}")
79
+ return
80
+ else:
81
+ queued = _directory_emails(emails_dir)
61
82
 
62
- for path in files[:MAX_EMAILS_PER_TICK]:
83
+ for item in queued[:MAX_EMAILS_PER_TICK]:
63
84
  try:
64
- message = email.message_from_bytes(path.read_bytes())
65
- except OSError as exc:
66
- print(f"[email_skills] Failed to read {path}: {exc}")
85
+ message = email.message_from_bytes(item.read())
86
+ except Exception as exc:
87
+ print(f"[email_skills] Failed to read {item.name}: {exc}")
67
88
  continue
68
89
 
69
90
  if not _sender_allowed(message):
70
91
  print(
71
- f"[email_skills] Sender of {path.name} not in allowed domains; dropping.")
72
- path.unlink(missing_ok=True)
92
+ f"[email_skills] Sender of {item.name} not in allowed domains; dropping.")
93
+ item.consume()
73
94
  continue
74
95
 
75
- skill = _match_skill(message, skills_by_address)
96
+ skill = (_match_skill(message, skills_by_address)
97
+ or skills_by_address.get(item.address))
76
98
  if skill is None:
77
99
  print(
78
- f"[email_skills] No skill matches recipients of {path.name}; dropping.")
79
- path.unlink(missing_ok=True)
100
+ f"[email_skills] No skill matches recipients of {item.name}; dropping.")
101
+ item.consume()
80
102
  continue
81
103
 
82
104
  print(
83
- f"[email_skills] Running {skill.name} for email {path.name} -> {skill.address}")
105
+ f"[email_skills] Running {skill.name} for email {item.name} -> {skill.address}")
84
106
  session_id = str(uuid.uuid4())
85
107
  prompt = render_email_prompt(skill.body, message)
86
108
  try:
@@ -88,7 +110,7 @@ def trigger_email_skills(
88
110
  effort=skill.effort)
89
111
  print(
90
112
  f"[email_skills] Claude response for {skill.name} ({len(response)} chars)")
91
- path.unlink(missing_ok=True)
113
+ item.consume()
92
114
  runs_db.record_run(skill.name, "email", session_id,
93
115
  "succeeded", message=prompt,
94
116
  user_message=prompt, response=response,
@@ -96,22 +118,81 @@ def trigger_email_skills(
96
118
  except runs_db.JobKilled as exc:
97
119
  # Stopped on purpose: consume the email so the next tick doesn't
98
120
  # start the same run again.
99
- print(f"[email_skills] {skill.name} for {path.name} was killed "
121
+ print(f"[email_skills] {skill.name} for {item.name} was killed "
100
122
  "from the dashboard.")
101
- path.unlink(missing_ok=True)
123
+ item.consume()
102
124
  runs_db.record_run(skill.name, "email", session_id, "killed",
103
125
  error=str(exc), message=prompt,
104
126
  user_message=prompt,
105
127
  main_context=main_context)
106
128
  except Exception as exc:
107
129
  print(
108
- f"[email_skills] Failed to run {skill.name} for {path.name}: {exc}")
130
+ f"[email_skills] Failed to run {skill.name} for {item.name}: {exc}")
109
131
  runs_db.record_run(skill.name, "email", session_id, "failed",
110
132
  error=str(exc)[:500], message=prompt,
111
133
  user_message=prompt,
112
134
  main_context=main_context)
113
135
 
114
136
 
137
+ def _directory_emails(emails_dir: Path) -> list[QueuedEmail]:
138
+ """.eml files dropped by mail_server (or anything else), oldest name first."""
139
+ emails_dir.mkdir(parents=True, exist_ok=True)
140
+ return [
141
+ QueuedEmail(path.name, path.read_bytes,
142
+ lambda path=path: path.unlink(missing_ok=True))
143
+ for path in sorted(p for p in emails_dir.glob("*.eml") if p.is_file())
144
+ ]
145
+
146
+
147
+ def _mailpit_api() -> str:
148
+ return os.environ.get("MAILPIT_API_URL", "").strip().rstrip("/")
149
+
150
+
151
+ def _mailpit_auth() -> tuple[str, str] | None:
152
+ """MAILPIT_AUTH=user:password (basic auth), optional."""
153
+ user, _, password = os.environ.get("MAILPIT_AUTH", "").partition(":")
154
+ return (user, password) if user else None
155
+
156
+
157
+ def _mailpit_emails(
158
+ skills_by_address: dict[str, EmailTriggeredSkill],
159
+ ) -> list[QueuedEmail]:
160
+ """Mailpit messages addressed to a skill, oldest first.
161
+
162
+ Searching by address leaves every other message in Mailpit untouched.
163
+ """
164
+ api, auth = _mailpit_api(), _mailpit_auth()
165
+ found: dict[str, tuple[str, str]] = {} # ID -> (Created, address)
166
+ for address in skills_by_address:
167
+ resp = requests.get(f"{api}/search",
168
+ params={"query": f'addressed:"{address}"', "limit": 50},
169
+ auth=auth, timeout=30)
170
+ resp.raise_for_status()
171
+ for meta in resp.json().get("messages") or []:
172
+ found.setdefault(meta["ID"], (meta.get("Created", ""), address))
173
+
174
+ def read(message_id: str) -> bytes:
175
+ resp = requests.get(f"{api}/message/{message_id}/raw", auth=auth, timeout=30)
176
+ resp.raise_for_status()
177
+ return resp.content
178
+
179
+ def delete(message_id: str) -> None:
180
+ try:
181
+ resp = requests.delete(f"{api}/messages", json={"IDs": [message_id]},
182
+ auth=auth, timeout=30)
183
+ resp.raise_for_status()
184
+ except Exception as exc:
185
+ print(f"[email_skills] Failed to delete Mailpit message {message_id}: {exc}")
186
+
187
+ return [
188
+ QueuedEmail(f"mailpit:{message_id}",
189
+ lambda message_id=message_id: read(message_id),
190
+ lambda message_id=message_id: delete(message_id),
191
+ address=address)
192
+ for message_id, (_, address) in sorted(found.items(), key=lambda kv: kv[1])
193
+ ]
194
+
195
+
115
196
  def find_email_triggered_skills(skills_dir: Path = SKILLS_DIR) -> dict[str, EmailTriggeredSkill]:
116
197
  """Map normalized recipient address -> skill. Duplicate addresses are skipped."""
117
198
  skills_by_address: dict[str, EmailTriggeredSkill] = {}
codee/test_admin.py CHANGED
@@ -3,7 +3,7 @@
3
3
  from types import SimpleNamespace
4
4
  from unittest.mock import Mock, patch
5
5
 
6
- from codee.admin import (EFFORT_DEFAULT, AdminState, ModelOption,
6
+ from codee.admin import (EFFORT_DEFAULT, AdminState, ModelOption, PeepStep,
7
7
  _highlight_parts, _run_preview, running_panel)
8
8
 
9
9
 
@@ -99,6 +99,69 @@ def test_killing_a_session_that_already_finished_says_so() -> None:
99
99
  toast.assert_called_once_with("That session had already finished.")
100
100
 
101
101
 
102
+ def _peep_state(**fields) -> SimpleNamespace:
103
+ state = SimpleNamespace(peep_job_id=0, peep_job_label="", peep_steps=[],
104
+ peep_note="")
105
+ state.__dict__.update(fields)
106
+ state._load_peep = lambda: AdminState._load_peep(state)
107
+ return state
108
+
109
+
110
+ def test_peep_shows_the_sessions_last_steps() -> None:
111
+ state = _peep_state()
112
+ with patch("codee.admin.SERVICE.peep_job", return_value={
113
+ "agent": "Claude Code",
114
+ "entries": [{"kind": "tool", "text": "Bash: ls",
115
+ "timestamp": "2026-10-01T10:00:00Z"}]}) as peep:
116
+ AdminState.open_peep.fn(state, 7, "/nightly")
117
+
118
+ peep.assert_called_once_with(7, 10)
119
+ assert (state.peep_job_id, state.peep_job_label) == (7, "/nightly")
120
+ assert [(step.kind, step.text) for step in state.peep_steps] == [
121
+ ("tool", "Bash: ls")]
122
+ assert state.peep_note == ""
123
+
124
+
125
+ def test_peep_says_when_there_is_nothing_yet() -> None:
126
+ state = _peep_state()
127
+ with patch("codee.admin.SERVICE.peep_job",
128
+ return_value={"agent": "Codex", "entries": []}):
129
+ AdminState.open_peep.fn(state, 7, "/nightly")
130
+
131
+ assert state.peep_steps == []
132
+ assert state.peep_note.startswith("Nothing to show yet.")
133
+
134
+
135
+ def test_peep_says_which_agents_it_cannot_read() -> None:
136
+ state = _peep_state()
137
+ with patch("codee.admin.SERVICE.peep_job",
138
+ return_value={"agent": "OpenCode", "entries": None}):
139
+ AdminState.open_peep.fn(state, 7, "/nightly")
140
+
141
+ assert state.peep_note == "Peep isn't available for OpenCode sessions yet."
142
+
143
+
144
+ def test_refreshing_a_finished_session_keeps_what_was_on_screen() -> None:
145
+ step = PeepStep(kind="text", text="Done.")
146
+ state = _peep_state(peep_job_id=7, peep_steps=[step])
147
+ with patch("codee.admin.SERVICE.peep_job", return_value=None):
148
+ AdminState.refresh_peep.fn(state)
149
+
150
+ assert state.peep_steps == [step]
151
+ assert state.peep_note.startswith("This session has finished.")
152
+
153
+
154
+ def test_closing_the_peep_dialog_forgets_the_session() -> None:
155
+ state = _peep_state(peep_job_id=7, peep_job_label="/nightly",
156
+ peep_steps=[PeepStep(kind="text", text="x")],
157
+ peep_note="note")
158
+
159
+ AdminState.set_peep_dialog_open.fn(state, False)
160
+
161
+ assert (state.peep_job_id, state.peep_job_label, state.peep_steps,
162
+ state.peep_note) == (0, "", [], "")
163
+
164
+
102
165
  def test_clearing_skill_search_resets_query() -> None:
103
166
  state = SimpleNamespace(skill_query="alarm")
104
167