The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(free-tier): offer sign-in after finished tasks, backing off
alt-glitch995bc1c0e7de
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 7e0c7d14632..c5e6859a811 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -1734,6 +1734,8 @@ def run_conversation(from agent.turn_context import export_current_turn_boundaryfrom tools.vision_tools_history_budget import native_turn_images+ # Steer / redirect / interrupt set this mid-turn; the result reports whether the turn ran untouched.+ agent._turn_user_intervened = False# Images attached natively to this user turn stay visible to vision_analyze for the turn, so# it does not embed the same pixels a second time into the same request (#76411).with native_turn_images(user_message):@@ -1755,6 +1757,8 @@ def run_conversation(prelude=prelude,)result = export_current_turn_boundary(agent, result, user_message)+ if isinstance(result, dict):+ result["user_intervened"] = bool(getattr(agent, "_turn_user_intervened", False))_close_durable_failed_turn(agent, result)return resultdiff --git a/agent/interrupt_control.py b/agent/interrupt_control.pyindex 4276f64d2ac..22fb3a749a0 100644--- a/agent/interrupt_control.py+++ b/agent/interrupt_control.py@@ -142,6 +142,7 @@ class InterruptControlMixin:self._interrupt_requested = Trueself._interrupt_message = messageself._tool_interrupt_reason = tool_interrupt_reason+ self._turn_user_intervened = True# The turn record and the log must agree on WHO asked for the stop (#112647).logger.info("Interrupt requested (%s): %s", "hard" if hard_cancel else "soft", tool_interrupt_reason)_hard_event = getattr(self, "_hard_interrupt_requested", None) if hard_cancel else None@@ -256,6 +257,8 @@ class InterruptControlMixin:with _ic_lock(self, "_pending_steer_lock"):existing = _ic_slot(self, "_pending_steer_lock", "_pending_steer")self._pending_steer = (existing + "\n" + cleaned) if existing else cleaned+ # The turn no longer ran on its own (first-task-done detection reads this off the result).+ self._turn_user_intervened = Truereturn Truedef redirect(self, text: str) -> bool:@@ -273,7 +276,10 @@ class InterruptControlMixin:if self._interrupt_requested:return Falsetry:- return bool(_native_steer(cleaned))+ accepted = bool(_native_steer(cleaned))+ if accepted:+ self._turn_user_intervened = True+ return acceptedexcept Exception:logger.debug("Codex app-server turn/steer failed", exc_info=True)return False@@ -306,6 +312,7 @@ class InterruptControlMixin:)self._interrupt_requested = Trueself._interrupt_message = None+ self._turn_user_intervened = True# Interrupt only the model request — no fan-out to tool workers / child agents as interrupt() does._execution_thread_id = getattr(self, "_execution_thread_id", None)diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 72f4b4a2cd1..46474dcb51e 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -643,6 +643,7 @@ export interface FreeTierStatusResult {retryable?: boolean | nullretry_after?: number | nullchallenge?: FreeTierChallengePayload | null+ nudge_due_in?: number | null}/** ``hermes_cli/anon_challenge.py::BrowserChallenge.as_payload``: the ``free_tier.challenge`` event, and ``free_tier.status``'s ``challenge`` field for a client that connected after it. */export interface FreeTierChallengePayload {@@ -674,6 +675,9 @@ export interface FreeTierProvisionResult {export interface FreeTierAckNoticeResult {acked: boolean}+export interface FreeTierClaimNudgeResult {+ claimed: boolean+}/** The focused profile's ``telemetry.shared_metrics`` opt-ins. ``send`` is never true while ``enabled`` is false; ``decided`` = either key is written in config.yaml (the shipped defaults are not an answer) and it is not a ``reask``: an "off" from before the type-ahead fix, offered once more with the reason. */export interface SharedMetricsConsentResult {enabled: boolean@@ -5108,6 +5112,8 @@ export interface RpcMethods {'free_tier.ack_notice': { params: ProfileParams; result: FreeTierAckNoticeResult }/** Report a browser window outcome for the matching pending attempt; mint remains authoritative. */'free_tier.challenge_result': { params: FreeTierChallengeResultParams; result: FreeTierChallengeResult }+ /** Claim the due sign-in offer; true for exactly one caller each time an offer comes due. */+ 'free_tier.claim_nudge': { params: ProfileParams; result: FreeTierClaimNudgeResult }/** Explicit retry of the free-tier identity mint when the boot bootstrap could not create it. */'free_tier.provision': { params: ProfileParams; result: FreeTierProvisionResult }/** Pure read of the focused profile's free-tier identity state (no network, no side effects). */@@ -5562,6 +5568,7 @@ export const RPC_METHODS = ['file.attach','free_tier.ack_notice','free_tier.challenge_result',+ 'free_tier.claim_nudge','free_tier.provision','free_tier.status','gateway.capabilities',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 7caf4a68e75..c39c0b45db4 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -1032,6 +1032,24 @@}}},+ {+ "name": "free_tier.claim_nudge",+ "summary": "Claim the due sign-in offer; true for exactly one caller each time an offer comes due.",+ "params": [+ {+ "name": "params",+ "schema": {+ "$ref": "#/components/schemas/ProfileParams"+ }+ }+ ],+ "result": {+ "name": "result",+ "schema": {+ "$ref": "#/components/schemas/FreeTierClaimNudgeResult"+ }+ }+ },{"name": "free_tier.provision","summary": "Explicit retry of the free-tier identity mint when the boot bootstrap could not create it.",@@ -14271,6 +14289,20 @@"title": "FreeTierChallengeResultParams","type": "object"},+ "FreeTierClaimNudgeResult": {+ "additionalProperties": false,+ "properties": {+ "claimed": {+ "title": "Claimed",+ "type": "boolean"+ }+ },+ "required": [+ "claimed"+ ],+ "title": "FreeTierClaimNudgeResult",+ "type": "object"+ },"FreeTierProvisionResult": {"additionalProperties": false,"properties": {@@ -14424,6 +14456,18 @@}],"default": null+ },+ "nudge_due_in": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Nudge Due In"}},"required": [diff --git a/hermes_cli/free_tier_offer.py b/hermes_cli/free_tier_offer.pynew file mode 100644index 00000000000..d9b95dabfd1--- /dev/null+++ b/hermes_cli/free_tier_offer.py@@ -0,0 +1,93 @@+"""When the free tier's "sign in for more" offer is due: after finished tasks, backing off.++The first offer comes ``OFFER_DELAY_S`` after the first finished task (normally the task setup hands off+to). Each later offer needs another finished task after the previous offer, comes ``OFFER_DELAY_S``+after that task, and never sooner than ``REOFFER_AFTER_S[n]`` after the previous offer, so a user who+keeps saying "Not now" hears it less often. "Finished task" is ``tui_gateway.free_tier_task_done``'s+call. The record is install-wide (the setup and primary profiles have different homes), at+``<default root>/free_tier/sign_in_offer.json``. Signing in ends the free tier, and with it every offer.+"""++from __future__ import annotations++import json+import math+import threading+import time+from contextlib import contextmanager+from typing import Any, Dict, Iterator, Optional++OFFER_DELAY_S = 180+REOFFER_AFTER_S = (60 * 60, 4 * 60 * 60, 24 * 60 * 60) # after the 1st, 2nd, then every later offer++_LOCK = threading.local()+_clock = time.time # tests swap this for a fake clock+++def _path():+ from hermes_constants import get_default_hermes_root+ return get_default_hermes_root() / "free_tier" / "sign_in_offer.json"+++def _read() -> Dict[str, Any]:+ try:+ data = json.loads(_path().read_text(encoding="utf-8-sig"))+ except (OSError, ValueError):+ return {}+ return data if isinstance(data, dict) and isinstance(data.get("first_task_at"), (int, float)) else {}+++@contextmanager+def _transaction() -> Iterator[tuple[Dict[str, Any], Any]]:+ from hermes_cli.auth import _file_lock+ from utils import atomic_write_text+ path = _path()+ with _file_lock(path.with_suffix(".lock"), _LOCK, 5.0, f"Timed out waiting for the sign-in offer record ({path})"):+ yield _read(), lambda data: atomic_write_text(path, json.dumps(data))+++def _on_free_tier() -> bool:+ from hermes_cli import anon_auth+ return anon_auth.has_guest() and anon_auth.guest_enabled()+++def _due_at(state: Dict[str, Any]) -> Optional[float]:+ if not state:+ return None+ offers = int(state.get("offers") or 0)+ last_task = float(state.get("last_task_at") or state["first_task_at"])+ if offers == 0:+ return float(state["first_task_at"]) + OFFER_DELAY_S+ last_offer = float(state.get("last_offered_at") or 0)+ if last_task <= last_offer:+ return None # nothing finished since the last offer+ return max(last_task + OFFER_DELAY_S, last_offer + REOFFER_AFTER_S[min(offers, len(REOFFER_AFTER_S)) - 1])+++def _due_in(state: Dict[str, Any]) -> Optional[int]:+ due_at = _due_at(state)+ if due_at is None or not _on_free_tier():+ return None+ return max(0, math.ceil(due_at - _clock()))+++def record_task_done() -> None:+ """A task finished on the free tier: the first one starts the offer clock, later ones re-arm it."""+ with _transaction() as (state, write):+ now = _clock()+ write({**state, "first_task_at": state.get("first_task_at", now), "last_task_at": now})+++def offer_due_in() -> Optional[int]:+ """Seconds until the offer is due (0 = now); None when none is pending or the user is not on the+ free tier. A pure read."""+ return _due_in(_read())+++def claim_offer() -> bool:+ """Compare-and-set under the lock: True for exactly one caller each time an offer comes due."""+ with _transaction() as (state, write):+ if _due_in(state) != 0:+ return False+ write({**state, "offers": int(state.get("offers") or 0) + 1, "last_offered_at": _clock()})+ return Truediff --git a/tests/agent/test_turn_user_intervened.py b/tests/agent/test_turn_user_intervened.pynew file mode 100644index 00000000000..ac0353e2525--- /dev/null+++ b/tests/agent/test_turn_user_intervened.py@@ -0,0 +1,95 @@+"""A turn reports ``user_intervened`` when the user steered, redirected or interrupted it, even when+the correction was fully absorbed and the turn still ``completed`` (first-task-done detection)."""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from tests.agent.test_run_agent import _mock_response+from tools.registry import registry++_PROBE = "intervention_probe"+_DURING_TOOL: list = [] # callables run inside the tool, i.e. while the turn is executing tools+++def _probe(args, **_kw):+ for fn in _DURING_TOOL:+ fn()+ return "probe ok"+++registry.register(+ name=_PROBE, toolset="utility",+ schema={"name": _PROBE, "description": "probe", "parameters": {"type": "object", "properties": {}}},+ handler=_probe, override=True)++[email protected](autouse=True)+def _clear_tool_hooks():+ _DURING_TOOL.clear()+ yield+ _DURING_TOOL.clear()+++def _loop_agent():+ from run_agent import AIAgent+ schema = {"type": "function", "function": {+ "name": _PROBE, "description": "probe", "parameters": {"type": "object", "properties": {}}}}+ with (patch("model_tools.get_tool_definitions", return_value=[schema]),+ patch("model_tools.check_toolset_requirements", return_value={}),+ patch("agent.process_bootstrap.OpenAI")):+ agent = AIAgent(api_key="test-key-1234567890", base_url="https://openrouter.ai/api/v1",+ quiet_mode=True, skip_context_files=True, skip_memory=True)+ agent.client = MagicMock()+ agent._disable_streaming = True+ agent._cached_system_prompt = "You are helpful."+ agent._use_prompt_caching = False+ agent.tool_delay = 0+ agent.compression_enabled = False+ agent.save_trajectories = False+ return agent+++def _run(agent, model_call, text="do the task"):+ agent._interruptible_api_call = model_call+ with (patch.object(agent, "_flush_messages_to_session_db"), patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"), patch.object(agent, "_cleanup_task_resources")):+ return agent.run_conversation(text)+++def _tool_then_reply(agent, intervene):+ calls = []++ def model_call(api_kwargs):+ calls.append(1)+ if len(calls) == 1:+ call = SimpleNamespace(id="c1", type="function", function=SimpleNamespace(name=_PROBE, arguments="{}"))+ return _mock_response(content=None, finish_reason="tool_calls", tool_calls=[call])+ if len(calls) == 2 and intervene == "redirect":+ assert agent.redirect("actually, do it differently") is True+ raise InterruptedError("redirect cancelled the in-flight request")+ return _mock_response(content="all done", finish_reason="stop")++ if intervene == "steer":+ # Lands while the tool runs; the steer drain absorbs it fully before the next request.+ _DURING_TOOL.append(lambda: agent.steer("also mention the weather"))+ return model_call++[email protected]("intervene", ["steer", "redirect"])+def test_absorbed_correction_still_marks_the_completed_turn(intervene):+ agent = _loop_agent()+ result = _run(agent, _tool_then_reply(agent, intervene))+ assert result["completed"] is True and not result.get("pending_steer")+ assert result["user_intervened"] is True+++def test_next_untouched_turn_starts_clean():+ agent = _loop_agent()+ assert _run(agent, _tool_then_reply(agent, "redirect"))["user_intervened"] is True+ result = _run(agent, lambda api_kwargs: _mock_response(content="hi", finish_reason="stop"), "hello")+ assert result["completed"] is True+ assert result["user_intervened"] is Falsediff --git a/tests/hermes_cli/test_free_tier_offer.py b/tests/hermes_cli/test_free_tier_offer.pynew file mode 100644index 00000000000..4db4fc5d17c--- /dev/null+++ b/tests/hermes_cli/test_free_tier_offer.py@@ -0,0 +1,115 @@+"""The install-wide record behind the free tier's sign-in offer: first due a fixed delay after the first+finished task, then again only after another finished task and never sooner than the back-off since+the previous offer; each due offer is claimable exactly once, and only while the user is on the free+tier."""++from __future__ import annotations++import threading++import pytest++from hermes_cli import anon_auth, free_tier_offer++DELAY = free_tier_offer.OFFER_DELAY_S+BACKOFF = free_tier_offer.REOFFER_AFTER_S+++class _Clock:+ def __init__(self, now: float = 1_000_000.0):+ self.now = now++ def __call__(self) -> float:+ return self.now+++def clock(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "root" / "profiles" / "setup"))+ monkeypatch.setattr(anon_auth, "has_guest", lambda: True)+ monkeypatch.setattr(anon_auth, "guest_enabled", lambda: True)+ fake = _Clock()+ monkeypatch.setattr(free_tier_offer, "_clock", fake)+ return fake+++def _take_due_offer(clock: _Clock) -> None:+ clock.now += free_tier_offer.offer_due_in()+ assert free_tier_offer.claim_offer() is True+++def test_first_offer_is_due_after_the_delay_from_the_first_task_and_later_tasks_do_not_move_it(clock):+ assert free_tier_offer.offer_due_in() is None+ free_tier_offer.record_task_done()+ assert free_tier_offer.offer_due_in() == DELAY+ clock.now += 60+ free_tier_offer.record_task_done()+ assert free_tier_offer.offer_due_in() == DELAY - 60+ clock.now += DELAY+ assert free_tier_offer.offer_due_in() == 0+++def test_claim_is_refused_before_due_then_granted_once(clock):+ free_tier_offer.record_task_done()+ assert free_tier_offer.claim_offer() is False+ clock.now += DELAY+ assert free_tier_offer.claim_offer() is True+ assert free_tier_offer.claim_offer() is False+++def test_no_reoffer_without_a_task_finished_after_the_offer(clock):+ free_tier_offer.record_task_done()+ _take_due_offer(clock)+ clock.now += 10 * BACKOFF[-1] # time alone never brings it back+ assert free_tier_offer.offer_due_in() is None+ assert free_tier_offer.claim_offer() is False++[email protected]("task_after_offer_s,due_in", [+ (60, BACKOFF[0] - 60), # a task soon after the offer: the back-off decides+ (BACKOFF[0], DELAY), # a task after the back-off ran out: the delay after that task decides+], ids=["back-off-bound", "task-bound"])+def test_reoffer_is_the_later_of_task_plus_delay_and_offer_plus_back_off(clock, task_after_offer_s, due_in):+ free_tier_offer.record_task_done()+ _take_due_offer(clock)+ clock.now += task_after_offer_s+ free_tier_offer.record_task_done()+ assert free_tier_offer.offer_due_in() == due_in+++def test_back_off_climbs_the_ladder_then_holds_at_its_last_step(clock):+ free_tier_offer.record_task_done()+ _take_due_offer(clock)+ for backoff in (*BACKOFF, BACKOFF[-1]):+ clock.now += 1 # a task right after the offer: the back-off is the bound+ free_tier_offer.record_task_done()+ assert free_tier_offer.offer_due_in() == backoff - 1+ _take_due_offer(clock)+++def test_concurrent_claims_grant_exactly_one(clock):+ free_tier_offer.record_task_done()+ clock.now += DELAY+ results: list[bool] = []+ threads = [threading.Thread(target=lambda: results.append(free_tier_offer.claim_offer())) for _ in range(8)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()+ assert sorted(results) == [False] * 7 + [True]+++def test_record_is_install_wide_across_profiles(clock, tmp_path, monkeypatch):+ free_tier_offer.record_task_done()+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "root" / "profiles" / "work"))+ assert free_tier_offer.offer_due_in() == DELAY++[email protected]("signed_in,tier_on", [(True, True), (False, False)], ids=["signed-in", "tier-off"])+def test_never_offered_off_the_free_tier(clock, monkeypatch, signed_in, tier_on):+ free_tier_offer.record_task_done()+ clock.now += DELAY+ monkeypatch.setattr(anon_auth, "has_guest", lambda: not signed_in)+ monkeypatch.setattr(anon_auth, "guest_enabled", lambda: tier_on)+ assert free_tier_offer.offer_due_in() is None+ assert free_tier_offer.claim_offer() is Falsediff --git a/tests/tui_gateway/test_free_tier_rpc.py b/tests/tui_gateway/test_free_tier_rpc.pyindex 13c11abfa8d..bbb9287bf34 100644--- a/tests/tui_gateway/test_free_tier_rpc.py+++ b/tests/tui_gateway/test_free_tier_rpc.py@@ -10,7 +10,7 @@ import timeimport pytestimport tui_gateway.server as srv-from hermes_cli import anon_auth+from hermes_cli import anon_auth, free_tier_offerfrom hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store@@ -175,3 +175,28 @@ def test_provision_sets_the_free_tier_up_through_the_lifecycle_primitive(tmp_pat_set_guest_off(monkeypatch)monkeypatch.setattr(anon_auth, "ensure_portal_identity", lambda **kw: (_ for _ in ()).throw(AssertionError("must not run")))assert _call("free_tier.provision") == {"has_guest": False, "enabled": False}+++def test_sign_in_offer_is_reported_then_claimed_once(guest, monkeypatch):+ now = [10_000.0]+ monkeypatch.setattr(free_tier_offer, "_clock", lambda: now[0])+ assert "nudge_due_in" not in _call("free_tier.status")+ assert _call("free_tier.claim_nudge") == {"claimed": False}++ free_tier_offer.record_task_done()+ assert _call("free_tier.status")["nudge_due_in"] == free_tier_offer.OFFER_DELAY_S+ assert _call("free_tier.claim_nudge") == {"claimed": False} # not due yet++ now[0] += free_tier_offer.OFFER_DELAY_S+ assert _call("free_tier.status")["nudge_due_in"] == 0+ assert _call("free_tier.claim_nudge") == {"claimed": True}+ assert _call("free_tier.claim_nudge") == {"claimed": False}+ assert "nudge_due_in" not in _call("free_tier.status") # nothing finished since the offer+++def test_sign_in_offer_is_moot_once_signed_in(guest, monkeypatch):+ monkeypatch.setattr(free_tier_offer, "_clock", lambda: 10_000.0)+ free_tier_offer.record_task_done()+ monkeypatch.setattr(anon_auth, "has_guest", lambda: False)+ assert "nudge_due_in" not in _call("free_tier.status")+ assert _call("free_tier.claim_nudge") == {"claimed": False}diff --git a/tests/tui_gateway/test_free_tier_task_done.py b/tests/tui_gateway/test_free_tier_task_done.pynew file mode 100644index 00000000000..bc72435f916--- /dev/null+++ b/tests/tui_gateway/test_free_tier_task_done.py@@ -0,0 +1,140 @@+"""A finished task on the free tier: a turn that completed on its own with a reply arms the sign-in+offer (``hermes_cli.free_tier_offer``); any user intervention while it ran disqualifies it."""++from __future__ import annotations++import threading+import types++import pytest++import tui_gateway.server as server+from hermes_cli import anon_auth, free_tier_offer+from tui_gateway.free_tier_task_done import note_task_done++CLEAN = {"completed": True, "final_response": "Here is your plan.", "user_intervened": False}++[email protected](autouse=True)+def free_tier(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setattr(anon_auth, "has_guest", lambda: True)+ monkeypatch.setattr(anon_auth, "guest_enabled", lambda: True)+ monkeypatch.setattr(anon_auth, "is_anonymous_agent", lambda agent: getattr(agent, "anonymous", True))+ monkeypatch.setattr(free_tier_offer, "_clock", lambda: 5_000.0)+++def _session(**extra):+ return {"agent": types.SimpleNamespace(anonymous=True), "session_key": "k", "history": [],+ "history_lock": threading.Lock(), "running": True, "attached_images": [], **extra}+++def _recorded() -> bool:+ return free_tier_offer.offer_due_in() is not None+++def test_a_clean_task_arms_the_offer():+ session = _session()+ note_task_done(session, dict(CLEAN), session["agent"], None)+ assert free_tier_offer.offer_due_in() == free_tier_offer.OFFER_DELAY_S++[email protected]("result,anonymous,display_kind,user_input", [+ ({**CLEAN, "completed": False}, True, None, False),+ ({**CLEAN, "final_response": " "}, True, None, False),+ ({**CLEAN, "pending_steer": "and the weather"}, True, None, False),+ ({**CLEAN, "user_intervened": True}, True, None, False),+ (CLEAN, True, None, True),+ (CLEAN, False, None, False),+ (CLEAN, True, "auto_continue", False),+], ids=["not-completed", "empty-reply", "pending-steer", "steered-or-interrupted", "typed-while-busy",+ "own-provider", "crash-resume"])+def test_disqualified_turns_record_nothing(result, anonymous, display_kind, user_input):+ session = _session(**({"_turn_user_input": True} if user_input else {}))+ session["agent"].anonymous = anonymous+ note_task_done(session, dict(result), session["agent"], display_kind)+ assert not _recorded()++[email protected]("method,params", [+ ("session.steer", {"text": "also check my calendar"}),+ ("session.redirect", {"text": "actually only Monday"}),+], ids=["steer", "redirect"])+def test_a_correction_rpc_during_the_task_disqualifies_it(method, params):+ """The session-level mark covers agents whose own flag never reaches this process (compute host)."""+ agent = types.SimpleNamespace(anonymous=True, steer=lambda text: True, redirect=lambda text: True,+ _supports_active_turn_redirect=True)+ server._sessions["sid"] = session = _session(agent=agent)+ try:+ resp = server.handle_request({"id": "1", "method": method, "params": {"session_id": "sid", **params}})+ assert "result" in resp, resp+ note_task_done(session, dict(CLEAN), agent, None)+ finally:+ server._sessions.pop("sid", None)+ assert not _recorded()+++class _ImmediateThread:+ def __init__(self, target=None, daemon=None, **kw):+ self._target = target++ def start(self):+ self._target()++[email protected]("touch,recorded_turns,records_at_each_complete", [+ (None, [1], [1]), ("steer", [], [0]), ("typed", [2], [0, 1]),+], ids=["untouched", "steered-over-rpc", "typed-while-busy"])+def test_prompt_submit_records_only_untouched_turns(monkeypatch, touch, recorded_turns, records_at_each_complete):+ """Typing into a running turn disqualifies that turn; the queued prompt then runs as its own task.+ Each record is written before its turn's message.complete goes out."""+ runs: list[str] = []+ recorded: list[int] = []+ monkeypatch.setattr(free_tier_offer, "record_task_done", lambda: recorded.append(len(runs)))++ class _Agent:+ anonymous = True+ session_id = "k"+ _cached_system_prompt = ""++ def steer(self, text):+ return True++ def run_conversation(self, prompt, **kw):+ runs.append(prompt)+ if touch == "steer":+ server.handle_request({"id": "s", "method": "session.steer",+ "params": {"session_id": "sid", "text": "and my calendar"}})+ if touch == "typed" and len(runs) == 1:+ resp = server.handle_request({"id": "t", "method": "prompt.submit",+ "params": {"session_id": "sid", "text": "and my calendar"}})+ assert resp["result"]["status"] == "queued", resp+ return {"final_response": "Here is your plan.", "completed": True, "user_intervened": False,+ "messages": [{"role": "assistant", "content": "Here is your plan."}]}++ from unittest.mock import MagicMock+ monkeypatch.setattr(server, "_get_db", lambda: MagicMock())+ recorded_at_complete: list[int] = []++ def _emit(event, *a, **kw):+ if event == "message.complete":+ recorded_at_complete.append(len(recorded))+ monkeypatch.setattr(server, "_emit", _emit)+ monkeypatch.setattr(server, "make_stream_renderer", lambda cols: None)+ monkeypatch.setattr(server, "render_message", lambda raw, cols: None)+ monkeypatch.setattr(server, "_sync_session_key_after_compress", lambda *a, **kw: None)+ monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(server, "_load_busy_input_mode", lambda: "queue")+ session = _session(agent=_Agent(), running=False, history_version=0, image_counter=0, cols=80,+ slash_worker=None, show_reasoning=False, tool_progress_mode="all", pending_title=None)+ server._sessions["sid"] = session+ try:+ resp = server.handle_request({"id": "1", "method": "prompt.submit",+ "params": {"session_id": "sid", "text": "Plan my week"}})+ assert "result" in resp, resp+ finally:+ server._sessions.pop("sid", None)+ assert recorded == recorded_turns+ # The desktop re-reads the offer on message.complete, so the record lands before that event.+ assert recorded_at_complete == records_at_each_complete+ assert "_turn_user_input" not in session # per turn: never leaks into the next onediff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.pyindex 30f81c2a098..ba3909445ae 100644--- a/tui_gateway/contracts/config_free_tier_control.py+++ b/tui_gateway/contracts/config_free_tier_control.py@@ -210,6 +210,9 @@ class FreeTierStatusResult(Result):retry_after: int | None = None# A browser challenge the account service is waiting on (``hermes_cli/anon_challenge.py``).challenge: FreeTierChallengePayload | None = None+ # Seconds until the sign-in offer after a finished task is due (0 = due now); absent when none is+ # pending (no finished task since the last offer, or not on the free tier).+ nudge_due_in: int | None = Nonemethod("free_tier.status", params=ProfileParams, result=FreeTierStatusResult,@@ -251,6 +254,14 @@ method("free_tier.ack_notice", params=ProfileParams, result=FreeTierAckNoticeResdoc="Mark the one-time availability notice as shown on the free-tier identity.")+class FreeTierClaimNudgeResult(Result):+ claimed: bool+++method("free_tier.claim_nudge", params=ProfileParams, result=FreeTierClaimNudgeResult,+ doc="Claim the due sign-in offer; true for exactly one caller each time an offer comes due.")++# ── shared metrics consent ────────────────────────────────────────────────────────────────────diff --git a/tui_gateway/free_tier_task_done.py b/tui_gateway/free_tier_task_done.pynew file mode 100644index 00000000000..275e258d40e--- /dev/null+++ b/tui_gateway/free_tier_task_done.py@@ -0,0 +1,37 @@+"""Detects a task finishing on its own on the free tier, which (re)arms the sign-in offer+(``hermes_cli.free_tier_offer``).++"On its own" = the turn completed with a reply, on the free tier, and nobody steered, redirected,+interrupted or typed into it while it ran. Answering a clarify card is not intervention: it is the+reply to a server request, which touches none of those paths. A crash resume is not a new task.+"""++from __future__ import annotations++import logging+from typing import Any++logger = logging.getLogger(__name__)+++def is_clean_task(result: Any, agent: Any, *, user_input: bool, display_kind: str | None) -> bool:+ from hermes_cli.anon_auth import is_anonymous_agent+ if display_kind == "auto_continue" or user_input:+ return False+ if not isinstance(result, dict) or not result.get("completed"):+ return False+ if result.get("pending_steer") or result.get("user_intervened"):+ return False+ if not str(result.get("final_response") or "").strip():+ return False+ return is_anonymous_agent(agent)+++def note_task_done(session: dict, result: Any, agent: Any, display_kind: str | None) -> None:+ """Record a clean free-tier task for the sign-in offer. Never fails the turn."""+ try:+ if is_clean_task(result, agent, user_input=bool(session.get("_turn_user_input")), display_kind=display_kind):+ from hermes_cli.free_tier_offer import record_task_done+ record_task_done()+ except Exception:+ logger.debug("sign-in offer task record failed", exc_info=True)diff --git a/tui_gateway/methods_free_tier.py b/tui_gateway/methods_free_tier.pyindex 8dcab19070c..10e6b77bd69 100644--- a/tui_gateway/methods_free_tier.py+++ b/tui_gateway/methods_free_tier.py@@ -25,6 +25,8 @@ def _(rid, params: dict) -> dict:when nothing else carries inference) is there for this install. Whether inference actually runson it is a ROUTE question answered by ``setup.runtime_check.free_tier``, never by this flag.``notice_pending`` is true until ``free_tier.ack_notice`` ran for this identity.+ ``nudge_due_in``: seconds until the sign-in offer after a finished task is due (install-wide,+ ``hermes_cli.free_tier_offer``); absent when none is pending.A pure read. The identity is created by the boot bootstrap (``free_tier_bootstrap``), never asa side effect of a client polling this method (NS-845 Q1.2)."""@@ -36,6 +38,9 @@ def _(rid, params: dict) -> dict:"has_guest": has_guest, "enabled": enabled, "available": has_guest and enabled,"notice_pending": bool(has_guest and enabled and anon_auth.guest_notice_pending()),"model": anon_auth.GUEST_MODEL, "label": anon_auth.FREE_TIER_LABEL}+ from hermes_cli import free_tier_offer+ if (nudge_due_in := free_tier_offer.offer_due_in()) is not None:+ payload["nudge_due_in"] = nudge_due_inif enabled and not has_guest:# Why there is no identity, when the last attempt to make one failed:# ``{error, error_code, retryable, retry_after}`` (the mint memo's verdict).@@ -95,6 +100,19 @@ def _(rid, params: dict) -> dict:return _err(rid, 5091, str(e))+@method("free_tier.claim_nudge")+@_profile_scoped+def _(rid, params: dict) -> dict:+ """Claim the due sign-in offer. Claim before showing, so two windows never both show it:+ ``claimed`` is true for exactly one caller each time an offer comes due."""+ try:+ from hermes_cli import free_tier_offer+ return _ok(rid, {"claimed": bool(free_tier_offer.claim_offer())})+ except Exception as e: # the RPC boundary: report it, never crash the dispatcher+ logger.warning("free_tier.claim_nudge failed", exc_info=True)+ return _err(rid, 5093, str(e))++@method("free_tier.challenge_result")@_profile_scopeddef _(rid, params: dict) -> dict:diff --git a/tui_gateway/methods_session_interrupt.py b/tui_gateway/methods_session_interrupt.pyindex 737dbfd5e7a..6cedbcff1e5 100644--- a/tui_gateway/methods_session_interrupt.py+++ b/tui_gateway/methods_session_interrupt.py@@ -30,6 +30,14 @@ def _resume_wake_after_interrupt() -> None:# ── interrupt / steer / redirect ─────────────────────────────────────+def _note_user_input(session: dict) -> None:+ """Mark the running turn as touched by the user (also covers compute-host turns, whose agent+ flag never reaches this process); popped by the turn's own finally."""+ with session["history_lock"]:+ if session.get("running"):+ session["_turn_user_input"] = True++@method("session.interrupt")def _(rid, params: dict) -> dict:_tts_stream_stop() # keypress barge-in also silences streaming TTS (voice is process-global)@@ -45,6 +53,7 @@ def _(rid, params: dict) -> dict:resume_wake = Falsereturn _ok(rid, {"status": "not_interrupted", "interrupted": False})sid = str(params.get("session_id") or "")+ _note_user_input(session)if _session_uses_compute_host(session):try:_interrupt_session_turn(sid, session, request_id=f"interrupt-{rid}")@@ -99,6 +108,7 @@ def _correction_method(name: str, verb: str, accepted_status: str, supported, unsession, err = _sess_nowait(params, rid)if err:return err+ _note_user_input(session)agent = session.get("agent")# Redirect during the turn-build window (running=True, agent None): queue for the next turn instead of# a misleading 4010 the client swallows into a lost follow-up.diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.pyindex 8a4b2731ab1..33d3f3b01e4 100644--- a/tui_gateway/prompt_turn.py+++ b/tui_gateway/prompt_turn.py@@ -1186,6 +1186,10 @@ def _run_prompt_submit(status_note = _absorb_turn_result(sid, session, st, text, display_kind, display_metadata)payload, raw, status = _complete_turn_payload(session, st, status_note, cols)+ if status == "complete":+ # Before message.complete: the desktop re-reads the sign-in offer on that event.+ from tui_gateway.free_tier_task_done import note_task_done+ note_task_done(session, st.result, st.agent, display_kind)_emit("message.complete", sid, payload)goal_followup = _goal_followup_after_turn(sid, session, st.result, status, raw)if status == "complete":@@ -1205,6 +1209,7 @@ def _run_prompt_submit(with session["history_lock"]:session["running"] = Falsesession["last_active"] = time.time()+ session.pop("_turn_user_input", None) # per turn: never leaks into the next oneif not st.error_retained:_clear_inflight_turn(session)_release_hosted_room_turn_slot(session)diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.pyindex 54e4c7cf47f..1b908464c08 100644--- a/tui_gateway/session_auto_continue.py+++ b/tui_gateway/session_auto_continue.py@@ -417,6 +417,8 @@ def _handle_busy_submit(rid, sid: str, session: dict, text: Any, transport: Any,with session["history_lock"]:if not session.get("running"):return None # turn ended since prompt.submit's busy check; caller retries on the idle session+ # Typed while the turn ran, in any busy mode: the running turn no longer counts as unattended.+ session["_turn_user_input"] = Trueimage_paths = list(session.get("attached_images", []))if image_paths:session["attached_images"] = [] # claim now so a later paste isn't consumed when the turn yields