Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 36 additions & 14 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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],
Expand Down
4 changes: 2 additions & 2 deletions backend/components/sonic_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
},
Expand Down Expand Up @@ -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": [],
Expand Down
10 changes: 9 additions & 1 deletion backend/services/agent_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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}
Expand All @@ -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")
Expand Down
17 changes: 13 additions & 4 deletions backend/services/change_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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":
Expand Down
Loading
Loading