diff --git a/app.py b/app.py index 9eb520a..93c3eec 100644 --- a/app.py +++ b/app.py @@ -917,7 +917,8 @@ async def secure_chat(request: ChatRequest, http_request: Request, current_user clarify_reply_to = previous_marks.get(clarify_utils.CLARIFY_MARK) # Sonic's last reply asked how a thing fits into their life: this message is the answer (or not) previous_reply = open_loops_utils.previous_reply(chat_sessions[history_key]) # so "Friday at 2" can be tied to what Sonic just asked about support_pick = request.support_choice if request.support_choice in support_choice_utils.KEYS else None - chat_sessions[history_key].append(stamp(HumanMessage(content=question, additional_kwargs={support_choice_utils.MODE_MARK: support_pick} if support_pick else {}))) + turn_message = stamp(HumanMessage(content=question, additional_kwargs={support_choice_utils.MODE_MARK: support_pick} if support_pick else {})) # this turn's own message + chat_sessions[history_key].append(turn_message) # The messages this turn sends word for word, and the summary of the older ones (backend/utils/conversation_summary.py): every message the summary does not cover, or the old last 10 for a # guest or in low-power mode. @@ -1299,6 +1300,39 @@ def log_timings(grade: str, outcome: str): # Pictures Sonic made this turn (a card with the person's words on their photo) are shown the same way a library picture is. kb_images = [*kb_images, *(final_state.get("generated_images") or [])] + # WHAT THEY WANT FROM SONIC, ASKED BEFORE THE REPLY IS WRITTEN (backend/utils/support_choice.py): at the start of a hard stretch the card goes up first and the turn waits, so one reply is + # written, in the mode they tapped, about what they actually said. It waits HERE because everything below may depend on the pick. Never under a safety plan, for a guest, or when they have + # already typed something more. + support_offer = (support_pick is None and not is_guest_username(username) and choice_cards.enabled() and support_choice_utils.should_offer( + final_state.get("emotional_state"), question, chat_sessions[history_key][:-1], page_can_show=bool(request.choice_cards), + conversational=source_type == "conversational", closing=is_closing_message(question), safety_active=risk_level != RISK_NONE) and not steering.has_pending(history_key)) + if support_offer: + support_card = support_choice_utils.card() + support_choice_utils.show(username, support_card, turn_message) + tally(turn_counts, "support_choice_offered") + yield f"data: {json.dumps({'event': 'node_progress', 'node': 'formatter_node', 'title': 'Waiting for your pick...', 'detail': f'The reply is written either way after about {int(support_choice_utils.WAIT_SECONDS)} seconds.'})}\n\n" + yield f"data: {json.dumps({'event': 'choice_card', **support_card})}\n\n" + wait_outcome, picked = await support_choice_utils.wait_for_pick(support_card, turn_message) + for _key, _count in support_choice_utils.counts_for_wait(wait_outcome, picked).items(): + turn_counts[_key] = turn_counts.get(_key, 0) + _count + if wait_outcome in (support_choice_utils.MOVED_ON, support_choice_utils.STOPPED): + # No reply to this message from this turn. What they said is still saved and remembered; a message they typed instead is sent by the page as the next one and answered in full. + if wait_outcome == support_choice_utils.STOPPED: + chat_sessions[history_key].append(stamp(AIMessage(content="_[Stopped by user before responding]_"))) + await asyncio.to_thread(save_conversation_turn, username, session_id, chat_sessions[history_key]) + if budget_guard.allows("memory_summaries", budget_state): + spawn_background_task(index_conversation_turn( + services.get("user_memory_vector_store"), username, question, "(No reply was written: they sent something else first.)", session_id, previous_reply)) + if open_loops_utils.open_loops_enabled() and budget_guard.allows("open_loops", budget_state): + spawn_background_task(open_loops_utils.capture_open_loops( + username, question, await asyncio.to_thread(get_user_timezone, username), risk_active=False, previous_reply=previous_reply)) + await asyncio.to_thread(record_turn_counts, turn_counts) + llm_turns.finish(llm_turn) + await asyncio.to_thread(llm_usage.flush) + log_timings(relevance_grade, wait_outcome) + yield f"data: {json.dumps({'event': 'final_generation', 'text': ''})}\n\n" + return + # "I hear you" only when no recent reply opened with it (it had become a stamp: emotion_utils.HEAR_YOU_GAP). hear_you_ok = not opened_with_hear_you(earlier_ai_replies(chat_sessions[history_key], HEAR_YOU_GAP)) emotional_context = safety_plan.context + build_emotional_context( @@ -1854,8 +1888,7 @@ def _read_progress_notes(): if carried_corrections: prompt = prompt + corrections_utils.build_block(carried_corrections) tally(turn_counts, "corrections_carried") - # What they want from Sonic right now (backend/utils/support_choice.py): a mode they picked on the support card holds for a few hours; otherwise, at the start of a hard stretch where - # Sonic would only be guessing, the reply is followed by a card that asks (just listen / advice / help fixing it). Never under a safety plan. + # What they want from Sonic right now (backend/utils/support_choice.py): a mode they picked on the support card (just now, above, or earlier) holds for a few hours. Never under a safety plan. if support_pick: for _key, _count in support_choice_utils.counts_for_pick(support_pick).items(): turn_counts[_key] = turn_counts.get(_key, 0) + _count @@ -1894,11 +1927,6 @@ def _read_progress_notes(): if _doing: prompt = prompt + message_doing.build_block(_doing) tally(turn_counts, "doing", _doing) - support_offer = (support_mode is None and not is_guest_username(username) and support_choice_utils.should_offer( - final_state.get("emotional_state"), question, chat_sessions[history_key][:-1], page_can_show=bool(request.choice_cards), - conversational=source_type == "conversational", closing=is_closing_message(question), safety_active=risk_level != RISK_NONE)) - if support_offer: - prompt = prompt + support_choice_utils.OFFER_NOTE # A timeline for a question about the history of something ongoing (backend/utils/timeline.py): every fact and note that names it, oldest first, so "what interview steps have I had # with Casey's?" is answered from all of them, not from the five vaguest facts (2026-11-23). Only on a history question; no model call. if not is_guest_username(username) and get_db() is not None and timeline_utils.asks_for_history(question): @@ -2249,13 +2277,7 @@ def _read_progress_notes(): if context_view: yield f"data: {json.dumps({'event': 'context', **context_view})}\n\n" yield f"data: {json.dumps({'event': 'final_generation', 'text': full_response})}\n\n" - if support_offer: - # The support card: a tap sends the option as their next message (support_choice), which sets the mode (backend/utils/support_choice.py). - yield f"data: {json.dumps({'event': 'choice_card', **support_choice_utils.card()})}\n\n" - tally(turn_counts, "support_choice_offered") ai_message = stamp(AIMessage(content=full_response)) - if support_offer: - ai_message.additional_kwargs[support_choice_utils.CARD_MARK] = True try: ai_message.additional_kwargs[reply_stamp.KEY] = reply_stamp.build( written_tier, tier_reason, reply_choice, [e["id"] for e in voice_example_entries], [n["id"] for n in people_note_entries], diff --git a/backend/components/sonic_changelog.py b/backend/components/sonic_changelog.py index 84e98ce..4bec2e7 100644 --- a/backend/components/sonic_changelog.py +++ b/backend/components/sonic_changelog.py @@ -1337,7 +1337,7 @@ ], "month": "2026-10", "title": "Stopping and steering", - "line": "You can stop me mid-answer with the stop button, and send a new message to steer me while I'm still working.", + "line": "You can stop me mid-answer with the stop button, or send a message to steer me while I'm working. If I'm waiting on a card, typing ends the wait and I read what you wrote.", "keywords": ["stop", "cancel", "interrupt", "steer", "redirect"], "volunteer": ["stop button", "can i interrupt"], }, @@ -1910,7 +1910,7 @@ "month": "2026-11", "title": "Asking what would help", "line": ( - "When you're having a hard time, I can now ask with a quick card whether you want me to just listen, give advice, or help fix it, and stick with your answer for the next few hours." + "When you're having a hard time, I can now ask before replying whether you want me to just listen, advise or help fix it, and answer that way. No tap in about a minute and a half and I reply anyway." ), "keywords": ["just listen", "advice", "fix it", "vent", "what would help", "support"], "volunteer": [], diff --git a/backend/services/agent_workflow.py b/backend/services/agent_workflow.py index e03a83d..b3c22c0 100644 --- a/backend/services/agent_workflow.py +++ b/backend/services/agent_workflow.py @@ -3637,7 +3637,7 @@ async def _still_waiting(seconds: int) -> None: outcome = await change_cards.wait_for(proposal["proposal_id"], on_tick=_still_waiting) finally: change_cards.forget(proposal["proposal_id"]) - key = {"applied": f"{prefix}_applied", "declined": f"{prefix}_declined", "failed": f"{prefix}_failed"}.get(outcome["kind"] if outcome else "", f"{prefix}_timeout") + key = {"applied": f"{prefix}_applied", "declined": f"{prefix}_declined", "failed": f"{prefix}_failed", "typed": f"{prefix}_typed"}.get(outcome["kind"] if outcome else "", f"{prefix}_timeout") await asyncio.to_thread(record_turn_counts, {key: 1}) return change_cards.result_text(proposal, outcome) @@ -4069,6 +4069,8 @@ async def _still_waiting(seconds: int, job_status: str) -> None: finished = await runner_jobs.wait_for_result(db, username, job["id"], timeout=after_edit_check.WAIT_SECONDS, on_tick=_still_waiting) if not finished: return "" + if finished.get(runner_jobs.TYPED_INSTEAD): + return "\n\n" + runner_jobs.format_result(finished) # nothing ran, so none of the "it ran" wording below done = finished.get("status") == runner_jobs.DONE and not finished.get("timed_out") passed = done and finished.get("exit_code") == 0 counts = {"code_after_edit_check_run": 1} @@ -4089,6 +4091,12 @@ async def _decision_result(shown: str, result: dict, decision: dict | None) -> s shown + " NO DECISION: there was no answer within " f"{int(local_edit_decisions.WAIT_SECONDS // 60)} minutes, so nothing was changed. Say that plainly in a short answer and stop; do not propose it again." ) + if decision["outcome"] == "typed": + # They wrote instead of pressing: the message is queued, and the loop takes it in at its next step. The card stays on their screen. + return ( + shown + " NOT DECIDED YET: they sent a message instead of pressing Apply or Decline, so nothing has been changed. The card is still on their screen. " + "Their message follows: read it and act on it. If it asks for a different change, propose that one; do not claim these edits were applied." + ) if decision["outcome"] == "declined": if plan_phase == code_plan.EXECUTE_PHASE: llm_turns.note_plan_blocked("declined") diff --git a/backend/services/change_cards.py b/backend/services/change_cards.py index 06c1a7d..9937dc4 100644 --- a/backend/services/change_cards.py +++ b/backend/services/change_cards.py @@ -47,7 +47,7 @@ def card_payload(proposal: Dict[str, Any]) -> Dict[str, Any]: def register(proposal: Dict[str, Any]) -> None: """Starts waiting for this proposal's decision. Call before the card is streamed, so a very quick press cannot arrive first.""" - _waiting[proposal["proposal_id"]] = {"proposal": proposal, "event": asyncio.Event(), "outcome": None, "deciding": False} + _waiting[proposal["proposal_id"]] = {"proposal": proposal, "event": asyncio.Event(), "outcome": None, "deciding": False, "mark": steering.typed_mark()} def forget(proposal_id: str) -> None: @@ -83,8 +83,8 @@ async def decide(username: str, proposal_id: str, decision: Any) -> Dict[str, An async def wait_for(proposal_id: str, timeout: Optional[float] = None, on_tick: Optional[Callable[[int], Awaitable[None]]] = None) -> Optional[Dict[str, Any]]: - """Waits for the decision on `proposal_id` and returns the outcome ({"kind", "message"}), or None when there was none within `timeout` seconds. `on_tick(seconds_waited)` runs every HEARTBEAT_SECONDS so the - stream stays open. Always forgets the proposal afterwards, including when the wait is cancelled.""" + """Waits for the decision on `proposal_id` and returns the outcome ({"kind", "message"}; "typed" when they sent a message instead of pressing), or None when there was none within `timeout` seconds or the turn + was stopped. `on_tick(seconds_waited)` runs every HEARTBEAT_SECONDS so the stream stays open. Always forgets the proposal afterwards, including when the wait is cancelled.""" entry = _waiting.get(proposal_id) if entry is None: return None @@ -94,10 +94,16 @@ async def wait_for(proposal_id: str, timeout: Optional[float] = None, on_tick: O try: while waited < limit: step = min(HEARTBEAT_SECONDS, limit - waited) - how = await steering.wait_event(entry["event"], step) + # A press being carried out right now is let finish (its Google call may already be under way): a typed message does not end that wait. + how = await steering.wait_event(entry["event"], step, None if entry["deciding"] else entry["mark"]) if how == "set": ended = entry["outcome"]["kind"] return entry["outcome"] + if how == "typed": + if entry["deciding"]: + continue + ended = "typed" + return {"kind": "typed", "message": ""} if how == "stopped": ended = "stopped" # Stop, or a new message instead of an answer: nobody is waiting any more, so nothing is applied return None @@ -122,6 +128,9 @@ def result_text(proposal: Dict[str, Any], outcome: Optional[Dict[str, Any]]) -> minutes = max(int(WAIT_SECONDS // 60), 1) return (f"NO DECISION: nothing was pressed within {minutes} minutes, so nothing in their {proposal.get('subject', 'calendar')} was changed, and the card no longer works. Say that plainly in your final answer and stop; " "they can ask again.") + if outcome["kind"] == "typed": + return (f"NOT DECIDED: they sent a message instead of pressing, so nothing in their {proposal.get('subject', 'calendar')} was changed, and the card no longer works. Their message follows: act on it. " + "If it asks for a different change, propose that one.") if outcome["kind"] == "applied": return f"APPLIED: {outcome['message']} It is done. Say so in one short sentence and, if the person asked for more, carry on with the rest. Do not propose the same change again." if outcome["kind"] == "declined": diff --git a/backend/services/choice_cards.py b/backend/services/choice_cards.py index 04bded8..efa653e 100644 --- a/backend/services/choice_cards.py +++ b/backend/services/choice_cards.py @@ -10,6 +10,7 @@ - ONE QUESTION, FEW OPTIONS. The card is validated here: a question, two to four distinct options with short labels, no "other" option of its own (the card always has a "Something else" box), at most two asks in a turn so it never becomes an interview. - ONE PERSON'S. An answer is accepted only from the person the card was shown to. - BOUNDED. CHOICE_WAIT_SECONDS (default 600); a turn that is cancelled, stopped (Stop) or answered with a new message instead of a tap stops waiting at once (steering.wait_event); a browser that merely went away does not end it. No answer means nothing was decided, and the turn says so and stops: Sonic does not guess. + A message typed into the waiting turn (the composer sends it as steering) ends the wait too, as "typed": the loop takes the message in at its next step. - ONLY WHEN THE PAGE CAN ANSWER. A page from before this existed would never answer; the chat request carries `choice_cards`, and the tool is only offered when it is true. - NO TEXT IS LOGGED: the question, the options and the person's own words are never written to a log; only that a wait ended, and how. """ @@ -93,9 +94,10 @@ def validate_card(args: Any) -> Tuple[Optional[Dict[str, Any]], str]: return {"choice_id": uuid.uuid4().hex, "question": question, "options": options}, "" -def register(username: str, card: Dict[str, Any]) -> None: - """Starts waiting for `card`'s answer. Call before the card is streamed, so a very quick tap cannot arrive first.""" - _waiting[card["choice_id"]] = {"username": username, "count": len(card["options"]), "event": asyncio.Event(), "answer": None} +def register(username: str, card: Dict[str, Any], words: bool = True) -> None: + """Starts waiting for `card`'s answer. Call before the card is streamed, so a very quick tap cannot arrive first. `words=False` takes a tap only: the person's own words belong in an ordinary + message, which is read in full (the support card).""" + _waiting[card["choice_id"]] = {"username": username, "count": len(card["options"]), "event": asyncio.Event(), "answer": None, "words": words, "mark": steering.typed_mark()} def forget(choice_id: str) -> None: @@ -115,6 +117,8 @@ def answer(username: str, choice_id: str, index: Any = None, other: Any = None) words = _clip(other)[:MAX_OTHER_CHARS] if isinstance(index, int) and not isinstance(index, bool) and 0 <= index < entry["count"]: entry["answer"] = {"kind": "picked", "index": index} + elif words and not entry["words"]: + return "no_waiter" # the page then sends the words as their next message elif words: entry["answer"] = {"kind": "other", "text": words} else: @@ -124,8 +128,8 @@ def answer(username: str, choice_id: str, index: Any = None, other: Any = None) async def wait_for(choice_id: str, timeout: Optional[float] = None, on_tick: Optional[Callable[[int], Awaitable[None]]] = None) -> Optional[Dict[str, Any]]: - """Waits for the answer to `choice_id` and returns it ({"kind": "picked", "index"} or {"kind": "other", "text"}), or None if there was none within `timeout` seconds. `on_tick(seconds_waited)` is called every HEARTBEAT_SECONDS so the - stream stays open. Always forgets the card afterwards, including when the wait is cancelled.""" + """Waits for the answer to `choice_id` and returns it ({"kind": "picked", "index"}, {"kind": "other", "text"}, or {"kind": "typed"} when they typed a message instead), or None if there was none within `timeout` seconds + or the turn was stopped. `on_tick(seconds_waited)` is called every HEARTBEAT_SECONDS so the stream stays open. Always forgets the card afterwards, including when the wait is cancelled.""" entry = _waiting.get(choice_id) if entry is None: return None @@ -135,10 +139,13 @@ async def wait_for(choice_id: str, timeout: Optional[float] = None, on_tick: Opt try: while waited < limit: step = min(HEARTBEAT_SECONDS, limit - waited) - how = await steering.wait_event(entry["event"], step) + how = await steering.wait_event(entry["event"], step, entry["mark"]) if how == "set": ended = entry["answer"]["kind"] return entry["answer"] + if how == "typed": + ended = "typed" + return {"kind": "typed"} if how == "stopped": ended = "stopped" # Stop, or a new message instead of an answer: nobody is waiting any more, so nothing is applied return None @@ -163,6 +170,8 @@ def result_text(card: Dict[str, Any], answer_given: Optional[Dict[str, Any]]) -> minutes = max(int(WAIT_SECONDS // 60), 1) return (f"No answer came within {minutes} minutes, so nothing was decided. Do not guess and do not carry on as if they had chosen: say in your final answer what you were going to ask and why, and stop. " "They can answer in their next message.") + if answer_given["kind"] == "typed": + return "They typed a message instead of tapping, so no option was chosen. Their message follows: treat it as their answer and act on it. Do not show the same question again." if answer_given["kind"] == "picked": option = card["options"][answer_given["index"]] detail = f" ({option['description']})" if option.get("description") else "" diff --git a/backend/services/local_edit_decisions.py b/backend/services/local_edit_decisions.py index f37380b..1739d12 100644 --- a/backend/services/local_edit_decisions.py +++ b/backend/services/local_edit_decisions.py @@ -10,7 +10,8 @@ - ONE PERSON'S. A decision is accepted only from the person the proposal was made for. - NOTHING IS APPLIED HERE. The browser still writes the files; this only carries its report back. A report with no one waiting (the turn ended, or the wait timed out) is ignored, and the card behaves as it always did. -- BOUNDED. LOCAL_EDIT_WAIT_SECONDS (default 600, ten minutes); a turn that is cancelled, stopped (Stop) or answered with a new message instead of a press stops waiting at once (steering.wait_event); a browser that merely went away does not end it. The waiting is in this process, +- BOUNDED. LOCAL_EDIT_WAIT_SECONDS (default 600, ten minutes); a turn that is cancelled, stopped (Stop) or answered with a new message instead of a press stops waiting at once (steering.wait_event); a browser that merely went away does not end it. + A message typed into the waiting turn ends the wait too ("typed"): the loop takes it in, and the card stays on screen, still able to apply. The waiting is in this process, so it needs the decision to reach the same server instance (one worker today; with more, a report that lands elsewhere is simply not seen and the wait times out). - ONLY WHEN THE BROWSER SAYS IT CAN REPORT. A page from before this existed would never answer, and a turn must not wait ten minutes for it (the chat request carries `edit_decisions`). @@ -49,7 +50,7 @@ def _clean_reason(text: Any) -> str: def register(username: str, proposal_id: str) -> None: """Starts waiting for `proposal_id`. Call before the card is streamed, so a very quick button press cannot arrive first.""" - _waiting[proposal_id] = {"username": username, "event": asyncio.Event(), "outcome": None} + _waiting[proposal_id] = {"username": username, "event": asyncio.Event(), "outcome": None, "mark": steering.typed_mark()} def remember_proposal(username: str, proposal_id: str, changes: Dict[str, Any]) -> None: @@ -96,8 +97,9 @@ def waiting_count() -> int: # WHY NOBODY WAS WAITING (2026-11-05). In production the turn twice ended the moment Apply was pressed, and nothing said why. A report that finds no waiter now says which of these it was, and is counted: # "cancelled" (the stream was cut while the turn waited: a proxy, the browser, a reload), "timeout" (the wait ran out), "decided" (this proposal was already answered: a second press), or "not_here" (this process -# never held it: another instance took the report, the server restarted, or it is more than six hours old). Only the first two cases and the last are failures; "decided" is a harmless second press. -NO_WAITER_REASONS = ("cancelled", "timeout", "decided", "not_here") +# never held it: another instance took the report, the server restarted, or it is more than six hours old). Only the first two cases and the last are failures; "decided" is a harmless second press, and so is +# "typed" (2026-11-29: they sent a message instead, and pressed the card afterwards). +NO_WAITER_REASONS = ("cancelled", "timeout", "decided", "not_here", "typed") def why_no_waiter(username: str, proposal_id: str) -> str: @@ -149,10 +151,13 @@ async def wait_for(proposal_id: str, timeout: Optional[float] = None, on_tick: O try: while waited < limit: step = min(HEARTBEAT_SECONDS, limit - waited) - how = await steering.wait_event(entry["event"], step) + how = await steering.wait_event(entry["event"], step, entry["mark"]) if how == "set": ended = "decided" return entry["outcome"] + if how == "typed": + ended = "typed" + return {"outcome": "typed", "reason": ""} if how == "stopped": ended = "stopped" # Stop, or a new message instead of an answer: nobody is waiting any more, so nothing is applied return None diff --git a/backend/services/steering.py b/backend/services/steering.py index 9e03e5d..4b68126 100644 --- a/backend/services/steering.py +++ b/backend/services/steering.py @@ -38,6 +38,9 @@ class _Run: stop: bool = False # the person pressed Stop (POST /api/chat/stop): the only thing that ends a turn early now that a lost connection does not interrupt: Optional["asyncio.Event"] = None # set with `stop`, so a turn blocked on a person's answer (wait_event) wakes at once instead of at its next check waiting: int = 0 # how many waits for a person's answer this turn is inside right now + sent: int = 0 # messages taken from the person so far this turn, so a wait can tell one arrived after its card went up + typed: Optional["asyncio.Event"] = None # set by each of them, to wake a wait at once + moved_on: bool = False # a new message arrived as a new request while this turn waited (abandon_wait): it ends quietly, unlike Stop _runs: dict = {} @@ -96,9 +99,40 @@ def abandon_wait(key: str) -> bool: run = _runs.get(key) if run is None or run.waiting <= 0: return False + run.moved_on = True return request_stop(key) == "stopping" +def moved_on(key: Optional[str] = None) -> bool: + """Whether the turn this code runs in was ended because a new message arrived as a new request, not because the person pressed Stop.""" + with _lock: + run = _runs.get(key or _turn_key.get() or "") + return bool(run and run.moved_on) + + +# A MESSAGE TYPED WHILE A CARD IS UP (2026-11-29). The page sends it here (POST /api/chat/steer), not as a new request, so it used to sit in the queue until the card was pressed or the wait ran out, +# up to ten minutes. A wait now takes a mark when its card goes up (typed_mark) and ends as soon as a later message arrives; the message stays queued for whoever picks it up. +def typed_mark() -> int: + """How many messages the turn this code runs in has taken so far. Call when a card goes up, and give it to wait_event or typed_since.""" + with _lock: + run = _runs.get(_turn_key.get() or "") + return run.sent if run else 0 + + +def typed_since(mark: int) -> bool: + """Whether the person has sent a message to this turn since `mark` was taken.""" + with _lock: + run = _runs.get(_turn_key.get() or "") + return bool(run and run.sent > mark) + + +def has_pending(key: str) -> bool: + """Whether a message is queued for this conversation's running turn and not yet taken in.""" + with _lock: + run = _runs.get(key) + return bool(run and run.pending) + + class person_wait: """`with steering.person_wait():` marks the turn as blocked on a person for as long as the block runs (for a wait that polls instead of using one event), so a new message can end it (abandon_wait).""" def __enter__(self): @@ -121,20 +155,27 @@ def wait_stopped(key: Optional[str] = None) -> bool: return stop_requested(key or _turn_key.get() or "") -async def wait_event(event: "asyncio.Event", timeout: float) -> str: - """Waits up to `timeout` seconds for `event` (the person's press or answer) and says how it ended: "set", "timeout", or "stopped" (the person pressed Stop, or sent a new message instead - of answering, while this turn was waiting). A press that arrived at the same moment wins. A browser that merely went away does NOT end it: the turn is meant to carry on (a locked phone). - Outside a registered turn it is a plain timed wait.""" +async def wait_event(event: "asyncio.Event", timeout: float, mark: Optional[int] = None) -> str: + """Waits up to `timeout` seconds for `event` (the person's press or answer) and says how it ended: "set", "timeout", "stopped" (the person pressed Stop, or sent a new message as a new + request, while this turn was waiting) or, when `mark` is given (typed_mark), "typed" (they typed a message into this turn after the mark). A press that arrived at the same moment wins. + A browser that merely went away does NOT end it: the turn is meant to carry on (a locked phone). Outside a registered turn it is a plain timed wait.""" key = _turn_key.get() with _lock: run = _runs.get(key) if key else None if run is not None: if run.stop and not event.is_set(): return "stopped" + if mark is not None and run.sent > mark and not event.is_set(): + return "typed" if run.interrupt is None: run.interrupt = asyncio.Event() run.waiting += 1 interrupt = run.interrupt + typing = None + if mark is not None: + if run.typed is None or run.typed.is_set(): + run.typed = asyncio.Event() + typing = run.typed if run is None: try: await asyncio.wait_for(event.wait(), timeout=timeout) @@ -143,18 +184,22 @@ async def wait_event(event: "asyncio.Event", timeout: float) -> str: return "timeout" pressed = asyncio.ensure_future(event.wait()) interrupted = asyncio.ensure_future(interrupt.wait()) + wrote = asyncio.ensure_future(typing.wait()) if typing is not None else None + tasks = [task for task in (pressed, interrupted, wrote) if task is not None] try: - await asyncio.wait({pressed, interrupted}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED) + await asyncio.wait(set(tasks), timeout=timeout, return_when=asyncio.FIRST_COMPLETED) finally: with _lock: run.waiting -= 1 - for task in (pressed, interrupted): + for task in tasks: if not task.done(): task.cancel() if pressed.done() and not pressed.cancelled(): return "set" if interrupted.done() and not interrupted.cancelled(): return "stopped" + if wrote is not None and wrote.done() and not wrote.cancelled(): + return "typed" return "timeout" @@ -194,6 +239,9 @@ def submit(key: str, text: str) -> str: if len(run.pending) >= MAX_PENDING_STEERS: return "too_many" run.pending.append(text[:MAX_STEER_CHARS]) + run.sent += 1 + if run.typed is not None: + run.typed.set() return "queued" diff --git a/backend/tests/test_after_edit_check.py b/backend/tests/test_after_edit_check.py index e4c3242..3e251fd 100644 --- a/backend/tests/test_after_edit_check.py +++ b/backend/tests/test_after_edit_check.py @@ -176,6 +176,15 @@ async def test_a_run_that_did_not_finish_is_not_counted_as_failed(monkeypatch): assert "NOT FINISHED" in seen["observation"] and {"code_after_edit_check_run": 1} in asked["counts"] +@run_async +async def test_a_check_called_off_by_a_typed_message_is_never_reported_or_counted_as_a_run(monkeypatch): + _connect_folder() + asked = _runner(monkeypatch, True, {"id": "j1", "check": "tests", "status": rj.CANCELLED, rj.TYPED_INSTEAD: True}) + seen = await _drive(monkeypatch, lambda pid: led.decide("jack", pid, "applied"), state_extra={"runner_cards": True}) + assert "APPLIED" in seen["observation"] and "NOT RUN: the person sent a message instead" in seen["observation"] + assert aec.AUTO_RAN_MARK not in seen["observation"] and not aec.ran_in(seen["observation"]) and not any("code_after_edit_check_run" in c for c in asked["counts"]) + + @run_async async def test_with_the_setting_off_nothing_runs_and_the_result_names_the_check(monkeypatch): _connect_folder() diff --git a/backend/tests/test_budget_guard.py b/backend/tests/test_budget_guard.py index c1705bf..eeda090 100644 --- a/backend/tests/test_budget_guard.py +++ b/backend/tests/test_budget_guard.py @@ -361,9 +361,10 @@ def test_the_chat_turn_decides_the_budget_first_and_pauses_the_extras_and_the_mo state_at = source.index("budget_state = await asyncio.to_thread(budget_guard.current_state, None, None, budget_guard.limit_username(username, is_admin_user), True)") assert state_at < source.index('"budget_level": budget_state.get("level")') < source.index("async def token_streamer():") assert "effective_deep_thinking = False" in source[state_at: state_at + 300] - for gate in ('budget_guard.allows("answer_recheck", budget_state)', 'budget_guard.allows("memory_summaries", budget_state)', - 'budget_guard.allows("open_loops", budget_state)'): - assert source.count(gate) == 1, gate + assert source.count('budget_guard.allows("answer_recheck", budget_state)') == 1 + # Twice each: after a reply, and when the turn ends at the support card with no reply and their message is still remembered (app.py, 2026-11-29). Both are paused in low power. + for gate in ('budget_guard.allows("memory_summaries", budget_state)', 'budget_guard.allows("open_loops", budget_state)'): + assert source.count(gate) == 2, gate streamer = source[source.index("async def token_streamer():"): source.index("async def steerable_turn():")] blocked_at = streamer.index("if budget_guard.blocked(budget_state):") assert blocked_at < streamer.index("workflow.ainvoke") # the stop is before any model-calling work diff --git a/backend/tests/test_change_cards.py b/backend/tests/test_change_cards.py index 5e450bc..57e978b 100644 --- a/backend/tests/test_change_cards.py +++ b/backend/tests/test_change_cards.py @@ -302,6 +302,22 @@ async def test_decline_tells_the_loop_not_to_propose_it_again_and_sends_nothing( assert seen["observations"][0].startswith("DECLINED") and google.writes() == [] and {"calendar_change_declined": 1} in seen["counts"] +@run_async +async def test_a_message_typed_instead_of_a_press_changes_nothing_and_is_counted_as_typed(monkeypatch, google): + from backend.services import steering + + async def type_instead(card): + steering.submit("jack::typed", "make it Friday instead") + + run = steering.open_run("jack::typed", []) + try: + seen = await asyncio.wait_for(_drive(monkeypatch, google, type_instead), 20) + finally: + steering.close_run("jack::typed", run) + assert seen["observations"][0].startswith("NOT DECIDED") and google.writes() == [] and cards.waiting_count() == 0 + assert {"calendar_change_typed": 1} in seen["counts"] and {"calendar_change_timeout": 1} not in seen["counts"] + + @run_async async def test_no_press_in_time_changes_nothing_and_is_counted(monkeypatch, google): monkeypatch.setattr(cards, "WAIT_SECONDS", 0.05) @@ -442,12 +458,12 @@ def test_every_calendar_counter_is_one_the_tally_accepts_is_recorded_and_the_sta from backend.utils import self_counters from backend.state.graph_state import GraphState - assert set(self_counters.CALENDAR_CHANGE_KEYS) == {"calendar_change_shown", "calendar_change_applied", "calendar_change_declined", "calendar_change_failed", "calendar_change_timeout", "calendar_change_refused"} + assert set(self_counters.CALENDAR_CHANGE_KEYS) == {"calendar_change_shown", "calendar_change_applied", "calendar_change_declined", "calendar_change_failed", "calendar_change_timeout", "calendar_change_refused", "calendar_change_typed"} assert set(self_counters.CALENDAR_CHANGE_KEYS) <= set(self_counters.KEYS) and "change_cards" in GraphState.__annotations__ # The tally keys are built from a prefix and a suffix by the shared handler (_propose_change): both halves must be there, and the loop tests above prove each key really is recorded. workflow = (ROOT / "backend" / "services" / "agent_workflow.py").read_text(encoding="utf-8") assert '"calendar_change"' in workflow - for suffix in ("shown", "applied", "declined", "failed", "timeout", "refused"): + for suffix in ("shown", "applied", "declined", "failed", "timeout", "refused", "typed"): assert f'f"{{prefix}}_{suffix}"' in workflow, f"{suffix} is never recorded" diff --git a/backend/tests/test_choice_cards.py b/backend/tests/test_choice_cards.py index 4e29618..ba8802f 100644 --- a/backend/tests/test_choice_cards.py +++ b/backend/tests/test_choice_cards.py @@ -283,7 +283,8 @@ def test_the_endpoint_the_request_flag_the_stream_event_and_the_card_are_wired_b chat = (ROOT / "local" / "src" / "pages" / "Chat.tsx").read_text(encoding="utf-8") assert "payload.event === 'choice_card'" in chat and "parseChoiceCard(payload)" in chat and " {"):chat.index("const onSubmitForm = ")] + assert "void handleSendMessage(text, attachmentsRef.current, [], supportChoice);" in send and "void handleSteer(text);" in send + assert "pendingResendRef.current.push({ id: genId(), text, supportChoice });" in send and send.index("if (!loading)") < send.index("else if (!supportChoice)") + assert "handleSendMessageRef.current(next.text, [], [], next.supportChoice);" in chat + assert "sendFromCardRef.current = sendFromCard;" in chat and "onSendMessage={(text, key) => sendFromCardRef.current(text, key)}" in chat + + +def test_no_card_for_a_page_that_cannot_show_one(world): + async def go(): + body = app_module.ChatRequest(question=HARD, affiliate="HQ", session_id="s1") + response = await app_module.secure_chat(body, SimpleNamespace(headers={}, client=None), {"sub": USER}) + return "".join([str(chunk) async for chunk in response.body_iterator]) + + text = run(go()) + assert "choice_card" not in text and REPLY in text diff --git a/backend/tests/test_support_choice.py b/backend/tests/test_support_choice.py index 48ff440..072c135 100644 --- a/backend/tests/test_support_choice.py +++ b/backend/tests/test_support_choice.py @@ -1,10 +1,13 @@ """The support card in conversations (backend/utils/support_choice.py): when it is offered, what a pick does and how long it lasts, and that the marks survive saving. Mood states come from the real merge_emotional_state, messages are stamped with real times. No model, no database.""" +import asyncio import os +import time from datetime import datetime, timedelta, timezone from langchain_core.messages import AIMessage, HumanMessage +from backend.services import choice_cards, steering from backend.utils import app_utils, self_counters from backend.utils import support_choice as sc from backend.utils.emotion_utils import merge_emotional_state @@ -12,6 +15,7 @@ REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) NOW = datetime.now(timezone.utc) +TURN = "jack::support" LOW = merge_emotional_state(None, {"valence": "low", "intensity": 0.6}, NOW) GATES = dict(page_can_show=True, conversational=True, closing=False, safety_active=False) @@ -80,14 +84,86 @@ def test_the_pick_outranks_the_guessed_need_in_the_reply_check(): assert sc.adjust_issue("thin_comfort", "advice", advice_reply, False) == "thin_comfort" -def test_the_card_has_three_keyed_options_in_message_mode(): +def test_the_card_has_three_keyed_options_answered_to_the_waiting_turn(): card = sc.card() - assert card["mode"] == "message" and card["question"] == sc.QUESTION and len(card["choice_id"]) == 32 + assert card["mode"] == "answer" and card["fallback"] == "message" and card["question"] == sc.QUESTION and len(card["choice_id"]) == 32 assert [o["key"] for o in card["options"]] == ["listen", "advice", "fix"] and not any(o["recommended"] for o in card["options"]) - assert "do not end with a question" in sc.OFFER_NOTE + assert sc.WAIT_SECONDS == 90 and not hasattr(sc, "OFFER_NOTE") # nothing is written before the pick, so no note about a card to follow assert sc.counts_for_pick("fix") == {"support_choice_fix": 1} and sc.counts_for_pick("nope") == {} +def test_a_card_shown_without_a_reply_still_counts_as_offered(): + assert not sc.should_offer(LOW, "still awful", [stamp(HumanMessage(content="awful", additional_kwargs={sc.CARD_MARK: True}), NOW - timedelta(hours=1))], now=NOW, **GATES) + + +def test_every_way_a_wait_ends_has_a_counter(): + assert sc.counts_for_wait(sc.PICKED, "advice") == {"support_choice_advice": 1} + for outcome in (sc.NO_TAP, sc.MOVED_ON, sc.STOPPED): + counts = sc.counts_for_wait(outcome) + assert counts == {f"support_card_{outcome}": 1} and set(counts) <= self_counters.KEYS + assert sc.counts_for_wait("nonsense") == {} + + +# ---- the wait itself ------------------------------------------------------------------------------------------------------------------------------- + +def _wait(act, timeout=5.0): + """Shows the card inside a registered turn, runs `act(card)` once it is waiting, and returns (outcome, key, their message, seconds).""" + async def go(): + run = steering.open_run(TURN, []) + try: + message, card = human("today was awful"), sc.card() + sc.show("jack", card, message) + started = time.monotonic() + waiter = asyncio.create_task(sc.wait_for_pick(card, message, timeout=timeout)) + await asyncio.sleep(0.05) + if act: + act(card) + outcome, key = await asyncio.wait_for(waiter, 4) + return outcome, key, message, time.monotonic() - started + finally: + steering.close_run(TURN, run) + return asyncio.run(go()) + + +def test_a_tap_marks_the_mode_on_their_own_message(): + outcome, key, message, took = _wait(lambda card: choice_cards.answer("jack", card["choice_id"], index=1)) + assert (outcome, key) == (sc.PICKED, "advice") and took < 2 + assert message.additional_kwargs[sc.CARD_MARK] is True and message.additional_kwargs[sc.MODE_MARK] == "advice" and sc.current_mode([message], NOW) == "advice" + + +def test_no_tap_in_time_goes_on_with_no_mode(): + outcome, key, message, _took = _wait(None, timeout=0.2) + assert (outcome, key) == (sc.NO_TAP, None) and sc.MODE_MARK not in message.additional_kwargs and choice_cards.waiting_count() == 0 + + +def test_typing_instead_ends_the_wait_at_once_and_leaves_the_message_queued_for_the_page_to_send(): + left = {} + + def typed(card): + assert steering.submit(TURN, "actually she just called") == "queued" + left["pending"] = steering.has_pending(TURN) + + outcome, key, message, took = _wait(typed) + assert (outcome, key) == (sc.MOVED_ON, None) and took < 2 and left["pending"] and sc.MODE_MARK not in message.additional_kwargs + + +def test_a_new_request_moves_on_and_stop_stops(): + assert _wait(lambda card: steering.abandon_wait(TURN))[0] == sc.MOVED_ON + assert _wait(lambda card: steering.request_stop(TURN))[0] == sc.STOPPED + + +def test_someone_elses_tap_and_words_on_this_card_are_not_taken(): + seen = {} + + def try_both(card): + seen["other_person"] = choice_cards.answer("mallory", card["choice_id"], index=0) + seen["words"] = choice_cards.answer("jack", card["choice_id"], other="i want to die") # words go as an ordinary message, which is read for safety + choice_cards.answer("jack", card["choice_id"], index=0) + + assert _wait(try_both)[:2] == (sc.PICKED, "listen") + assert seen == {"other_person": "no_waiter", "words": "no_waiter"} + + def test_the_marks_survive_saving_and_loading_the_conversation(): saved = app_utils._serialize_messages([human("Just listen", mode="listen"), ai("reply", card=True)]) assert saved[0][sc.MODE_MARK] == "listen" and saved[1][sc.CARD_MARK] is True @@ -95,13 +171,14 @@ def test_the_marks_survive_saving_and_loading_the_conversation(): assert sc.current_mode(loaded, NOW) == "listen" and sc.card_offered_recently(loaded, NOW) -def test_the_reply_offers_the_card_applies_the_mode_and_counts_both(): +def test_the_turn_asks_before_anything_that_depends_on_the_pick_and_applies_the_mode(): app = open(os.path.join(REPO, "app.py"), encoding="utf-8").read() assert "support_choice: Optional[str] = None" in app assert "support_pick = request.support_choice if request.support_choice in support_choice_utils.KEYS else None" in app assert "if support_mode and risk_level == RISK_NONE:\n prompt = prompt + support_choice_utils.mode_block(support_mode)" in app assert "page_can_show=bool(request.choice_cards)" in app and "safety_active=risk_level != RISK_NONE" in app - assert "yield f\"data: {json.dumps({'event': 'choice_card', **support_choice_utils.card()})}" in app - assert "ai_message.additional_kwargs[support_choice_utils.CARD_MARK] = True" in app + asked = app.index("wait_outcome, picked = await support_choice_utils.wait_for_pick(support_card, turn_message)") + for later in ("low_move = low_moves.choose(", "prompt = build_voice_prompt(", "support_mode = support_choice_utils.current_mode(chat_sessions[history_key])\n", "memory_context = await asyncio.to_thread("): + assert app.index(later) > asked, later assert "emotional_issue = support_choice_utils.adjust_issue(emotional_issue, support_mode, checked_reply, safety_plan.active)" in app assert {"support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied"} <= self_counters.KEYS diff --git a/backend/tests/test_waits_end_on_stop.py b/backend/tests/test_waits_end_on_stop.py index 013b761..268efc8 100644 --- a/backend/tests/test_waits_end_on_stop.py +++ b/backend/tests/test_waits_end_on_stop.py @@ -221,6 +221,176 @@ def test_the_chat_endpoint_gives_a_waiting_turn_a_moment_to_end_instead_of_a_409 assert block.count("steering.is_running(history_key)") == 3 and block.index("abandon_wait") < len(block) +# ---- a message typed into the waiting turn (2026-11-29) -------------------------------------------------------------------------------------- +# The page sends what is typed during a turn as steering (POST /api/chat/steer), not as a new request, so until then it sat in the queue until the card was pressed or the wait ran out. + +def _typed(): + async def type_it(): + assert steering.submit(KEY, "actually, make it three o'clock") == "queued" + return type_it + + +async def _in_a_turn_after(register, wait, after, body_time=0.1): + """Like _in_a_turn, with the card registered inside the turn (as the tools do) and the queued messages read back after the wait.""" + seen = {} + + async def produce(): + run = steering.open_run(KEY, []) + try: + register() + started = time.monotonic() + seen["result"] = await wait() + seen["took"] = time.monotonic() - started + seen["queued"] = list(run.pending) + seen["waiting"] = run.waiting + yield "done" + finally: + steering.close_run(KEY, run) + + reader = asyncio.create_task(_drain(detached_stream.relay(produce))) + await asyncio.sleep(body_time) + await after() + await reader + return seen + + +def test_typing_ends_a_choice_card_wait_and_the_message_stays_queued_for_the_loop(): + card, _ = choices.validate_card({"question": "Which?", "options": [{"label": "A"}, {"label": "B"}]}) + seen = _run(_in_a_turn_after(lambda: choices.register("jack", card), lambda: choices.wait_for(card["choice_id"], timeout=30), _typed())) + assert seen["result"] == {"kind": "typed"} and seen["took"] < 2 and choices.waiting_count() == 0 + assert seen["queued"] == ["actually, make it three o'clock"] and seen["waiting"] == 0 + told = choices.result_text(card, seen["result"]) + assert "typed a message instead" in told and "no option was chosen" in told and "No answer came" not in told + + +def test_typing_ends_a_change_card_wait_with_nothing_applied(): + applied = [] + proposal = _change_proposal() + proposal["apply"] = lambda p: applied.append(1) or "done" + seen = _run(_in_a_turn_after(lambda: cards.register(proposal), lambda: cards.wait_for("p1", timeout=30), _typed())) + assert seen["result"] == {"kind": "typed", "message": ""} and seen["took"] < 2 and applied == [] and cards.waiting_count() == 0 + told = cards.result_text(proposal, seen["result"]) + assert "sent a message instead" in told and "was changed" in told and "APPLIED" not in told and "FAILED" not in told + + +def test_a_press_already_being_carried_out_is_not_cut_short_by_typing(): + proposal = _change_proposal() + + def slow(p): + time.sleep(0.5) + return "done" + + proposal["apply"] = slow + + async def press_then_type(): + press = asyncio.create_task(cards.decide("jack", "p1", "apply")) + await asyncio.sleep(0.1) + steering.submit(KEY, "thanks") + assert (await press)["status"] == "applied" + + seen = _run(_in_a_turn_after(lambda: cards.register(proposal), lambda: cards.wait_for("p1", timeout=30), press_then_type)) + assert seen["result"] == {"kind": "applied", "message": "done"} + + +def test_typing_ends_an_edit_decision_wait_and_a_press_afterwards_is_known_to_be_harmless(): + edits.remember_proposal("jack", "e9", {"a.py": (1, 0)}) + seen = _run(_in_a_turn_after(lambda: edits.register("jack", "e9"), lambda: edits.wait_for("e9", timeout=30), _typed())) + assert seen["result"] == {"outcome": "typed", "reason": ""} and seen["took"] < 2 and edits.waiting_count() == 0 + assert edits.decide("jack", "e9", "applied") == "no_waiter" and edits.why_no_waiter("jack", "e9") == "typed" + assert edits.no_waiter_counts("applied", "no_waiter", "typed") == {"apply_no_waiter_typed": 1} + from backend.utils import self_counters + assert "apply_no_waiter_typed" in self_counters.KEYS + + +def test_a_message_sent_before_the_card_went_up_does_not_end_its_wait(): + cards.register(_change_proposal()) # replaced below, inside the turn + cards._waiting.clear() + + def register(): + steering.submit(KEY, "also check the other file") # typed while the model was still working + cards.register(_change_proposal()) + + async def nothing(): + pass + + seen = _run(_in_a_turn_after(register, lambda: cards.wait_for("p1", timeout=0.4), nothing)) + assert seen["result"] is None and seen["took"] >= 0.35 and seen["queued"] == ["also check the other file"] + + +def test_a_message_sent_between_the_card_and_the_wait_ends_it_at_once(): + def register(): + cards.register(_change_proposal()) + steering.submit(KEY, "wait") + + async def nothing(): + pass + + seen = _run(_in_a_turn_after(register, lambda: cards.wait_for("p1", timeout=30), nothing)) + assert seen["result"]["kind"] == "typed" and seen["took"] < 1 + + +@pytest.mark.parametrize("kind", ["choice", "edit"]) +def test_a_choice_or_edit_card_also_sees_a_message_sent_between_the_card_and_the_wait(kind): + card, _ = choices.validate_card({"question": "Which?", "options": [{"label": "A"}, {"label": "B"}]}) + module, key, register = ((choices, card["choice_id"], lambda: choices.register("jack", card)) if kind == "choice" else (edits, "e7", lambda: edits.register("jack", "e7"))) + + def register_then_type(): + register() + steering.submit(KEY, "wait") + + async def nothing(): + pass + + seen = _run(_in_a_turn_after(register_then_type, lambda: module.wait_for(key, timeout=30), nothing)) + assert seen["result"] in ({"kind": "typed"}, {"outcome": "typed", "reason": ""}) and seen["took"] < 1 + + +def test_a_wait_woken_by_typing_says_so_at_once_and_one_that_takes_no_mark_is_left_alone(): + async def go(): + run = steering.open_run(KEY, []) + try: + mark = steering.typed_mark() + marked = asyncio.create_task(steering.wait_event(asyncio.Event(), 5, mark)) + await asyncio.sleep(0.05) + steering.submit(KEY, "hello") + woken = await marked + unmarked = asyncio.create_task(steering.wait_event(asyncio.Event(), 0.3)) + await asyncio.sleep(0.05) + steering.submit(KEY, "again") + return woken, await unmarked + finally: + steering.close_run(KEY, run) + + assert _run(go()) == ("typed", "timeout") + + +def test_typing_cancels_a_check_that_is_still_waiting_for_run_and_says_it_did_not_run(): + db = FakeDB() + record, _ = connected(db, now=rj._now()) + job = rj.create_job(db, "jack@example.com", record["_id"], "tests", None) + seen = _run(_in_a_turn_after(lambda: None, lambda: rj.wait_for_result(db, "jack@example.com", job["id"], timeout=30, poll=0.05), _typed(), body_time=0.3)) + assert seen["result"]["status"] == rj.CANCELLED and seen["result"][rj.TYPED_INSTEAD] is True and seen["took"] < 3 + assert rj.approve_job(db, "jack@example.com", job["id"]) is None + told = rj.format_result(seen["result"]) + assert told.startswith("NOT RUN: the person sent a message instead of pressing Run") and "CANCELLED by the person" not in told and "Do not offer" not in told + + +def test_typing_does_not_stop_a_check_they_already_started(): + db = FakeDB() + record, _ = connected(db, now=rj._now()) + job = rj.create_job(db, "jack@example.com", record["_id"], "tests", None) + assert rj.approve_job(db, "jack@example.com", job["id"]) + seen = _run(_in_a_turn_after(lambda: None, lambda: rj.wait_for_result(db, "jack@example.com", job["id"], timeout=0.8, poll=0.05), _typed(), body_time=0.3)) + assert seen["result"]["status"] == rj.APPROVED and seen["took"] >= 0.7 and rj.TYPED_INSTEAD not in seen["result"] + + +def test_the_page_stops_treating_a_card_as_awaited_once_something_is_typed(): + chat = (ROOT / "local" / "src" / "pages" / "Chat.tsx").read_text(encoding="utf-8") + steer = chat[chat.index("const handleSteer = async"):chat.index("const sendFromCard = ")] + queued = steer[steer.index("if (status === 'queued') {"):steer.index("if (status !== 'queued') {")] + assert "awaitedProposalRef.current = null;" in queued + + # ---- the helper itself ----------------------------------------------------------------------------------------------------------------------- def test_a_press_and_a_stop_at_the_same_moment_is_a_press(): diff --git a/backend/utils/runner_jobs.py b/backend/utils/runner_jobs.py index 93ba958..1e6a1b2 100644 --- a/backend/utils/runner_jobs.py +++ b/backend/utils/runner_jobs.py @@ -963,6 +963,11 @@ def waiting_text(seconds: int, status: str) -> Dict[str, str]: return {"title": "Waiting for you to press Run...", "detail": f"{clock} so far. Nothing runs until you press Run."} +TYPED_INSTEAD = "typed_instead" # on a job returned by wait_for_result: the person sent a message instead of pressing Run, so it was cancelled before it ran +_TYPED_INSTEAD_TEXT = ("NOT RUN: the person sent a message instead of pressing Run, so nothing ran and that card is closed. Their message follows: act on it. " + "If what they ask still needs the run, ask for it again.") + + def _cancel_unseen(db: Any, username: str, job_id: str) -> None: """Cancels a check whose turn ended, so it cannot run later unseen. Never raises.""" try: @@ -982,12 +987,18 @@ async def wait_for_result(db: Any, username: str, job_id: str, timeout: Optional limit = WAIT_SECONDS if timeout is None else timeout started = last_tick = time.monotonic() + mark = steering.typed_mark() try: with steering.person_wait(): while True: job = await asyncio.to_thread(get_job, db, username, job_id) if job is None or job["status"] not in OPEN_STATES: return job + if job["status"] == AWAITING and steering.typed_since(mark) and not steering.wait_stopped(): + # They typed instead of pressing Run. Only a check still waiting for that press: one they have already started runs on. + _cancel_unseen(db, username, job_id) + cancelled = await asyncio.to_thread(get_job, db, username, job_id) + return None if cancelled is None else {**cancelled, TYPED_INSTEAD: cancelled["status"] == CANCELLED} elapsed = time.monotonic() - started if elapsed >= limit: return job @@ -1206,6 +1217,8 @@ def api_result(db: Any, key: Dict[str, Any], job_id: str, body: Dict[str, Any], def format_result(job: Dict[str, Any]) -> str: """A job's outcome as the tool tells the model. The output is text a command produced on someone's machine, so it is labelled as data. Pure.""" + if job.get(TYPED_INSTEAD): + return _TYPED_INSTEAD_TEXT name, status = job.get("check"), job.get("status") if job.get("kind") == KIND_COMMAND: return _format_command_result(job) diff --git a/backend/utils/self_counters.py b/backend/utils/self_counters.py index d23a40e..5d01b03 100644 --- a/backend/utils/self_counters.py +++ b/backend/utils/self_counters.py @@ -101,7 +101,7 @@ # How much each turn mattered, whatever model wrote it (backend/utils/reply_tier.py STAKES, plus "none" for a plain turn): sizes the turns a stronger reply voice would be spent on. Counts only. "reply_stakes": ("safety", "emotional", "checkin", "companion", "identity", "frustration", "none"), } -_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "code_thinking_turns", "native_cache_expired_shrinks", "native_cache_expired_chars", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "claim_denial_dropped", "edit_turn_correction", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "shared_moment_offered", "shared_moment_used", "moment_capture_asked", "moment_capture_proposed", "moment_capture_refused", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "code_after_edit_check_run", "code_after_edit_check_failed", "code_after_edit_check_suggested", "code_after_edit_check_held", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") +_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "code_thinking_turns", "native_cache_expired_shrinks", "native_cache_expired_chars", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "claim_denial_dropped", "edit_turn_correction", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "shared_moment_offered", "shared_moment_used", "moment_capture_asked", "moment_capture_proposed", "moment_capture_refused", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "code_after_edit_check_run", "code_after_edit_check_failed", "code_after_edit_check_suggested", "code_after_edit_check_held", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "support_card_none", "support_card_moved_on", "support_card_stopped","encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") # The rhythm of a coding turn (backend/utils/loop_rhythm.py): turns it was followed on, turns that acted at all, reads before the first act (summed), edits applied, applied edits checked in the next # step, and reading-streak notices shown. Counts only. RHYTHM_KEYS = ("code_rhythm_turns", "code_rhythm_acted_turns", "code_rhythm_reads_before_first_act", "code_rhythm_applies", "code_rhythm_applies_checked", "code_rhythm_streak_notices") @@ -132,7 +132,7 @@ LESSON_KEYS = ("lesson_offered", "guidance_edit_proposed") # Apply or Decline pressed when no turn was waiting for it (backend/services/local_edit_decisions.py why_no_waiter): the stream was cut while the turn waited, the wait timed out, the proposal was already answered, # or this process never held it (another instance, a restart). Counts only. -APPLY_WAIT_KEYS = ("apply_no_waiter_cancelled", "apply_no_waiter_timeout", "apply_no_waiter_decided", "apply_no_waiter_not_here") +APPLY_WAIT_KEYS = ("apply_no_waiter_cancelled", "apply_no_waiter_timeout", "apply_no_waiter_decided", "apply_no_waiter_not_here", "apply_no_waiter_typed") # The conversation summary (backend/utils/conversation_summary.py): messages that said Sonic should already know something ("I already told you"), and the same inside a conversation that had a # summary in force; turns that had one and the characters it added to their prompts; folds (and the ones the person asked for), items kept and thrown out by the checks, and edits by the person. Counts only. CONVSUM_KEYS = ("convsum_forgot", "convsum_forgot_summarized", "convsum_summarized_turns", "convsum_chars_injected", "convsum_folds", "convsum_manual_folds", "convsum_item_added", "convsum_item_dropped", @@ -204,9 +204,9 @@ # Requests refused by the per-address rate limit (backend/utils/rate_limit.py), by rule (auth, webhook, guest): one address over its limit, and `_all` for everyone together over the rule's total. Flushed at most once a minute. Counts only. RATE_LIMIT_KEYS = ("rate_limited_auth", "rate_limited_auth_all", "rate_limited_webhook", "rate_limited_webhook_all", "rate_limited_guest", "rate_limited_guest_all") # Calendar-change cards (backend/services/change_cards.py): shown, then how each ended (applied, declined, failed, or no press before the wait ran out), and proposals refused before a card was shown. Counts only. -CALENDAR_CHANGE_KEYS = ("calendar_change_shown", "calendar_change_applied", "calendar_change_declined", "calendar_change_failed", "calendar_change_timeout", "calendar_change_refused") +CALENDAR_CHANGE_KEYS = ("calendar_change_shown", "calendar_change_applied", "calendar_change_declined", "calendar_change_failed", "calendar_change_timeout", "calendar_change_refused", "calendar_change_typed") # The same for Google Doc changes (backend/services/doc_changes_service.py). Counts only. -DOC_CHANGE_KEYS = ("doc_change_shown", "doc_change_applied", "doc_change_declined", "doc_change_failed", "doc_change_timeout", "doc_change_refused") +DOC_CHANGE_KEYS = ("doc_change_shown", "doc_change_applied", "doc_change_declined", "doc_change_failed", "doc_change_timeout", "doc_change_refused", "doc_change_typed") # The connected project's own skills (backend/utils/skills.py): coding turns where some were listed, skills loaded with use_skill, and loads that named none the project has. Counts only: a name is never counted. SKILL_KEYS = ("skill_turns_with_skills", "skill_used", "skill_not_found") # Tool loops run with one tool list for every call so the prompt cache is read (backend/services/native_loop.py STABLE_CONTINUE_TOOL), and forced endings that used a tool they may not use there and were diff --git a/backend/utils/support_choice.py b/backend/utils/support_choice.py index c9afaa6..dce2cb4 100644 --- a/backend/utils/support_choice.py +++ b/backend/utils/support_choice.py @@ -1,8 +1,14 @@ """Asking someone who is having a hard time what they want from Sonic (just listen, advice, or help fixing it), instead of guessing, and keeping their answer for the rest of that stretch. -WHY (Jack, 2026-11-23). The reasoner reads a hidden "need" from every message (venting, solving...), and the reply follows the guess. A friend asks. The coding tool loop already has a choice card -(backend/services/choice_cards.py), but that card pauses a turn that is waiting; a conversational reply has nothing waiting. So here the reply is written first, in full, and the card comes at the end; -a tap sends the option as the person's next message, carrying which option it was (`support_choice` on the chat request), and that sets the mode. +WHY (Jack, 2026-11-23). The reasoner reads a hidden "need" from every message (venting, solving...), and the reply follows the guess. A friend asks. + +THE CARD COMES FIRST (Jack, 2026-11-29). It began as a card after a reply that had already been written, drawn above it, so "You chose: Give me advice" sat over a reply that was not advice, and the tap +was answered as a message of its own. Now the turn shows the card before writing anything and waits (backend/services/choice_cards.py), up to WAIT_SECONDS: +- they tap: the option is marked on THEIR message, and one reply is written in that mode about what they actually said; +- no tap in time: the reply is written with no mode, so a locked phone still comes back to a finished reply; +- they type instead, or send a new message: this turn ends without a reply, and that message gets one in full (read for safety and mood like any other), with the first one above it in the history; +- Stop: the turn ends. +A tap after the wait has passed is sent as their next message, carrying which option it was (`support_choice` on the chat request), and that sets the mode. WHEN THE CARD IS OFFERED (`should_offer`, all in code): - this message was read as low, distressed or frustrated, at least OFFER_MIN_INTENSITY, and not a small lift; @@ -14,17 +20,21 @@ steps. It lasts MODE_HOURS from the pick, and they can change it any time by saying so (the block says to follow that). The pick is a mark on their own message, saved with the conversation, so nothing else is stored. """ +import os import re import uuid from datetime import datetime, timedelta, timezone -from typing import Any, Dict, Iterable, List, Optional +from typing import Any, Dict, Iterable, List, Optional, Tuple +from backend.services import choice_cards, steering from backend.utils import view_check from backend.utils.emotion_utils import NEGATIVE_VALENCES from backend.utils.time_utils import sent_at MODE_MARK = "support_mode" # on their message: the option they picked ("listen", "advice", "fix") -CARD_MARK = "support_card" # on Sonic's reply: a card was shown with it +CARD_MARK = "support_card" # on their message: a card was shown for it (conversations saved before 2026-11-29 carry it on Sonic's reply instead) +WAIT_SECONDS = float(os.getenv("SUPPORT_CARD_WAIT_SECONDS", "90")) # how long the reply waits for a tap before it is written anyway +PICKED, NO_TAP, MOVED_ON, STOPPED = "picked", "none", "moved_on", "stopped" MODE_HOURS = 6 LISTEN_TURNS = 10 # how many of their messages "just listen" holds for after the tap OFFER_MIN_INTENSITY = 0.35 @@ -70,10 +80,10 @@ def current_mode(messages: Iterable[Any], now: Optional[datetime] = None) -> Opt def card_offered_recently(messages: Iterable[Any], now: Optional[datetime] = None) -> bool: - """True when one of Sonic's replies in the last MODE_HOURS carried a card. Pure apart from the clock.""" + """True when a card was shown in the last MODE_HOURS, whether or not a reply followed it. Pure apart from the clock.""" moment = now or datetime.now(timezone.utc) for message in reversed(list(messages or [])): - if getattr(message, "type", "") == "ai" and (getattr(message, "additional_kwargs", None) or {}).get(CARD_MARK): + if (getattr(message, "additional_kwargs", None) or {}).get(CARD_MARK): when = sent_at(message) if when is not None and moment - when <= timedelta(hours=MODE_HOURS): return True @@ -82,7 +92,7 @@ def card_offered_recently(messages: Iterable[Any], now: Optional[datetime] = Non def should_offer(emotional_state: Any, message: str, messages: Iterable[Any], *, page_can_show: bool, conversational: bool, closing: bool, safety_active: bool, now: Optional[datetime] = None) -> bool: - """Whether this reply ends with the card (see the module docstring). Pure apart from the clock.""" + """Whether the card goes up before this reply (see the module docstring). `messages` is the conversation before this message. Pure apart from the clock.""" if not page_can_show or not conversational or closing or safety_active or stated_what_they_want(message): return False state = emotional_state if isinstance(emotional_state, dict) else {} @@ -98,17 +108,40 @@ def should_offer(emotional_state: Any, message: str, messages: Iterable[Any], *, def card() -> Dict[str, Any]: - """The card for the page: the same shape as a tool-loop choice card, with `mode` "message" (a tap is sent as their next message) and each option's `key`. Pure apart from the new id.""" + """The card for the page: the same shape as a tool-loop choice card, answered back to the waiting turn (`mode` "answer"), with each option's `key`. `fallback` "message" tells the page that once + nobody is waiting, a tap is sent as their next message instead. Pure apart from the new id.""" return { - "choice_id": uuid.uuid4().hex, "question": QUESTION, "mode": "message", "kind": "support", + "choice_id": uuid.uuid4().hex, "question": QUESTION, "mode": "answer", "fallback": "message", "kind": "support", "options": [{"key": key, "label": label, "description": description, "recommended": False} for key, label, description in OPTIONS], } -OFFER_NOTE = ( - "\nA CARD WILL FOLLOW YOUR REPLY asking what would help most: just listen, advice, or help fixing it. So write your reply to what they said, in full, and do not end with a question of " - "your own or ask what they want from you: the card asks that. Do not mention the card.\n" -) +def show(username: str, shown: Dict[str, Any], message: Any) -> None: + """Gets ready to wait for `shown`, and marks their message as the one it was shown for. Call before the card is streamed, so a very quick tap cannot arrive first.""" + choice_cards.register(username, shown, words=False) + message.additional_kwargs[CARD_MARK] = True + + +async def wait_for_pick(shown: Dict[str, Any], message: Any, timeout: Optional[float] = None) -> Tuple[str, Optional[str]]: + """Waits for the tap and says how the wait ended: (PICKED, key), with the mode marked on their message; (NO_TAP, None) when the time ran out; (MOVED_ON, None) when they typed or sent a new + message instead; (STOPPED, None) for the Stop button. Never raises except when the turn itself is cancelled.""" + answer = await choice_cards.wait_for(shown["choice_id"], timeout=WAIT_SECONDS if timeout is None else timeout) + if answer and answer["kind"] == "picked": + key = shown["options"][answer["index"]]["key"] + message.additional_kwargs[MODE_MARK] = key + return PICKED, key + if (answer and answer["kind"] == "typed") or steering.moved_on(): + return MOVED_ON, None + if steering.wait_stopped(): + return STOPPED, None + return NO_TAP, None + + +def counts_for_wait(outcome: str, key: Optional[str] = None) -> Dict[str, int]: + """The counters for how a wait ended (self_counters SUPPORT_KEYS). Pure.""" + if outcome == PICKED: + return counts_for_pick(key) + return {f"support_card_{outcome}": 1} if outcome in (NO_TAP, MOVED_ON, STOPPED) else {} _MODE_TEXT = { "listen": ( diff --git a/local/src/components/ChoiceCard.tsx b/local/src/components/ChoiceCard.tsx index 22b38a2..411e561 100644 --- a/local/src/components/ChoiceCard.tsx +++ b/local/src/components/ChoiceCard.tsx @@ -1,11 +1,11 @@ import { useEffect, useRef, useState } from 'react'; import { api } from '../api'; -import { MAX_OTHER_CHARS, answerText, cleanOther, messageFor, type ChoiceAnswer, type ChoiceCardData } from './choiceCardLogic'; +import { MAX_OTHER_CHARS, afterAnswer, answerText, cleanOther, goesAsMessage, messageFor, type ChoiceAnswer, type ChoiceCardData } from './choiceCardLogic'; import './__styles__/ChoiceCard.css'; interface ChoiceCardProps { card: ChoiceCardData; - /** Message mode: sends the pick as the person's next message (the chat page's own send), with the option's key. */ + /** Sends the pick or the words as a message (the chat page decides when it can go), with the option's key. Used when nothing is waiting for the answer. */ onSendMessage?: (text: string, key?: string) => void; } @@ -16,9 +16,10 @@ type State = | { kind: 'expired' }; /** - * One question from Sonic with a few options (its ask_choice tool, backend/services/choice_cards.py): a button for each option, its recommendation first, and a box for something else. - * Sonic's turn is waiting for the answer, so pressing a button sends it straight back and Sonic carries on, with everything it had read still in hand. If nobody is waiting any more - * (the turn timed out or ended), the card says so, and the answer can simply be typed as a message. + * One question from Sonic with a few options (its ask_choice tool, backend/services/choice_cards.py, and the support card, backend/utils/support_choice.py): a button for each option, its + * recommendation first, and a box for something else. Sonic's turn is waiting for the answer, so pressing a button sends it straight back and Sonic carries on, with everything it had read + * still in hand. If nobody is waiting any more (the turn timed out or ended), the card says so, and the answer can simply be typed as a message; a card with a message fallback sends it that + * way itself. */ export default function ChoiceCard({ card, onSendMessage }: ChoiceCardProps) { const [state, setState] = useState({ kind: 'open' }); @@ -29,22 +30,27 @@ export default function ChoiceCard({ card, onSendMessage }: ChoiceCardProps) { const open = state.kind === 'open'; + const sendAsMessage = (answer: ChoiceAnswer) => { + const { text, key } = messageFor(card, answer); + if (!text || !onSendMessage) return; + onSendMessage(text, key); + setState({ kind: 'answered', answer }); + }; + const send = async (answer: ChoiceAnswer) => { if (state.kind !== 'open') return; setError(''); - if (card.mode === 'message') { - // Nothing is waiting: the pick is the person's next message (the support card, backend/utils/support_choice.py). - const { text, key } = messageFor(card, answer); - if (!text || !onSendMessage) return; - onSendMessage(text, key); - setState({ kind: 'answered', answer }); + if (goesAsMessage(card, answer)) { + sendAsMessage(answer); return; } setState({ kind: 'sending' }); try { const reply = await api.answerChoice(card.choice_id, 'index' in answer ? { index: answer.index } : { other: answer.other }); if (!alive.current) return; - setState(reply.status === 'recorded' ? { kind: 'answered', answer } : { kind: 'expired' }); + const next = afterAnswer(card, reply.status); + if (next === 'send') sendAsMessage(answer); + else setState(next === 'answered' ? { kind: 'answered', answer } : { kind: 'expired' }); } catch (problem) { if (!alive.current) return; setError(problem instanceof Error ? problem.message : 'Could not send your answer.'); diff --git a/local/src/components/choiceCardLogic.test.mjs b/local/src/components/choiceCardLogic.test.mjs index 9cf87b5..088d59e 100644 --- a/local/src/components/choiceCardLogic.test.mjs +++ b/local/src/components/choiceCardLogic.test.mjs @@ -1,7 +1,7 @@ // Run with: node --test src/components/choiceCardLogic.test.mjs (from local/; Node 22.18+ runs the TypeScript module directly) import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { MAX_OTHER_CHARS, answerText, cleanOther, messageFor, parseChoiceCard } from './choiceCardLogic.ts'; +import { MAX_OTHER_CHARS, afterAnswer, answerText, cleanOther, goesAsMessage, messageFor, parseChoiceCard } from './choiceCardLogic.ts'; const good = { choice_id: 'abc123', @@ -46,7 +46,28 @@ test('an answered card says what was chosen or written', () => { assert.equal(answerText(card, { index: 9 }), 'You answered.'); }); -// ---- the support card (backend/utils/support_choice.py): nothing is waiting, so a tap is the person's next message ---- +// ---- the support card (backend/utils/support_choice.py): a short wait for the tap, and a message once nobody is waiting ---- + +test('the support card answers the waiting turn, and only a card that says so falls back to a message', () => { + const waiting = parseChoiceCard({ ...support, mode: 'answer', fallback: 'message' }); + assert.equal(waiting.mode, 'answer'); + assert.equal(waiting.fallback, 'message'); + assert.equal(goesAsMessage(waiting, { index: 1 }), false); + assert.equal(goesAsMessage(waiting, { other: 'something of my own' }), true); // words are sent as an ordinary message, never to the waiting turn + assert.equal(afterAnswer(waiting, 'recorded'), 'answered'); + assert.equal(afterAnswer(waiting, 'no_waiter'), 'send'); + assert.equal(afterAnswer(waiting, 'invalid'), 'expired'); + + const tool = parseChoiceCard(good); + assert.equal(tool.fallback, undefined); + assert.equal(parseChoiceCard({ ...good, fallback: 'anything' }).fallback, undefined); + assert.equal(goesAsMessage(tool, { index: 0 }), false); + assert.equal(goesAsMessage(tool, { other: 'words' }), false); + assert.equal(afterAnswer(tool, 'no_waiter'), 'expired'); + assert.equal(afterAnswer(tool, 'recorded'), 'answered'); + + assert.equal(goesAsMessage(parseChoiceCard(support), { index: 0 }), true); // a message-mode card from an older server still sends +}); const support = { choice_id: 'sup1', diff --git a/local/src/components/choiceCardLogic.ts b/local/src/components/choiceCardLogic.ts index 2e72732..7b5bccf 100644 --- a/local/src/components/choiceCardLogic.ts +++ b/local/src/components/choiceCardLogic.ts @@ -16,10 +16,15 @@ export interface ChoiceCardData { question: string; options: ChoiceOption[]; /** - * "answer" (the default): a tool turn is waiting, and the card answers it (POST /api/chat/choice/{id}). - * "message": nothing is waiting (the support card after a conversational reply, backend/utils/support_choice.py), so a tap is sent as the person's next message, carrying the option's key. + * "answer" (the default): a turn is waiting, and the card answers it (POST /api/chat/choice/{id}). + * "message": nothing is waiting, so a tap is sent as the person's next message, carrying the option's key (the support card before 2026-11-29). */ mode: 'answer' | 'message'; + /** + * "message": once nobody is waiting any more, a tap is sent as the next message instead of being refused, and the person's own words always go as a message + * (the support card, which waits a short while before the reply is written: backend/utils/support_choice.py). + */ + fallback?: 'message'; } /** An option by its position (0 is the first button), or the person's own words. */ @@ -44,7 +49,18 @@ export function parseChoiceCard(payload: unknown): ChoiceCardData | null { const key = typeof o.key === 'string' && /^[a-z_]{1,20}$/.test(o.key) ? o.key : undefined; options.push({ label, description: typeof o.description === 'string' ? o.description.trim() : '', recommended: o.recommended === true, ...(key ? { key } : {}) }); } - return { choice_id: id, question, options, mode: raw.mode === 'message' ? 'message' : 'answer' }; + return { choice_id: id, question, options, mode: raw.mode === 'message' ? 'message' : 'answer', ...(raw.fallback === 'message' ? { fallback: 'message' as const } : {}) }; +} + +/** Whether this answer goes out as a message rather than back to a waiting turn. */ +export function goesAsMessage(card: ChoiceCardData, answer: ChoiceAnswer): boolean { + return card.mode === 'message' || (card.fallback === 'message' && !('index' in answer)); +} + +/** What the card does with the server's reply to an answer sent back to a turn: it was taken, it goes as a message instead (nobody waiting, on a card that allows that), or it is too late. */ +export function afterAnswer(card: ChoiceCardData, status: 'recorded' | 'no_waiter' | 'invalid'): 'answered' | 'send' | 'expired' { + if (status === 'recorded') return 'answered'; + return status === 'no_waiter' && card.fallback === 'message' ? 'send' : 'expired'; } /** The person's own words as they are sent: trimmed, spaces collapsed, cut to what the server accepts. Empty means there is nothing to send. */ diff --git a/local/src/pages/Chat.tsx b/local/src/pages/Chat.tsx index 45fccc5..212ea31 100644 --- a/local/src/pages/Chat.tsx +++ b/local/src/pages/Chat.tsx @@ -239,6 +239,7 @@ interface ChatMessageListProps { messagesEndRef: React.RefObject; attachmentsRef: React.MutableRefObject<{ filename: string; content: string }[]>; handleSendMessageRef: React.MutableRefObject<(text: string, attachments: { filename: string; content: string }[], replaceIds?: string[], supportChoice?: string) => void>; + sendFromCardRef: React.MutableRefObject<(text: string, supportChoice?: string) => void>; handleFeedbackRef: React.MutableRefObject<(messageId: string, choice: 'like' | 'dislike') => void>; getTokenRef: React.MutableRefObject<(() => Promise) | undefined>; canEditLocal: boolean; @@ -319,7 +320,7 @@ function CodeBlock({ language, code }: { language: string; code: string }) { // sessionId/principal/etc — the same class of bug fixed earlier for attachmentsRef. const ChatMessageList = React.memo(function ChatMessageList({ messages, earlierCount, loadingEarlier, loadEarlierRef, hasChatted, loading, agentStatus, latestStepTitle, liveSteps, theme, isEmbedded, - chatWindowRef, messagesEndRef, attachmentsRef, handleSendMessageRef, handleFeedbackRef, getTokenRef, + chatWindowRef, messagesEndRef, attachmentsRef, handleSendMessageRef, sendFromCardRef, handleFeedbackRef, getTokenRef, canEditLocal, localEditActionsRef, localGitMode, planCard, planAnchorId = null, putInComposer, }: ChatMessageListProps) { // The reply whose "Source: Memory" citation was clicked: its viewer is open while this is set. @@ -410,7 +411,7 @@ const ChatMessageList = React.memo(function ChatMessageList({ /> )} - {msg.choiceCard && handleSendMessageRef.current(text, attachmentsRef.current, [], key)} />} + {msg.choiceCard && sendFromCardRef.current(text, key)} />} {msg.changeCard && } {msg.runnerCheck && } {msg.commandSteps && s.id).join('-') + msg.id} steps={msg.commandSteps.steps} runner={msg.commandSteps.runner} onTell={putInComposer} />} @@ -852,7 +853,7 @@ export const ChatPage: React.FC = ({ theme, toggleTheme }) => { // folded them into the agent's work; whatever is still unapplied when the turn ends is re-sent // as an ordinary message so a steer is never lost. const steerLogRef = useRef<{ id: string; text: string; applied: boolean }[]>([]); - const pendingResendRef = useRef<{ id: string; text: string }[]>([]); + const pendingResendRef = useRef<{ id: string; text: string; supportChoice?: string }[]>([]); // The server holds a turn open while a proposed change waits for Apply or Decline. If the person's report finds nobody waiting (the server restarted under the turn, for one), the turn is dead and the // page must not stay busy until a reload: `awaitedProposalRef` is the proposal this turn waits on, `lostTurnRef` says the turn was ended for that reason. const awaitedProposalRef = useRef(null); @@ -2313,7 +2314,11 @@ useEffect(() => { } catch (err) { console.warn("Steering request failed; it will be sent as a normal message instead.", err); } - if (status === 'queued') setPatchySteer(c => c + 1); + if (status === 'queued') { + setPatchySteer(c => c + 1); + // A message typed while a card is up ends that wait (backend/services/steering.py), so this turn no longer waits on a proposal: pressing its card afterwards must not read as a lost turn. + awaitedProposalRef.current = null; + } if (status !== 'queued') { // Nothing could act on it (no running turn, work phase already over, ...): send it as the next // message as soon as the current turn is done. @@ -2324,6 +2329,19 @@ useEffect(() => { } }; + // A pick or a few words from a card that nothing is waiting for (components/ChoiceCard.tsx). While Sonic is working, words go in like anything typed, and an option waits for the turn to end so it + // keeps which option it was. + const sendFromCard = (text: string, supportChoice?: string) => { + if (!loading) { + void handleSendMessage(text, attachmentsRef.current, [], supportChoice); + } else if (!supportChoice) { + void handleSteer(text); + } else { + pendingResendRef.current.push({ id: genId(), text, supportChoice }); + setResendTick(t => t + 1); + } + }; + const onSubmitForm = (e: React.FormEvent) => { e.preventDefault(); if (!input.trim()) return; @@ -2359,6 +2377,7 @@ useEffect(() => { // below can skip re-rendering on unrelated state changes (e.g. typing) without ever calling a // stale version of these handlers — the same stale-closure fix applied earlier to attachmentsRef. const handleSendMessageRef = useRef(handleSendMessage); +const sendFromCardRef = useRef(sendFromCard); const handleFeedbackRef = useRef(handleFeedback); const getTokenRef = useRef(getToken); // The person's Apply or Decline, reported to the turn that waits on it. Only the FIRST report for the proposal this turn waits on can say the turn is gone: the server answers "no_waiter" when nobody is @@ -2378,6 +2397,7 @@ useEffect(() => { // Pressing Start office hours is the person saying "let's begin": the first line goes in for them, and Sonic opens the meeting. meetingStartedRef.current = (name: string) => { void handleSendMessageRef.current(`Let's start our ${name}.`, []); }; handleSendMessageRef.current = handleSendMessage; + sendFromCardRef.current = sendFromCard; handleFeedbackRef.current = handleFeedback; getTokenRef.current = getToken; localEditActionsRef.current = { apply: workspace.applyEdits, undo: workspace.undoEdits, getFolderHandle: workspace.getFolderHandle, decide: decideOnProposal, connect: workspace.connect, canConnect: workspace.supported }; @@ -2391,7 +2411,7 @@ useEffect(() => { const next = pendingResendRef.current.shift(); if (!next) return; setMessages(prev => prev.filter(m => m.id !== next.id)); - handleSendMessageRef.current(next.text, []); + handleSendMessageRef.current(next.text, [], [], next.supportChoice); }, [loading, resendTick]); const sendFeedbackPayload = async ( @@ -2770,6 +2790,7 @@ const handleSubmitNegativeFeedback = async (e: React.FormEvent) => { messagesEndRef={messagesEndRef} attachmentsRef={attachmentsRef} handleSendMessageRef={handleSendMessageRef} + sendFromCardRef={sendFromCardRef} handleFeedbackRef={handleFeedbackRef} getTokenRef={getTokenRef} canEditLocal={workspace.canEdit}