diff --git a/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py b/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py index 7f1801c22..33b4a9a9f 100644 --- a/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py +++ b/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py @@ -20,9 +20,10 @@ - ``name`` (the agent name), ``display_name`` and ``first_name`` (else the display name's first word): how the agent's wakes and the user sim name the user; ``agent_name``: the deployed agent always_on asks (``ask`` below). -- ``schedule`` (``wake``, ``sleep``, ``work``, ``work_days``, ``busy``): when the user reads, where ``sleep`` may be - past midnight (wake 08:00, sleep 00:30); ``response_times`` (minutes by ``morning`` / ``work`` / ``free``): how long - a reply is held; ``max_replies``: after that many replies the user stops reading. ``schedule`` and +- ``schedule`` (``wake``, ``sleep``, ``work``, ``work_days``, ``busy``): when the user first looks, where ``sleep`` may + be past midnight (wake 08:00, sleep 00:30); ``response_times`` (minutes by ``morning`` / ``work`` / ``free``): how + long after that look she reads and answers, what the agent sends meanwhile joining that read; ``max_replies``: after + that many replies the user stops reading. ``schedule`` and ``response_times`` need the task's clock (``sync_env_clock``): always_on refuses to start a run that sets either with no clock armed. The user's time zone is the task clock's. - ``description``, ``permissions``, ``keep_private``: in ``person``, for the reads. @@ -65,10 +66,10 @@ ``answer`` returns ``{"outcome": "reply" | "no_reply" | "done", "message": str, "used": str | None}``, and may add ``input``, ``raw``, ``score``, ``schema_errors``, ``turns``, ``retried``, ``first_answer``, ``shown`` and -``past_turn_cap``, which always_on records. A ``reply`` or ``done`` with text is held for the response time, then -wakes the agent as the user's message; the recorded extras (``used``, ``score``, ...) never reach the agent. A reply -that never reaches the agent (one still held when the run ends, or the answer to the last read below) is recorded with -``delivered: false``. ``done`` ends a one-sitting run after the agent's turn on that message, or at once when it has +``past_turn_cap``, which always_on records. A ``reply`` or ``done`` with text wakes the agent as the user's message at +once, labelled with the read's time (her response time ran before the read); the recorded extras (``used``, +``score``, ...) never reach the agent. A reply that never reaches the agent (the answer to the last read below) is +recorded with ``delivered: false``. ``done`` ends a one-sitting run after the agent's turn on that message, or at once when it has no text, with no further reads; in a multi-day run it is only recorded. When the last ``ask`` of a read returned an error, the run ends (``user_sim_error``). @@ -155,8 +156,8 @@ def schedule_problems(schedule: Any, response_times: Any, max_replies: Any) -> l if not (isinstance(busy, list) and all(isinstance(b, dict) and _local_time(b.get("start")) and _local_time(b.get("end")) for b in busy)): out.append('schedule.busy must be a list of {start, end} local times, like "2026-11-12T09:00"') - if response_times is not None and not schedule: # no schedule, or {}: the user reads at once, nothing is held - out.append("response_times needs a schedule (an empty one counts as none); without one, replies are never held") + if response_times is not None and not schedule: # no schedule, or {}: the user reads and answers at once + out.append("response_times needs a schedule (an empty one counts as none); without one, the user answers at once") if response_times is not None: if not isinstance(response_times, dict): out.append(f"response_times must be an object of minutes by {list(RESPONSE_TIME_KEYS)}") diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 6e035d0b5..71c11fd22 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -17,19 +17,22 @@ ``stay_quiet`` on, no wake in Opus 5.5 and GPT 6.1 runs of Surprise 30th ended in a message left in closing text. The step takes only its agent's role's messages: another role's stay queued, and what the role sent before the run is recorded apart (``user_chat_before_run``), never read by the user. -- The user sim is asked only after the agent sent something, at the time the user would read it (``schedule``), with - everything sent meanwhile in one read: the time, the agent's messages, what triggers sent the user's phone - (``notify`` to ``user_phone``) and the user's own lines (the opening request, ``user_says`` lines, ``final``). - Nothing meant for the agent is in it. Its answer is reply / no_reply / done; a reply, or a done with text, is held - for the response time. A schedule and response times are task time, so a user sim that sets either needs an armed +- The user sim is asked only after the agent sent something. The user first looks when she is free (``schedule``); + her response time for that time of day (``response_times``) then runs, and when it is up she reads everything the + agent sent by then in one read and answers at once: the time, the agent's messages, what triggers sent the user's + phone (``notify`` to ``user_phone``) and the user's own lines (the opening request, ``user_says`` lines, ``final``), + each up to that time. So the wait holds the agent's messages, not her answer, and an answer never reaches the agent + after a message of its she hadn't read when she wrote it (FD-7185). Nothing meant for the agent is in it. Its answer + is reply / no_reply / done; a reply, or a done with text, reaches the agent as the user's message, labelled with the + time she wrote it. A schedule and response times are task time, so a user sim that sets either needs an armed clock (sync_env_clock): without one the step refuses to start. Done ends a one-sitting run (after the agent's turn on its text); a run whose end_time falls on a later day than its start goes on to end_time. - Scripted user lines are triggers' ``notify`` actions to the ``user_says`` recipient: sent to the agent as the user's message at their time. - The clock runs at the task's speed (sync_env_clock) only during the agent's turns: the step freezes it between them (clock/v1 set_rate), so settles and reads don't move it, and puts the task's rate back at the end. When nothing is - due, the step advances it to the earliest of: the next trigger event, the next notification, a held reply, a - pending read, or end_time, never past one; then waits for the world to settle. A contact's reply (an AI-played contact, a trigger's executor) counts as in + due, the step advances it to the earliest of: the next trigger event, the next notification, a reply to deliver, + the user's next look or answer, or end_time, never past one; then waits for the world to settle. A contact's reply (an AI-played contact, a trigger's executor) counts as in progress until it ends or its time limit passes; other trigger work gets ``settle_timeout_seconds``. A contact's time limit is the one it was registered with (register_env_triggers' ``executor_timeout_seconds``), and one trigger's replies run side by side (``contact_replies_in_parallel``). What comes due in the same minute wakes the @@ -41,8 +44,8 @@ when the task sets none. An agent's turn that ends past end_time is followed by it, with whatever came due (a read due before end_time goes first), never by an ordinary wake. The run's last wake, at end_time or the one ``max_wakes`` makes the last, carries the last-turn notice (``final_reminder``). After it the user sim reads what - the agent sent (its wrap-up), no earlier than the task's time when the run ended, and the user's reaction, and any - reply still held, are recorded; then the run ends. + the agent sent (its wrap-up), no earlier than the task's time when the run ended, and the user's reaction is + recorded, never delivered; then the run ends. - A real-time budget keeps the run inside the hub's 8-hour job (``effective_time_budget`` gives the rule): once one more wake might end past ``time_budget_seconds`` (7 h, lowered to fit the task's own timeouts), the agent gets its closing wake, with the step's wrap-up line and the last-turn notice, and the run ends with end reason time_budget. @@ -503,10 +506,13 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.wakes = 0 self.end_reason: Optional[str] = None self.unread: list[dict] = [] # the agent's messages the user hasn't read - self.read_at: Optional[datetime] = None - self.read_mode = "now" - self.held: list[dict] = [] # user replies held for their response time: {deliver_at, text} + self.read_at: Optional[datetime] = None # when she next looks at them (``_schedule_read``) + self.read_mode = "now" # the time of day she looks in, for her response time + self.looked_at: Optional[datetime] = None # when she looked, her response time running from then + self.answer_at: Optional[datetime] = None # when she reads and answers, her response time up (``_look``) + self.held: list[dict] = [] # her answers not yet delivered: {deliver_at, text}; the last read's stay self.you_sent: list[dict] = [] # the user's own lines since their last read: {at, text} + self.phone_later: list[dict] = [] # phone alerts taken for a read but past its time: for her next read self.history: list[dict] = [] # every read and its answer, for the plug-in # The conversation as the user-sim gate reads it, (role, text); and the gate's judge settings, set up once. self.gate_history: list[tuple[str, str]] = [] @@ -515,7 +521,6 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.replies = 0 self.gave_up = False self.final_sent = False - self.last_reply_at: Optional[datetime] = None self.per_turn_trajectory_urls: list[Optional[str]] = [] self.per_turn_trajectories: list[TurnTrajectory] = [] self.copies: Optional[AtifCopies] = None @@ -1222,15 +1227,16 @@ def _latency(self, mode: str) -> timedelta: return timedelta(minutes=float(rt.get(mode, rt.get("free", 0)))) async def _schedule_read(self) -> None: - if not self.unread or self.read_at is not None or self.gave_up or self.signed_off: + """When the user first looks at the agent's unread messages: once she's free after the first of them. Nothing + while she already waits to answer (``answer_at``): what the agent sends meanwhile joins that read.""" + if not self.unread or self.read_at is not None or self.answer_at is not None or self.gave_up \ + or self.signed_off: return # A message has no time when the chat env's clock is unarmed; the task's time (another env's clock, else the # computer's) stands in for it. first_at = min(_utc(m["at"]) for m in self.unread if m.get("at")) if any(m.get("at") for m in self.unread) \ else await self.now() at, mode = self._available(first_at) - if self.last_reply_at and at < self.last_reply_at: - at, mode = self._available(self.last_reply_at) self.read_at, self.read_mode = at, mode self.log("user_read_scheduled", read_at=_iso(at), mode=mode, unread=len(self.unread)) @@ -1296,17 +1302,22 @@ async def _next(self) -> bool: time_budget_seconds=self.time_budget, wake_reserve_seconds=reserve) await self._final(now, reason="time_budget") return False - # 1. a read that is due: the user sim reads what the agent sent (one due only at or past end_time is the last - # read, after the final check-in) + # 1. the user's answer that is due: she reads what the agent sent by its time and answers at once; one that + # came due during the agent's turn is written at its time. One due by now is read even past end_time, so it + # reaches the agent with the final check-in, as a reply due by then always did. + if self.answer_at is not None and self.answer_at <= now: + await self.read(self.answer_at) + return True + # 1b. her look that is due: she answers at once, or once her response time is up (``_look``) if self.read_at is not None and self.read_at <= now and self.unread \ and (self.end is None or self.read_at < self.end): - if self.read_at < now: # her time to read passed during the agent's turn: she reads now if she's free + if self.read_at < now: # her time to look passed during the agent's turn: she looks now if she's free at, self.read_mode = self._available(now) - if at > now: # asleep or busy by now: she reads when she's next free + if at > now: # asleep or busy by now: she looks when she's next free self.read_at = at self.log("user_read_scheduled", read_at=_iso(at), mode=self.read_mode, unread=len(self.unread)) return True - await self.read(now) + await self._look(now) return True # past end_time (the clock runs during the agent's turns, so one can end past it): the final check-in next, with # whatever else is due, rather than ordinary wakes that would use up max_wakes without one @@ -1357,17 +1368,24 @@ async def _later(self, now: datetime) -> dict[str, datetime]: "agent_notification": await self._next_due(self.recipient, now), "user_says": await self._next_due(USER_SAYS, now), "held_reply": min((h["deliver_at"] for h in self.held), default=None), - "user_read": self.read_at if self.unread else None} + "user_read": self.read_at if self.unread else None, + "user_answer": self.answer_at} return {k: v for k, v in candidates.items() if v is not None and v > now} async def _final(self, now: datetime, reason: str = "end_time") -> None: """The final check-in: at end_time, the user's ``final`` line, else ``FINAL_DEFAULT_TEXT`` (a line from the - step, not the user); with whatever else is due, and the last-turn notice. A reply held past now stays held, - to be recorded as pending.""" + step, not the user); with whatever else is due, and the last-turn notice. At end_time, the user's answer due by + then comes with it; else it is her last read, recorded as pending.""" step = self.step if reason == "end_time" and self.end > now and await self._armed(): # with no clock, the check-in is now await self.advance(self.end, reason="end_time") now = await self.now() + if reason == "end_time" and self.answer_at is not None and self.answer_at <= now: + # her answer due by the check-in (at end_time itself) comes with it, as a reply due by then always did. Not + # at the time budget's closing: the closing's worst case has room for one read, her last read after it. + await self.read(self.answer_at) + if self.end_reason is not None: # the read ended the run (a user sim error, a blank done): no check-in + return self.final_sent = True lines = await self._take_user_says() replies = [h for h in self.held if h["deliver_at"] <= now] @@ -1382,17 +1400,26 @@ async def _final(self, now: datetime, reason: str = "end_time") -> None: async def _last_read(self) -> None: """After the agent's last turn, the user sim reads what it sent since her last read, at the time she would - (the world's clock stays where the run ended), so her reaction to its wrap-up is recorded; a reply she gives - is held and recorded as pending, never delivered. Not after done ends a one-sitting run, after she gave up, or + answer (the world's clock stays where the run ended), so her reaction to its wrap-up is recorded; a reply she + gives is held and recorded as pending, never delivered. One read, within the closing's room for one: at the + answer she was waiting to give when nothing came after its time; else, from her look at the rest (one due during + the last turn, which went on sending, from now), everything at once when her response time is up. Not after done + ends a one-sitting run (with or without a message), after she gave up, when the user sim gate ended the run, or when the run ended on an error.""" - if not self.unread or self.signed_off or self.gave_up or self.end_reason in ERROR_ENDS: + if not self.unread or self.signed_off or self.gave_up \ + or self.end_reason in (*ERROR_ENDS, "user_done", "user_sim_invalid"): + return + if self.answer_at is not None and not _by_then(self.unread, self.answer_at)[1]: + await self.read(self.answer_at, last=True) return + self.answer_at = None await self._schedule_read() now = await self.now() at = self.read_at or now - if at < now: # she'd have looked during the last turn, which went on sending: she reads it all, from now + if at < now: at, self.read_mode = self._available(now) - await self.read(at, last=True) + self.looked_at = at + await self.read(at + self._latency(self.read_mode), last=True) def _prompt_parts(self) -> list[dict]: """The user's first message, the user sim's opening, as A2A parts, its seed applied.""" @@ -1839,19 +1866,25 @@ def _no_answer(self, error: TimeoutError, turn: str) -> str: return "timeout" async def read(self, now: datetime, last: bool = False) -> None: - """The user sim reads what the agent sent since her last read, at ``now``; ``last`` marks the read after the - run's last wake, whose answer can no longer change how the run ends.""" - phone = [] + """The user sim reads, at ``now``, what the agent sent since her last read, and answers; her answer reaches the + agent at once, her response time having run before the read (``_look``). ``now`` may be past: an answer that + came due during the agent's turn is written at its time, so what came after it (the agent's messages, her + phone's alerts, her own lines) waits for her next look. ``last`` marks the read after the run's last wake, whose + answer can no longer change how the run ends.""" + phone = list(self.phone_later) if self.notification_envs: for it in await take_due(self.notification_envs, USER_PHONE): phone.append({"at": it.get("at"), "channel": it["channel"], "text": "\n\n".join(p["text"] for p in it["parts"] if p.get("kind") == "text")}) + phone, self.phone_later = _by_then(phone, now) self.idle_jumps, self.idle_since = 0, None - seen = list(self.unread) + seen, self.unread = _by_then(self.unread, now) + you_sent, self.you_sent = _by_then(self.you_sent, now) read = {"time": _iso(now), "assistant_messages": [{"at": m.get("at"), "text": m["text"]} for m in seen], "phone": phone, - "you_sent": list(self.you_sent), "done_ends_run": not self.multi_day} - self.unread, self.you_sent, self.read_at = [], [], None + "you_sent": you_sent, "done_ends_run": not self.multi_day} + looked_at = self.looked_at or now + self.read_at, self.looked_at, self.answer_at = None, None, None calls = [] cap = self.step.read_cap_seconds() deadline = time.monotonic() + cap @@ -1876,11 +1909,10 @@ async def ask(text: str) -> dict: self.gate_history.append(("user", ans["message"])) self.history.append({"read": read, "answer": ans}) mode = self.read_mode - latency = self._latency(mode) flagged = (len(ans.get("message") or "") > ASSISTANT_LIKE_MESSAGE_CHARS or bool(re.search(r"^\s*(#|\|)", ans.get("message") or "", re.M))) - entry = self.log("user_sim_read", virtual_time=_iso(now), version=self.version, read=read, - input=ans.get("input"), raw=ans.get("raw"), outcome=ans.get("outcome"), + entry = self.log("user_sim_read", virtual_time=_iso(now), looked_at=_iso(looked_at), version=self.version, + read=read, input=ans.get("input"), raw=ans.get("raw"), outcome=ans.get("outcome"), message=ans.get("message"), used=ans.get("used"), score=ans.get("score"), schema_errors=ans.get("schema_errors"), mode=mode, real_seconds=round(time.time() - t, 1), looks_like_assistant=flagged, @@ -1898,7 +1930,7 @@ async def ask(text: str) -> dict: hook = {"hook": HOOK_NAME, "turn": self.wakes, "read_at": _iso(now), "wrote_at": min((m["at"] for m in seen if m.get("at")), default=None), "outcome": outcome} if outcome in ("reply", "done") and said: - deliver = now + latency + deliver = now reply_to = _reply_to(ans, seen) entry.update(deliver_at=_iso(deliver), reply_to=reply_to, reply_to_candidates=len(seen)) # Not delivered until a wake carries it, which sets user_reads_at; one never delivered (her last read's @@ -1907,7 +1939,6 @@ async def ask(text: str) -> dict: hook.update(delivered=False, deliver_at=_iso(deliver), reply_to=_cut(reply_to)) self.held.append({"deliver_at": deliver, "text": ans["message"], "done": outcome == "done", "hook": hook}) - self.last_reply_at = deliver self.hook_records.append(hook) if outcome == "reply" and said: self.replies += 1 @@ -1927,6 +1958,22 @@ async def ask(text: str) -> dict: self.end_reason = "user_done" if calls and calls[-1].get("error") and not last: self.end_reason = self.end_reason or "user_sim_error" + await self._schedule_read() # what the agent sent after her answer's time: her next look + + async def _look(self, now: datetime) -> None: + """The user looks at what the agent sent, at ``now``. With no response time for the time of day she looks in, + she reads and answers at once; else she answers once it is up (``answer_at``), and what the agent sends + meanwhile waits for that read too. So her answer is to everything it sent by then and reaches it at once, never + after a message she hadn't read; and a single message gets its answer when it always did, her response time + after her look.""" + self.looked_at = now + latency = self._latency(self.read_mode) + if not latency: + await self.read(now) + return + self.read_at, self.answer_at = None, now + latency + self.log("user_answer_scheduled", virtual_time=_iso(now), answer_at=_iso(self.answer_at), mode=self.read_mode, + unread=len(self.unread)) async def _gate(self, ans: dict, ask) -> tuple[dict, dict]: """The user sim's answer after the user-sim gate (user_sim_gate.py): each failing message is held back and the @@ -2051,9 +2098,9 @@ async def _contacts_at_work(self) -> list[dict]: return out async def _pending_at_end(self) -> dict: - """What was still pending when the run ended: her replies held for their response time, the agent's messages - she never read, user lines and alerts for the agent never delivered, its scheduled checks not yet due, and - contact replies still in progress.""" + """What was still pending when the run ended: her replies written but never delivered (her last read's), the + agent's messages she never read (with those she looked at but hadn't answered yet), user lines and alerts for + the agent never delivered, its scheduled checks not yet due, and contact replies still in progress.""" alerts, checks = [], [] for st in await self._notes_state(self.recipient): alerts += [{k: n.get(k) for k in ("at", "channel", "text", "trigger_id")} @@ -2434,6 +2481,13 @@ def quoting(quote: Any) -> list[dict]: return None +def _by_then(items: list[dict], t: datetime) -> tuple[list[dict], list[dict]]: + """``items`` (each with its ``at``) split, in order, into those at or before ``t`` and those after; one with no + time (a clock that wasn't armed) counts as before.""" + before = [i for i in items if not i.get("at") or _utc(i["at"]) <= t] + return before, [i for i in items if i.get("at") and _utc(i["at"]) > t] + + def _cut(item: Optional[dict]) -> Optional[dict]: """``item`` with its text cut to PENDING_TEXT_CHARS, for what the run's metadata keeps.""" if not item or len(item.get("text") or "") <= PENDING_TEXT_CHARS: @@ -2466,9 +2520,9 @@ def _small(value: Any, depth: int = 0) -> Any: # The timeline fields the process log may show as they are: names, ids, times, states and settings, never what a person # or the agent wrote. Any other string is logged as its length, a list as its count, a dict as its keys' view. _LOGGED_AS_IS = frozenset({ - "virtual_time", "from", "to", "reason", "state", "outcome", "mode", "read_at", "deliver_at", "end_time", "agent", - "agent_role", "user_sim", "version", "user_model", "time_zone", "kind", "trigger_id", "env_id", "phase", - "error_type", "matched_by", "at", "wake", "n", "trajectory_url", "object_url"}) + "virtual_time", "from", "to", "reason", "state", "outcome", "mode", "read_at", "deliver_at", "looked_at", + "answer_at", "end_time", "agent", "agent_role", "user_sim", "version", "user_model", "time_zone", "kind", + "trigger_id", "env_id", "phase", "error_type", "matched_by", "at", "wake", "n", "trajectory_url", "object_url"}) # Past this length even one of those fields is logged as its length. LOGGED_TEXT_CHARS = 200 diff --git a/tst/unit/task_step/test_always_on_endings.py b/tst/unit/task_step/test_always_on_endings.py index 81a85261a..3da59114b 100644 --- a/tst/unit/task_step/test_always_on_endings.py +++ b/tst/unit/task_step/test_always_on_endings.py @@ -125,7 +125,9 @@ async def test_the_user_sim_reads_the_wrap_up_and_her_reaction_and_held_reply_ar assert tail.index("message_to_user") < tail.index("user_sim_read") [read] = rig.events(ctx, "user_sim_read") assert read["last_read"] is True and read["outcome"] == "reply" - assert read["virtual_time"] == "2026-11-11T14:00:00Z" and read["deliver_at"] == "2026-11-11T16:30:00Z" + # she looks at the wrap-up at 9 AM and answers once her response time is up: the answer she'd send then + assert read["looked_at"] == "2026-11-11T14:00:00Z" + assert read["virtual_time"] == "2026-11-11T16:30:00Z" and read["deliver_at"] == "2026-11-11T16:30:00Z" held = rig.record(ctx)["pending_at_end"]["held_replies"] assert held == {"count": 1, "items": [{"at": "2026-11-11T16:30:00Z", "text": "amazing, book La Ola too", "done": False}]} @@ -167,9 +169,10 @@ def wraps_up_late(n, texts, rig): ctx = await rig.run(rig.step(max_wakes=1), rig.context(user=DAY)) [read] = rig.reads - assert read["time"] == "2026-11-10T12:30:00Z" # 7:30 AM, when she wakes + assert read["time"] == "2026-11-10T12:45:00Z" # she looks at 7:30 AM, when she wakes, and answers 15 min later [event] = rig.events(ctx, "user_sim_read") - assert (event["mode"], event["deliver_at"]) == ("morning", "2026-11-10T12:45:00Z") + assert (event["mode"], event["looked_at"], event["deliver_at"]) == ( + "morning", "2026-11-10T12:30:00Z", "2026-11-10T12:45:00Z") @pytest.mark.asyncio @@ -188,9 +191,10 @@ def runs_late(n, texts, rig): ctx = await rig.run(rig.step(max_wakes=3), rig.context(user=DAY)) [read, *_] = rig.reads - assert read["time"] == "2026-11-10T12:30:00Z" # 7:30 AM, when she wakes, not at midnight + assert read["time"] == "2026-11-10T12:45:00Z" # she looks at 7:30 AM, when she wakes, not at midnight [event, *_] = rig.events(ctx, "user_sim_read") - assert (event["mode"], event["deliver_at"]) == ("morning", "2026-11-10T12:45:00Z") + assert (event["mode"], event["looked_at"], event["deliver_at"]) == ( + "morning", "2026-11-10T12:30:00Z", "2026-11-10T12:45:00Z") @pytest.mark.asyncio diff --git a/tst/unit/task_step/test_always_on_held_replies.py b/tst/unit/task_step/test_always_on_held_replies.py new file mode 100644 index 000000000..08f3ea4e9 --- /dev/null +++ b/tst/unit/task_step/test_always_on_held_replies.py @@ -0,0 +1,577 @@ +"""The user's response time holds the agent's messages, not her answer (FD-7185). She first looks when she's free, then, +once her response time is up, reads everything the agent sent by then and answers at once. So an answer never reaches +the agent after a newer message of its that she hadn't read when she wrote it, and a single message still gets its +answer at the same time, in the same wake, with the same time label as before.""" + +from __future__ import annotations + +import pytest + +from agent_env.task_step.context import AgentTurnInfraError +from agent_env.task_step.task_steps import always_on as ao +from agent_env.task_step.task_steps.agent import user_sim_versions +from tst.unit.task_step.always_on_harness import Fail, Rig +from tst.unit.task_step.test_prompt_agent_user_side import _SWAP, pattern_judge # noqa: F401 + +pytestmark = pytest.mark.usefixtures("local_stores") + +# Linda's day in New York (the rig's T0 is Mon Nov 9, 9:00 AM there): an hour to answer at work, as in the concert task. +WORK_HOUR = {"schedule": {"wake": "07:30", "sleep": "23:30", "work": ["09:00", "18:00"]}, + "response_times": {"work": 60, "free": 30, "morning": 15}} +SEATS = "holding 2 seats at $124.66 total, OK to buy?" +VIP = "those sold out. 2 VIP seats are $480.83 total, want them?" + + +class LatestAnswer: + """A user sim that answers the latest message she read: yes to the seats, no to VIP.""" + + def __init__(self, rig: Rig): + self.rig = rig + + def setup(self, version, person): + return {"system_prompt": "you are Linda", "output_format": None} + + async def answer(self, version, person, history, read, ask): + self.rig.reads.append(read) + latest = read["assistant_messages"][-1]["text"] + return {"outcome": "reply", "message": "no vip" if "VIP" in latest else "yes, buy them", + "replying_to": len(read["assistant_messages"])} + + parse = staticmethod(user_sim_versions.parse) + + +def _woke(ctx, rig): + return [(w["virtual_time"], w["woke_by"]) for w in rig.events(ctx, "wake")] + + +def _no_stale_answer(ctx, rig): + """Every answer reached the agent stamped with the time she wrote it, and she wrote it having read every message + the agent sent up to that time: none answers an older message while a newer one waited unread.""" + sent = [(ao._utc(e["virtual_time"]), e["text"]) for e in rig.events(ctx, "message_to_user")] + seen: set[str] = set() + for read in rig.events(ctx, "user_sim_read"): + seen |= {m["text"] for m in read["read"]["assistant_messages"]} + if read.get("deliver_at"): + assert read["deliver_at"] == read["virtual_time"], read + unread = [text for at, text in sent if at <= ao._utc(read["deliver_at"]) and text not in seen] + assert not unread, f"the answer at {read['deliver_at']} was written before she read {unread}" + + +# ---- the concert task's morning ------------------------------------------------------------------------------------ + +@pytest.mark.asyncio +async def test_a_message_sent_while_she_is_busy_is_read_with_the_one_before_and_gets_the_only_answer(monkeypatch, + tmp_path): + """psi-ts-gatelark-new-country-act: the agent asks about the seats, they sell out while Linda is at work, it offers + VIP. Her hour up, she reads both and answers the VIP offer; her yes to the seats is never written, so the agent + can't take it as a yes to VIP.""" + bought = [] + + def agent(n, texts, rig): + if n == 1: + rig.message(SEATS) + return "asked" + if any("sold out" in t for t in texts): + rig.message(VIP) + return "offered VIP" + if any("yes, buy them" in t for t in texts): + bought.append("2 VIP seats, $480.83") + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + rig.plugin = LatestAnswer(rig) + await rig.arm() + rig.triggers(rig.notify_at("sellout", "2026-11-09T14:15:00Z", "Ticketline: the $124.66 seats sold out", + channel="Gmail")) + ctx = await rig.run(rig.step(), rig.context(user=WORK_HOUR)) + + assert bought == [] + assert not any("yes, buy them" in t for texts in rig.sent for t in texts) + [read] = rig.reads + assert read["time"] == "2026-11-09T15:00:00Z" + assert [m["text"] for m in read["assistant_messages"]] == [SEATS, VIP] + [event] = rig.events(ctx, "user_sim_read") + assert event["virtual_time"] == event["deliver_at"] == "2026-11-09T15:00:00Z" + assert event["looked_at"] == "2026-11-09T14:00:00Z" and event["mode"] == "work" + assert event["reply_to"]["text"] == VIP + assert _woke(ctx, rig) == [("2026-11-09T14:00:00Z", ["user_request"]), + ("2026-11-09T14:15:00Z", ["notification:Gmail"]), + ("2026-11-09T15:00:00Z", ["user_reply"])] + assert "[Mon Nov 9, 10:00 AM EST] Linda: no vip" in rig.sent[2] + [scheduled] = rig.events(ctx, "user_answer_scheduled") + assert (scheduled["virtual_time"], scheduled["answer_at"], scheduled["mode"]) == ( + "2026-11-09T14:00:00Z", "2026-11-09T15:00:00Z", "work") + _no_stale_answer(ctx, rig) + assert rig.record(ctx)["end_reason"] == "finished_nothing_pending" + + +@pytest.mark.asyncio +async def test_another_message_does_not_restart_her_response_time(monkeypatch, tmp_path): + """Her hour counts from her first look, so an agent can't push her answer later by writing again.""" + def agent(n, texts, rig): + if n == 1: + rig.message("found two houses") + return "sent" + if n == 2: + rig.message("and a third, near the beach") + return "sent" + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=[{"outcome": "reply", "message": "the beach one"}]) + await rig.arm() + rig.triggers(rig.notify_at("listing", "2026-11-09T14:50:00Z", "Airbnb: new listing", channel="Gmail")) + ctx = await rig.run(rig.step(), rig.context(user=WORK_HOUR)) + + [read] = rig.reads + assert read["time"] == "2026-11-09T15:00:00Z" + assert [m["text"] for m in read["assistant_messages"]] == ["found two houses", "and a third, near the beach"] + assert _woke(ctx, rig)[2] == ("2026-11-09T15:00:00Z", ["user_reply"]) + _no_stale_answer(ctx, rig) + + +# ---- one message: the same answer time as before ------------------------------------------------------------------- + +def _asks(rig): + rig.message("blue house or green?") + return "asked" + + +def _quiet(rig): + rig.quiet() + return "" + + +def _turn_runs_to(until): + """The agent's first turn asks, and goes on (the task's clock running) until ``until``.""" + def play(rig): + rig.message("blue house or green?") + rig.gw._clock.advance(until) + return "asked" + return play + + +def _quiet_turn_runs_to(until): + """A turn that sends nothing, the task's clock running on to ``until``.""" + def play(rig): + rig.gw._clock.advance(until) + rig.quiet() + return "" + return play + + +def _wakes(*pairs): + return [(f"2026-11-{at}:00Z", woke_by) for at, woke_by in pairs] + + +BLUE = "Linda: the blue one" +# The agent's first turn (default: it asks), a later alert and the turn it starts (default: a quiet one), her schedule, +# the step's settings; then every wake the agent got (time and cause), the label on her answer (none when it never +# reaches the agent), what was left pending and the end reason. Each case was run on main (fb5a5a65) and on this change +# and is the same on both, down to every text the agent got: only what the user sim reads, and when, moves. +SAME_AS_BEFORE = { + "work": dict(wakes=_wakes(("09T14:00", ["user_request"]), ("09T15:00", ["user_reply"])), + stamped="[Mon Nov 9, 10:00 AM EST] " + BLUE), + "free": dict(t0="2026-11-09T23:30:00Z", wakes=_wakes(("09T23:30", ["user_request"]), ("10T00:00", ["user_reply"])), + stamped="[Mon Nov 9, 7:00 PM EST] " + BLUE), + "night_then_morning": dict(t0="2026-11-10T05:00:00Z", + wakes=_wakes(("10T05:00", ["user_request"]), ("10T12:45", ["user_reply"])), + stamped="[Tue Nov 10, 7:45 AM EST] " + BLUE), + "busy_block": dict(user={**WORK_HOUR, "schedule": {**WORK_HOUR["schedule"], "busy": [ + {"start": "2026-11-09T09:00", "end": "2026-11-09T11:00"}]}}, + wakes=_wakes(("09T14:00", ["user_request"]), ("09T17:00", ["user_reply"])), + stamped="[Mon Nov 9, 12:00 PM EST] " + BLUE), + "answer_lands_after_bedtime": dict(t0="2026-11-10T04:15:00Z", + wakes=_wakes(("10T04:15", ["user_request"]), ("10T04:45", ["user_reply"])), + stamped="[Mon Nov 9, 11:45 PM EST] " + BLUE), + "the_asking_turn_runs_on": dict(first=_turn_runs_to("2026-11-09T14:40:00Z"), + wakes=_wakes(("09T14:00", ["user_request"]), ("09T15:40", ["user_reply"])), + stamped="[Mon Nov 9, 10:40 AM EST] " + BLUE), + "a_quiet_turn_spans_her_answer": dict(alert="2026-11-09T14:50:00Z", second=_quiet_turn_runs_to("2026-11-09T15:20:00Z"), + wakes=_wakes(("09T14:00", ["user_request"]), + ("09T14:50", ["notification:Gmail"]), + ("09T15:20", ["user_reply"])), + stamped="[Mon Nov 9, 10:00 AM EST] " + BLUE), + "no_response_times": dict(user={"schedule": WORK_HOUR["schedule"]}, + wakes=_wakes(("09T14:00", ["user_request"]), ("09T14:00", ["user_reply"])), + stamped="[Mon Nov 9, 9:00 AM EST] " + BLUE), + "an_alert_in_the_same_minute_comes_with_it": dict( + alert="2026-11-09T15:00:30Z", + wakes=[("2026-11-09T14:00:00Z", ["user_request"]), ("2026-11-09T15:00:30Z", ["notification:Gmail", "user_reply"])], + stamped="[Mon Nov 9, 10:00 AM EST] " + BLUE), + "her_answer_at_end_time_comes_with_the_check_in": dict( + step={"end_time": "2026-11-09T15:00:00Z"}, end="end_time", + wakes=_wakes(("09T14:00", ["user_request"]), ("09T15:00", ["user_reply", "step:final"])), + stamped="[Mon Nov 9, 10:00 AM EST] " + BLUE), + "a_turn_past_the_end_and_her_answer_gets_it_with_the_check_in": dict( + alert="2026-11-09T14:50:00Z", second=_quiet_turn_runs_to("2026-11-09T15:10:00Z"), + step={"end_time": "2026-11-09T14:55:00Z"}, end="end_time", + wakes=_wakes(("09T14:00", ["user_request"]), ("09T14:50", ["notification:Gmail"]), + ("09T15:10", ["user_reply", "step:final"])), + stamped="[Mon Nov 9, 10:00 AM EST] " + BLUE), + "her_answer_before_end_time": dict( + alert="2026-11-09T14:20:00Z", step={"end_time": "2026-11-09T15:30:00Z"}, end="end_time", + wakes=_wakes(("09T14:00", ["user_request"]), ("09T14:20", ["notification:Gmail"]), + ("09T15:00", ["user_reply"]), ("09T15:30", ["step:final"])), + stamped="[Mon Nov 9, 10:00 AM EST] " + BLUE), + "her_answer_after_end_time": dict( + step={"end_time": "2026-11-09T14:30:00Z"}, end="end_time", + wakes=_wakes(("09T14:00", ["user_request"]), ("09T14:30", ["step:final"])), + held=[("2026-11-09T15:00:00Z", "the blue one")]), + "the_final_turn_runs_quietly_past_her_answer": dict( + second=_quiet_turn_runs_to("2026-11-09T15:10:00Z"), step={"end_time": "2026-11-09T14:50:00Z"}, end="end_time", + wakes=_wakes(("09T14:00", ["user_request"]), ("09T14:50", ["step:final"])), + held=[("2026-11-09T15:00:00Z", "the blue one")]), + "max_wakes": dict( + alert="2026-11-09T14:20:00Z", step={"max_wakes": 2}, end="max_wakes", + wakes=_wakes(("09T14:00", ["user_request"]), ("09T14:20", ["notification:Gmail"])), + held=[("2026-11-09T15:00:00Z", "the blue one")]), +} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("case", SAME_AS_BEFORE.values(), ids=SAME_AS_BEFORE.keys()) +async def test_a_single_message_gets_its_answer_at_the_same_time_as_before(monkeypatch, tmp_path, case): + plays = {1: case.get("first", _asks), 2: case.get("second", _quiet)} + rig = Rig(monkeypatch, tmp_path, t0=case.get("t0", "2026-11-09T14:00:00Z"), + agent=lambda n, texts, rig: plays.get(n, _quiet)(rig), + answers=[{"outcome": "reply", "message": "the blue one"}]) + await rig.arm() + if case.get("alert"): + rig.triggers(rig.notify_at("alert", case["alert"], "Airbnb: a new listing", channel="Gmail")) + ctx = await rig.run(rig.step(**case.get("step", {})), rig.context(user=case.get("user", WORK_HOUR))) + + assert _woke(ctx, rig) == case["wakes"] + got_it = [n for n, texts in enumerate(rig.sent) if any(BLUE in t for t in texts)] + if case.get("stamped"): + [n] = got_it + assert "user_reply" in case["wakes"][n][1] and case["stamped"] in rig.sent[n] + else: + assert got_it == [] + record = rig.record(ctx) + assert [(h["at"], h["text"]) for h in record["pending_at_end"]["held_replies"]["items"]] == case.get("held", []) + assert record["end_reason"] == case.get("end", "finished_nothing_pending") + assert len(rig.reads) == 1 + + +@pytest.mark.asyncio +async def test_a_single_message_is_read_when_she_answers_and_what_she_reads_is_as_of_then(monkeypatch, tmp_path): + """She writes her answer at the time it reaches the agent, so her read is stamped then and holds the phone alerts + and her own lines from before then.""" + rig = Rig(monkeypatch, tmp_path, agent=lambda n, texts, rig: _asks(rig) if n == 1 else _quiet(rig), + answers=[{"outcome": "reply", "message": "the blue one"}]) + await rig.arm() + rig.triggers(rig.notify_at("phone", "2026-11-09T14:30:00Z", "Airbnb: Pedro replied", channel="Gmail", + to=ao.USER_PHONE)) + ctx = await rig.run(rig.step(), rig.context(user=WORK_HOUR)) + + [read] = rig.reads + assert read["time"] == "2026-11-09T15:00:00Z" + assert [p["text"] for p in read["phone"]] == ["Airbnb: Pedro replied"] + [event] = rig.events(ctx, "user_sim_read") + assert (event["looked_at"], event["virtual_time"], event["deliver_at"]) == ( + "2026-11-09T14:00:00Z", "2026-11-09T15:00:00Z", "2026-11-09T15:00:00Z") + + +# ---- her answer time falls inside an agent turn --------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_an_answer_due_during_a_turn_holds_what_was_sent_by_then_and_later_messages_wait_for_her_next_read( + monkeypatch, tmp_path): + """She answers at 10:00 with what she had by then; the 10:10 message waits for her next look. Her answer keeps its + 10:00 label, so the agent can see the messages crossed.""" + def agent(n, texts, rig): + if n == 1: + rig.message("blue house or green?") + return "asked" + if n == 2: # woken at 9:50 by an alert; works on past 10:00, her phone getting texts meanwhile + rig.gw._clock.advance("2026-11-09T14:55:00Z") + rig.message("the blue one has a pool, fyi") + rig.gw._clock.advance("2026-11-09T14:58:00Z") + rig.gw._notifications.notify("Messages", "Sam: are we on?", to=ao.USER_PHONE) + rig.gw._clock.advance("2026-11-09T15:05:00Z") + rig.gw._notifications.notify("Messages", "Sam: ok see you then", to=ao.USER_PHONE) + rig.gw._clock.advance("2026-11-09T15:10:00Z") + rig.message("also: dinner at 8 on Saturday?") + rig.gw._clock.advance("2026-11-09T15:20:00Z") + return "sent" + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=[{"outcome": "reply", "message": "blue!"}, + {"outcome": "reply", "message": "8 works"}]) + await rig.arm() + rig.triggers(rig.notify_at("alert", "2026-11-09T14:50:00Z", "Airbnb: Pedro replied", channel="Gmail")) + ctx = await rig.run(rig.step(), rig.context(user=WORK_HOUR)) + + first, second = rig.reads + assert first["time"] == "2026-11-09T15:00:00Z" + assert [m["text"] for m in first["assistant_messages"]] == ["blue house or green?", "the blue one has a pool, fyi"] + assert [p["text"] for p in first["phone"]] == ["Sam: are we on?"] + # her next look is at the turn's end (10:20), as a look missed during a turn always is; an hour later she answers + assert second["time"] == "2026-11-09T16:20:00Z" + assert [m["text"] for m in second["assistant_messages"]] == ["also: dinner at 8 on Saturday?"] + assert [p["text"] for p in second["phone"]] == ["Sam: ok see you then"] + woke = _woke(ctx, rig) + assert woke[2] == ("2026-11-09T15:20:00Z", ["user_reply"]) + assert "[Mon Nov 9, 10:00 AM EST] Linda: blue!" in rig.sent[2] + assert woke[3] == ("2026-11-09T16:20:00Z", ["user_reply"]) + _no_stale_answer(ctx, rig) + + +@pytest.mark.asyncio +async def test_a_message_left_after_an_answer_due_during_a_turn_is_read_even_when_she_had_nothing_to_say(monkeypatch, + tmp_path): + """No reply means no wake to deliver one: her next look is set by the read itself, so the later message isn't left + unread with nothing to wake anyone.""" + def agent(n, texts, rig): + if n == 1: + rig.message("fyi: the host confirmed") + return "sent" + if n == 2: # woken at 9:50, works on past 10:00 + rig.gw._clock.advance("2026-11-09T15:10:00Z") + rig.message("blue house or green?") + rig.gw._clock.advance("2026-11-09T15:20:00Z") + return "asked" + return _quiet(rig) + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=[{"outcome": "no_reply", "message": ""}, + {"outcome": "reply", "message": "blue"}]) + await rig.arm() + rig.triggers(rig.notify_at("alert", "2026-11-09T14:50:00Z", "Airbnb: Pedro replied", channel="Gmail")) + ctx = await rig.run(rig.step(), rig.context(user=WORK_HOUR)) + + first, second = rig.reads + assert first["time"] == "2026-11-09T15:00:00Z" + assert [m["text"] for m in first["assistant_messages"]] == ["fyi: the host confirmed"] + assert second["time"] == "2026-11-09T16:20:00Z" + assert [m["text"] for m in second["assistant_messages"]] == ["blue house or green?"] + assert _woke(ctx, rig)[-1] == ("2026-11-09T16:20:00Z", ["user_reply"]) + assert rig.record(ctx)["end_reason"] == "finished_nothing_pending" + + +# ---- what her answer can do ----------------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_a_done_after_her_response_time_ends_a_one_sitting_run_after_the_agent_s_turn_on_it(monkeypatch, + tmp_path): + def agent(n, texts, rig): + if n == 1: + rig.message("all set: shelves restocked") + return "sent" + if n == 2: + rig.message("glad to help!") + return "sent" + return _quiet(rig) + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=[{"outcome": "done", "message": "thanks!"}]) + await rig.arm() + rig.triggers(rig.notify_at("later", "2026-11-10T14:00:00Z", "a new order", channel="Craftweb")) + ctx = await rig.run(rig.step(), rig.context(user=WORK_HOUR)) + + assert rig.record(ctx)["end_reason"] == "user_done" and len(rig.sent) == 2 + assert _woke(ctx, rig)[1] == ("2026-11-09T15:00:00Z", ["user_reply"]) + assert "[Mon Nov 9, 10:00 AM EST] Linda: thanks!" in rig.sent[1] + [event] = rig.events(ctx, "user_sim_read") + assert event["ends_run"] is True and event["virtual_time"] == "2026-11-09T15:00:00Z" + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("pattern_judge") +async def test_the_user_sim_gate_checks_an_answer_given_after_her_response_time(monkeypatch, tmp_path): + """The answer is checked when she writes it, and the rewrite reaches the agent at that same time.""" + rig = Rig(monkeypatch, tmp_path, agent=lambda n, texts, rig: _asks(rig) if n == 1 else _quiet(rig), + answers=[{"outcome": "reply", "message": _SWAP}], + user_texts=('{"outcome": "reply", "message": "blue, I think?", "used": "none"}',)) + await rig.arm() + ctx = await rig.run(rig.step(max_wakes=4, user_sim_gate={"patterns": True, "judge_model": "judge"}), + rig.context(user=WORK_HOUR)) + + [event] = rig.events(ctx, "user_sim_read") + assert event["virtual_time"] == event["deliver_at"] == "2026-11-09T15:00:00Z" + assert event["message"] == "blue, I think?" and event["user_sim_gate"]["first_message"] == _SWAP + assert _woke(ctx, rig)[1] == ("2026-11-09T15:00:00Z", ["user_reply"]) + assert "[Mon Nov 9, 10:00 AM EST] Linda: blue, I think?" in rig.sent[1] + + +# ---- the end of the run --------------------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_an_answer_due_after_the_end_is_recorded_as_held_at_the_time_it_would_have_arrived(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=lambda n, texts, rig: _asks(rig) if n == 1 else _quiet(rig), + answers=[{"outcome": "reply", "message": "the blue one"}]) + await rig.arm() + ctx = await rig.run(rig.step(end_time="2026-11-09T14:30:00Z"), rig.context(user=WORK_HOUR)) + + assert not any("the blue one" in t for texts in rig.sent for t in texts) + held = rig.record(ctx)["pending_at_end"]["held_replies"] + assert held == {"count": 1, "items": [{"at": "2026-11-09T15:00:00Z", "text": "the blue one", "done": False}]} + [read] = rig.reads + assert read["time"] == "2026-11-09T15:00:00Z" + assert rig.record(ctx)["end_reason"] == "end_time" + + +@pytest.mark.asyncio +async def test_a_wrap_up_sent_before_her_answer_time_is_read_with_the_message_she_was_waiting_to_answer(monkeypatch, + tmp_path): + def agent(n, texts, rig): + if n == 1: + return _asks(rig) + if n == 2: # the final check-in at 9:30 + rig.message("wrap-up: blue house on hold till Friday") + return "done" + return _quiet(rig) + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=[{"outcome": "reply", "message": "blue, thanks"}]) + await rig.arm() + ctx = await rig.run(rig.step(end_time="2026-11-09T14:30:00Z"), rig.context(user=WORK_HOUR)) + + [read] = rig.reads + assert read["time"] == "2026-11-09T15:00:00Z" + assert [m["text"] for m in read["assistant_messages"]] == ["blue house or green?", + "wrap-up: blue house on hold till Friday"] + [event] = rig.events(ctx, "user_sim_read") + assert event["last_read"] is True + assert rig.record(ctx)["pending_at_end"]["held_replies"]["items"][0]["at"] == "2026-11-09T15:00:00Z" + + +@pytest.mark.asyncio +async def test_an_answer_due_during_the_final_turn_is_read_once_with_the_wrap_up_sent_after_it(monkeypatch, tmp_path): + """The final turn runs past her answer time and sends its wrap-up after it. The closing has room for one read, so + she reads both once, from her look when the turn ended and her response time: her reaction to the wrap-up is + recorded, and the step stays within the closing's worst case.""" + def agent(n, texts, rig): + if n == 1: + return _asks(rig) + if n == 2: # the final check-in at 9:50, running to 10:10 + rig.gw._clock.advance("2026-11-09T15:05:00Z") + rig.message("wrap-up: blue house on hold till Friday") + rig.gw._clock.advance("2026-11-09T15:10:00Z") + return "done" + return _quiet(rig) + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=[{"outcome": "reply", "message": "blue, thanks!"}]) + await rig.arm() + ctx = await rig.run(rig.step(end_time="2026-11-09T14:50:00Z"), rig.context(user=WORK_HOUR)) + + [read] = rig.reads + assert read["time"] == "2026-11-09T16:10:00Z" # her look at 10:10, when the turn ended, and her hour + assert [m["text"] for m in read["assistant_messages"]] == ["blue house or green?", + "wrap-up: blue house on hold till Friday"] + [event] = rig.events(ctx, "user_sim_read") + assert event["last_read"] is True and event["looked_at"] == "2026-11-09T15:10:00Z" + held = rig.record(ctx)["pending_at_end"]["held_replies"]["items"] + assert [(h["at"], h["text"]) for h in held] == [("2026-11-09T16:10:00Z", "blue, thanks!")] + assert rig.record(ctx)["pending_at_end"]["unread_by_user"]["count"] == 0 + assert rig.record(ctx)["end_reason"] == "end_time" + + +@pytest.mark.asyncio +async def test_at_the_time_budget_s_closing_an_answer_due_is_her_last_read_not_part_of_the_closing(monkeypatch, + tmp_path): + """The closing's worst case has room for one read: her last read, after the closing turn. So an answer due when the + budget closes the run is written then, and recorded as pending, rather than read before the closing wake.""" + rig = Rig(monkeypatch, tmp_path, agent=lambda n, texts, rig: _asks(rig) if n == 1 else _quiet(rig), + answers=[{"outcome": "reply", "message": "the blue one"}]) + + def spent(run): # an hour a turn, and the budget is up once the clock reaches her answer time + due = run.answer_at is not None and run.answer_at <= ao._utc(rig.gw._clock.read()["virtual_time"]) + return 3600.0 * len(rig.sent) + (9000.0 if due else 0.0) + + monkeypatch.setattr(ao._Run, "spent", spent) + await rig.arm() + ctx = await rig.run(rig.step(time_budget_seconds=12120), rig.context(user=WORK_HOUR)) + + record = rig.record(ctx) + assert record["end_reason"] == "time_budget" + assert _woke(ctx, rig) == _wakes(("09T14:00", ["user_request"]), ("09T15:00", ["step:final"])) + assert not any(BLUE in t for texts in rig.sent for t in texts) + [event] = rig.events(ctx, "user_sim_read") + assert event["last_read"] is True and event["virtual_time"] == "2026-11-09T15:00:00Z" + assert [(h["at"], h["text"]) for h in record["pending_at_end"]["held_replies"]["items"]] == [ + ("2026-11-09T15:00:00Z", "the blue one")] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("answer,gate,end", [ + ({"outcome": "done", "message": ""}, None, "user_done"), + ({"outcome": "reply", "message": _SWAP}, {"patterns": True, "judge_model": "judge", "max_rewrites": 0, + "on_fail": "end"}, "user_sim_invalid"), +], ids=["a_done_with_no_message", "the_user_sim_gate"]) +@pytest.mark.usefixtures("pattern_judge") +async def test_an_answer_that_ends_the_run_is_her_last_read_even_with_messages_sent_after_its_time( + monkeypatch, tmp_path, answer, gate, end): + """Her answer, due during a turn that went on sending, ends the run: she has no further read, so the record holds + the end she chose and the message she never read, not a second reaction.""" + def agent(n, texts, rig): + if n == 1: + return _asks(rig) + if n == 2: # an alert at 9:50; the turn runs to 10:10 and writes again at 10:05 + rig.gw._clock.advance("2026-11-09T15:05:00Z") + rig.message("also: dinner at 8?") + rig.gw._clock.advance("2026-11-09T15:10:00Z") + return "sent" + return _quiet(rig) + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=[answer]) + await rig.arm() + rig.triggers(rig.notify_at("alert", "2026-11-09T14:50:00Z", "Airbnb: a new listing", channel="Gmail")) + ctx = await rig.run(rig.step(**({"user_sim_gate": gate} if gate else {})), rig.context(user=WORK_HOUR)) + + record = rig.record(ctx) + assert record["end_reason"] == end + [event] = rig.events(ctx, "user_sim_read") + assert event["virtual_time"] == "2026-11-09T15:00:00Z" and not event.get("last_read") + assert [m["text"] for m in record["pending_at_end"]["unread_by_user"]["items"]] == ["also: dinner at 8?"] + + +@pytest.mark.asyncio +async def test_a_done_with_no_message_due_at_end_time_ends_the_run_without_the_check_in(monkeypatch, tmp_path): + """Her answer due at end_time is read before the check-in; a done with no message ends the run there, so the agent + gets no final check-in after she signed off.""" + rig = Rig(monkeypatch, tmp_path, agent=lambda n, texts, rig: _asks(rig) if n == 1 else _quiet(rig), + answers=[{"outcome": "done", "message": ""}]) + await rig.arm() + ctx = await rig.run(rig.step(end_time="2026-11-09T15:00:00Z"), rig.context(user=WORK_HOUR)) + + assert _woke(ctx, rig) == _wakes(("09T14:00", ["user_request"])) + [event] = rig.events(ctx, "user_sim_read") + assert event["virtual_time"] == "2026-11-09T15:00:00Z" and event["outcome"] == "done" + assert rig.record(ctx)["end_reason"] == "user_done" + + +@pytest.mark.asyncio +async def test_a_run_cut_at_max_wakes_still_records_the_answer_she_was_waiting_to_give(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=lambda n, texts, rig: _asks(rig) if n == 1 else _quiet(rig), + answers=[{"outcome": "reply", "message": "the blue one"}]) + await rig.arm() + rig.triggers(rig.notify_at("alert", "2026-11-09T14:20:00Z", "Airbnb: a new listing", channel="Gmail")) + ctx = await rig.run(rig.step(max_wakes=2), rig.context(user=WORK_HOUR)) + + assert rig.record(ctx)["end_reason"] == "max_wakes" + [read] = rig.reads + assert read["time"] == "2026-11-09T15:00:00Z" + held = rig.record(ctx)["pending_at_end"]["held_replies"]["items"] + assert [(h["at"], h["text"]) for h in held] == [("2026-11-09T15:00:00Z", "the blue one")] + + +@pytest.mark.asyncio +async def test_a_run_that_breaks_while_she_waits_records_her_unread_messages_and_no_answer(monkeypatch, tmp_path): + def agent(n, texts, rig): + if n == 1: + return _asks(rig) + return Fail("the sandbox died", error_type=ao.INFRA_ERROR) + + rig = Rig(monkeypatch, tmp_path, agent=agent, answers=[{"outcome": "reply", "message": "the blue one"}]) + await rig.arm() + rig.triggers(rig.notify_at("alert", "2026-11-09T14:20:00Z", "Airbnb: a new listing", channel="Gmail")) + ctx = rig.context(user=WORK_HOUR) + with pytest.raises(AgentTurnInfraError): + await rig.run(rig.step(), ctx) + + record = rig.record(ctx) + assert record["end_reason"] == ao.AGENT_TURN_INFRA_ERROR + assert rig.reads == [] + assert [m["text"] for m in record["pending_at_end"]["unread_by_user"]["items"]] == ["blue house or green?"] + assert record["pending_at_end"]["held_replies"]["count"] == 0 diff --git a/tst/unit/task_step/test_always_on_loop.py b/tst/unit/task_step/test_always_on_loop.py index 5cfc50171..d94313d78 100644 --- a/tst/unit/task_step/test_always_on_loop.py +++ b/tst/unit/task_step/test_always_on_loop.py @@ -93,8 +93,8 @@ async def test_a_reply_is_held_for_the_reply_time_then_wakes_the_agent(monkeypat ctx = await rig.run(rig.step(), rig.context(user=LINDA_DAY)) [read] = rig.events(ctx, "user_sim_read") - assert read["virtual_time"] == "2026-11-09T14:00:00Z" and read["mode"] == "work" - assert read["deliver_at"] == "2026-11-09T16:30:00Z" + assert read["looked_at"] == "2026-11-09T14:00:00Z" and read["mode"] == "work" + assert read["virtual_time"] == read["deliver_at"] == "2026-11-09T16:30:00Z" assert _woke(ctx, rig)[1] == ("2026-11-09T16:30:00Z", ["user_reply"]) assert "[Mon Nov 9, 11:30 AM EST] Linda: the blue one" in rig.sent[1] @@ -111,8 +111,8 @@ async def test_the_user_reads_once_awake_and_not_busy(monkeypatch, tmp_path): [scheduled, *_] = rig.events(ctx, "user_read_scheduled") assert scheduled["read_at"] == "2026-11-10T15:00:00Z" # past the night and the 7-10 AM block [first, second] = rig.events(ctx, "user_sim_read") - assert first["virtual_time"] == "2026-11-10T15:00:00Z" - assert first["deliver_at"] == "2026-11-10T15:15:00Z" + assert first["looked_at"] == "2026-11-10T15:00:00Z" + assert first["virtual_time"] == first["deliver_at"] == "2026-11-10T15:15:00Z" @pytest.mark.asyncio @@ -127,7 +127,7 @@ def two(rig): await rig.run(rig.step(), rig.context(user=LINDA_DAY)) [read] = rig.reads - assert read["time"] == "2026-11-10T12:30:00Z" + assert read["time"] == "2026-11-10T12:45:00Z" # her look at 7:30 AM, then her morning response time assert [m["text"] for m in read["assistant_messages"]] == ["house: the blue one, $855", "dinner: La Ola, Saturday 8pm"] diff --git a/tst/unit/task_step/test_always_on_no_clock.py b/tst/unit/task_step/test_always_on_no_clock.py index 757fb7c69..d02da0363 100644 --- a/tst/unit/task_step/test_always_on_no_clock.py +++ b/tst/unit/task_step/test_always_on_no_clock.py @@ -69,13 +69,13 @@ async def invoke(self, uri, method, params=None, **kw): async def test_a_message_the_chat_env_couldn_t_time_is_read_on_the_task_s_clock(monkeypatch, tmp_path): rig = Rig(monkeypatch, tmp_path, agent=_asks_once, answers=[{"outcome": "reply", "message": "blue"}]) ctx = rig.context(user=DAY) - task_time = datetime(2027, 3, 1, 15, 0, tzinfo=timezone.utc) # Mon 10 AM in New York: she reads at once + task_time = datetime(2027, 3, 1, 15, 0, tzinfo=timezone.utc) # Mon 10 AM in New York: she looks at once assert abs(datetime.now(timezone.utc) - task_time) > timedelta(days=30) ctx.deployed_envs.append(_ClockEnv(task_time)) ctx = await asyncio.wait_for(rig.run(rig.step(), ctx), 10) [read] = rig.reads assert read["assistant_messages"][0]["at"] is None # the chat env's clock is unarmed - assert read["time"] == "2027-03-01T15:00:00Z" + assert read["time"] == "2027-03-01T17:30:00Z" # her look, then her response time at work [scheduled] = rig.events(ctx, "user_read_scheduled") assert scheduled["read_at"] == "2027-03-01T15:00:00Z" diff --git a/tst/unit/task_step/test_always_on_user_sim_inputs.py b/tst/unit/task_step/test_always_on_user_sim_inputs.py index e6684cb8c..09ca7a02c 100644 --- a/tst/unit/task_step/test_always_on_user_sim_inputs.py +++ b/tst/unit/task_step/test_always_on_user_sim_inputs.py @@ -110,7 +110,7 @@ async def test_a9_every_message_since_her_last_read_arrives_in_one_read_oldest_f await rig.run(rig.step(), rig.context(user=DAY)) [read] = rig.reads - assert read["time"] == "2026-11-10T12:30:00Z" + assert read["time"] == "2026-11-10T12:45:00Z" # her look at 7:30 AM, then her morning response time assert [(m["at"], m["text"]) for m in read["assistant_messages"]] == [ ("2026-11-10T05:00:00Z", "house: blue, $855"), ("2026-11-10T05:00:00Z", "dinner: La Ola"), ("2026-11-10T08:00:00Z", "flights held")] @@ -224,7 +224,8 @@ async def test_c2_c4_a_reply_or_a_done_reaches_the_agent_after_her_reply_time(mo ctx = await rig.run(rig.step(end_time="P3D"), rig.context(user=DAY)) [read] = rig.events(ctx, "user_sim_read") - assert read["virtual_time"] == "2026-11-09T14:00:00Z" and read["deliver_at"] == "2026-11-09T16:30:00Z" + assert read["looked_at"] == "2026-11-09T14:00:00Z" + assert read["virtual_time"] == "2026-11-09T16:30:00Z" and read["deliver_at"] == "2026-11-09T16:30:00Z" assert _woken_by_user(rig)[-1] == "[Mon Nov 9, 11:30 AM EST] Linda: blue, thanks!" assert rig.events(ctx, "wake")[1]["virtual_time"] == "2026-11-09T16:30:00Z" diff --git a/tst/unit/task_step/test_always_on_who_did_what.py b/tst/unit/task_step/test_always_on_who_did_what.py index 1f7b21300..47ff919d4 100644 --- a/tst/unit/task_step/test_always_on_who_did_what.py +++ b/tst/unit/task_step/test_always_on_who_did_what.py @@ -158,7 +158,7 @@ def agent(n, texts, rig): start, first, second = ctx.metadata["post_turn_hooks"]["week"] assert start == {"hook": "always_on", "turn": 0, "started_at": "2026-11-09T14:00:00Z"} - assert first == {"hook": "always_on", "turn": 1, "read_at": "2026-11-09T14:00:00Z", + assert first == {"hook": "always_on", "turn": 1, "read_at": "2026-11-09T16:30:00Z", "wrote_at": "2026-11-09T14:00:00Z", "outcome": "reply", "delivered": True, "deliver_at": "2026-11-09T16:30:00Z", "user_reads_at": "2026-11-09T16:30:00Z", "reply_to": {"wake": 1, "at": "2026-11-09T14:00:00Z", "text": "question 1?",