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
2 changes: 2 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,7 @@ class ChatRequest(BaseModel):
choice_cards: bool = False # the page can show a choice card (one question, a few options) and report the answer (POST /api/chat/choice/{id}), so the tool loop may ask and wait (backend/services/choice_cards.py)
change_cards: bool = False # the page can show a calendar-change card (Apply / Decline) and report the press (POST /api/chat/change/{id}/decision), so the tool loop may propose a change and wait (backend/services/change_cards.py)
runner_cards: bool = False # the page can show a local-runner check card (Run / Cancel), so the run_local_check tool may be offered (backend/utils/runner_jobs.py)
runner_id: Optional[str] = Field(default=None, max_length=64) # the computer the person picked in the Connection card's "Runner for checks"; the checks go only to it (no fallback). None: the server picks, as before
reply_model: Optional[str] = None # the shared guest's base-model choice ("gemini", "lite" or "auto"), kept in their browser because the guests share one settings record; honoured for the guest only (backend/utils/user_settings_utils.py reply_choice_for_turn)
demo_project: Optional[bool] = None # the shared guest chose a demo card, so this turn works on the server's demo project (backend/utils/demo_project.py); ignored for anyone else
folder_expected: Optional[bool] = None # the browser has a local folder connected (and may write to it), so a turn that finds none on the server can say so (the answer then used GitHub), and so an edit is only proposed where it can be applied. None: an older page that does not say
Expand Down Expand Up @@ -975,6 +976,7 @@ async def secure_chat(request: ChatRequest, http_request: Request, current_user
"edit_decisions": bool(request.edit_decisions),
"code_followup": code_followup,
"runner_cards": bool(request.runner_cards),
"runner_id": (request.runner_id or "").strip() or None, # set every turn, so a choice they cleared does not stay in the conversation's state
"choice_cards": bool(request.choice_cards),
"change_cards": bool(request.change_cards),
"demo_project": demo_turn,
Expand Down
14 changes: 14 additions & 0 deletions backend/components/sonic_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -2140,4 +2140,18 @@
"keywords": ["promise", "remind", "check on", "always be there", "honest"],
"volunteer": [],
},
{
"id": "choose_the_runner",
"requires": [
"backend/utils/runner_jobs.py::def chosen_runner_problem",
"app.py::request.runner_id",
],
"month": "2026-11",
"title": "Choosing which computer",
"line": (
"With the runner on more than one computer, you can now pick which one my checks go to under Connection, and pair another there. When the one you picked can't take a check, no other computer is used."
),
"keywords": ["runner", "computer", "choose", "switch", "pair"],
"volunteer": [],
},
]
12 changes: 9 additions & 3 deletions backend/services/agent_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -3271,11 +3271,16 @@ def _run_snippet(code: str, branch: str = None):
# A runner on the person's own machine (backend/utils/runner_jobs.py, runner/): offered only when the page can show its card, the person is signed in, and exactly one runner of theirs is
# connected (or one is in the folder they connected). The menu names the checks it has, so the model asks for one by name; it never supplies a command.
runner_for_checks = None
runner_note = "" # said with the request when the computer they picked can take nothing: without it the runner tools are just missing and the reply cannot say why
if state.get("runner_cards") and not is_guest_username(username) and get_db() is not None:
try:
runner_for_checks = await asyncio.to_thread(
runner_jobs.connected_runner, get_db(), username, workspace_status(username).get("name", "") if local_workspace_handle is not None else ""
)
chosen_runner = state.get("runner_id") or None
runner_folder = workspace_status(username).get("name", "") if local_workspace_handle is not None else ""
runner_for_checks = await asyncio.to_thread(runner_jobs.connected_runner, get_db(), username, runner_folder, None, chosen_runner)
if runner_for_checks is None and chosen_runner:
problem = await asyncio.to_thread(runner_jobs.chosen_runner_problem, get_db(), username, runner_folder, chosen_runner)
runner_note = (f"\n\nTHEIR RUNNER: {problem} Nothing can run on their own machine in this turn, and no other computer of theirs is used instead. If the request needs a check or a command "
"on their machine, say this plainly, and that they can start that computer, add the project to it, or choose another under Connection, Runner for checks. Otherwise do not mention it.")
except Exception:
logger.warning("[tool_agent_node] could not look for a connected runner.", exc_info=True)
if runner_for_checks is not None and runner_jobs.runnable_checks(runner_for_checks):
Expand Down Expand Up @@ -4671,6 +4676,7 @@ async def _announce_step(title, detail, step_id, tool=None, subject=None, last_s
try:
loop_result = await _native_engine(
question=msg + (f"\n\n{code_plan.PLAN_RULES}" if plan_phase == code_plan.PLAN_PHASE else "") + (await _plan_files_block() if plan_phase == code_plan.EXECUTE_PHASE else "")
+ runner_note
+ _care_pause_note(msg, state), # cancelling therapy or other care while low: one gentle question first (backend/utils/goal_guard.py)
schema=schema,
act=_counted_act,
Expand Down
1 change: 1 addition & 0 deletions backend/state/graph_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ class GraphState(TypedDict):
choice_cards: Optional[bool] # the page can show a choice card and report the answer (POST /api/chat/choice/{id}), so the ask_choice tool may be offered (backend/services/choice_cards.py)
change_cards: Optional[bool] # the page can show a calendar-change card (Apply / Decline) and report the press (POST /api/chat/change/{id}/decision), so propose_calendar_change may be offered (backend/services/change_cards.py)
runner_cards: Optional[bool] # the page can show a local-runner check card (Run / Cancel), so the run_local_check tool may be offered (backend/utils/runner_jobs.py)
runner_id: Optional[str] # the computer they picked for checks (ChatRequest.runner_id); None: the server picks (runner_jobs.connected_runner)
tool_model: Optional[str] # "claude" | "sonnet" | "gpt" | "gemini": the person's choice for the tool agent's reasoning steps; None = the server's default
reply_model: Optional[str] # "gemini" | "gpt" | "lite" | "haiku" | "auto": the person's base-model setting this turn; the reasoner runs on Haiku for "haiku" only (models.reasoner_llm_for)
execute_model: Optional[str] # "claude" | "sonnet" | "gpt" | "gemini": the person's choice for the model that carries out an approved plan; None = the same as their Code model
Expand Down
16 changes: 16 additions & 0 deletions backend/tests/test_after_edit_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,22 @@ async def test_a_pass_is_counted_as_a_run_not_a_failure(monkeypatch):
assert not any("code_after_edit_check_failed" in c for c in asked["counts"])


@run_async
async def test_after_edit_check_uses_the_chosen_runner(monkeypatch):
_connect_folder()
_runner(monkeypatch, True, PASSED_RUN)
picked = []
view = {"id": "r2", "name": "desktop", "root_name": "local-rag", "project_id": PID, "checks": [PYTEST], "settings": {"disabled": [], "fake_keys": True, "after_edit_auto": True}}

def chosen(db, username, root, now, runner_id=None):
picked.append(runner_id)
return view if runner_id == "r2" else None

monkeypatch.setattr(aw.runner_jobs, "connected_runner", chosen)
await _drive(monkeypatch, lambda pid: led.decide("jack", pid, "applied"), state_extra={"runner_cards": True, "runner_id": "r2"})
assert picked and all(choice == "r2" for choice in picked)


@run_async
async def test_a_run_that_did_not_finish_is_not_counted_as_failed(monkeypatch):
_connect_folder()
Expand Down
4 changes: 3 additions & 1 deletion backend/tests/test_run_local_check_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def play():
return thread


async def drive(monkeypatch, decisions, *, db=None, runner_cards=True, username="jack", engine="native"):
async def drive(monkeypatch, decisions, *, db=None, runner_cards=True, username="jack", engine="native", state_extra=None):
"""Runs tool_agent_node with the loop replaced by one that calls the tool and records what it returned, the events it emitted and what it offered."""
from backend.tests.test_tool_agent_node import _setup_github_repo, _state

Expand All @@ -68,11 +68,13 @@ async def fake_run(**kwargs):
seen["observations"].append(await kwargs["act"](decision))
seen["prompt"] = kwargs.get("prompt_template") or legacy_loop.menu_of(kwargs.get("tools"))
seen["tools"] = [t["name"] for t in (kwargs.get("tools") or [])]
seen["question"] = kwargs.get("question") or ""
return {"final_answer": "done", "attempts": [], "show_work": False}

monkeypatch.setattr(aw.native_loop, "run", fake_run)
state = _state("run the tests for me", username=username)
state["runner_cards"] = runner_cards
state.update(state_extra or {})
await aw.tool_agent_node(state)
seen["events"] = [(c.args[0], c.args[1]) for c in emit.call_args_list]
return seen
Expand Down
125 changes: 125 additions & 0 deletions backend/tests/test_runner_choice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
"""The computer a person picks for checks (Connection panel, "Runner for checks"): it travels from the chat request through the graph to the tool agent, checks go to that computer only, and when it
can take nothing Sonic is told why. Fake database; no model, no network."""
import pytest
from langgraph.graph import END, START, StateGraph

from backend.state.graph_state import GraphState
from backend.tests.fake_runner_db import FakeDB
from backend.tests.test_run_local_check_tool import CHECKS, call, drive, run
from backend.tests.test_support_card_turn import Graph, app_module, turn, world # noqa: F401 (world is a fixture)
from backend.utils import runner_jobs as rj

USER = "jack"


def computer(db, name, root="demo", username=USER):
"""A paired computer of this person. With a `root` it has said hello with that project; without one it has never connected."""
code = rj.create_pairing(db, username, name)["code"]
made = rj.exchange_pairing(db, code)
record = rj.authenticate(db, made["key"])
if root:
rj.hello(db, record, {"version": "0.1.0", "root_name": root, "checks": CHECKS})
return record["_id"]


# ---- the choice reaches the tool agent ----------------------------------------------------------------------------------------------------------

def test_the_graph_keeps_the_choice_for_its_nodes():
"""LangGraph silently drops an input key the state does not declare, which is how a choice sent by the page could vanish before any node saw it."""
seen = {}

def node(state):
seen["runner_id"] = state.get("runner_id")
return {}

graph = StateGraph(GraphState)
graph.add_node("look", node)
graph.add_edge(START, "look")
graph.add_edge("look", END)
graph.compile().invoke({"messages": [], "username": USER, "runner_id": "r2"})
assert seen == {"runner_id": "r2"}


@pytest.mark.parametrize("sent, expected", [({"runner_id": "r2"}, "r2"), ({}, None), ({"runner_id": " "}, None)])
def test_the_chat_request_puts_the_choice_in_the_turns_state_every_time(world, monkeypatch, sent, expected): # noqa: F811
states = []

class Keeping(Graph):
async def astream_events(self, state, version, config):
states.append(dict(state))
async for event in super().astream_events(state, version, config):
yield event

monkeypatch.setitem(app_module.services, "compiled_workflow", Keeping())
monkeypatch.setattr(app_module.support_choice_utils, "should_offer", lambda *a, **k: False)
run(turn("run the tests", **sent))
assert "runner_id" in states[0] and states[0]["runner_id"] == expected # present even when empty, so an old choice cannot linger in the conversation's saved state


# ---- checks go to that computer only ------------------------------------------------------------------------------------------------------------

def test_with_two_computers_in_the_folder_the_chosen_one_gets_the_check(monkeypatch):
db = FakeDB()
computer(db, "laptop")
desktop = computer(db, "desktop")
monkeypatch.setattr(rj, "WAIT_SECONDS", 0.3)
seen = run(drive(monkeypatch, [call("tests")], db=db, state_extra={"runner_id": desktop}))
assert [job["runner_id"] for job in db[rj.JOBS].find({})] == [desktop]
assert "THEIR RUNNER" not in seen["question"]


def test_with_two_computers_and_no_choice_no_check_is_offered_and_nothing_is_said(monkeypatch):
db = FakeDB()
computer(db, "laptop")
computer(db, "desktop")
seen = run(drive(monkeypatch, [], db=db))
assert "run_local_check" not in seen["tools"] and "THEIR RUNNER" not in seen["question"]


def test_a_chosen_computer_that_is_off_is_not_replaced_and_sonic_is_told(monkeypatch):
db = FakeDB()
computer(db, "laptop") # connected, and would be used with no choice
tablet = computer(db, "tablet", root=None) # paired, never connected
seen = run(drive(monkeypatch, [call("tests")], db=db, state_extra={"runner_id": tablet}))
assert "run_local_check" not in seen["tools"] and not db[rj.JOBS].find({})
assert 'THEIR RUNNER: The computer they picked for checks, "tablet", is not connected.' in seen["question"]
assert "no other computer of theirs is used instead" in seen["question"]
assert seen["question"].startswith("run the tests for me") # their words stay first


def test_the_note_is_left_out_where_the_page_cannot_run_checks_anyway(monkeypatch):
db = FakeDB()
tablet = computer(db, "tablet", root=None)
seen = run(drive(monkeypatch, [], db=db, runner_cards=False, state_extra={"runner_id": tablet}))
assert "THEIR RUNNER" not in seen["question"]


# ---- why the chosen computer can take nothing ---------------------------------------------------------------------------------------------------

def test_each_reason_is_named():
db = FakeDB()
off = computer(db, "tablet", root=None)
other = computer(db, "laptop", root="other-project")
theirs = computer(db, "stranger", username="someone-else")
why = lambda runner_id, folder="demo": rj.chosen_runner_problem(db, USER, folder, runner_id)
assert why(off).endswith('"tablet", is not connected.')
assert why(other).endswith('"laptop", has no single project named "demo".')
assert why(other, "").endswith('"laptop", serves more than one project and no folder is connected to say which.')
assert why("gone") == "The computer they picked for checks is no longer one of their runners."
assert why(theirs) == why("gone") and "stranger" not in why(theirs) # another person's computer is never described

rj.hello(db, rj.authenticate(db, _key_of(db, "bare")), {"version": "0.1.0", "projects": []})
assert why(_id_of(db, "bare")).endswith('"bare", has no project added.')


_BARE = {}


def _key_of(db, name):
made = rj.exchange_pairing(db, rj.create_pairing(db, USER, name)["code"])
_BARE[name] = made["key_id"]
return made["key"]


def _id_of(db, name):
return _BARE[name]
24 changes: 24 additions & 0 deletions backend/tests/test_runner_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,30 @@ def test_the_runner_a_job_goes_to_is_the_one_in_that_folder_or_the_only_one():
assert second["_id"] != first["_id"]


def test_connected_runner_with_a_chosen_id_returns_only_that_runner():
db = FakeDB()
first, _ = connected(db, name="laptop", root="saapp")
second, _ = connected(db, name="desktop", root="saapp")
view = rj.connected_runner(db, "jack@example.com", "saapp", NOW, runner_id=second["_id"])
assert view is not None and view["id"] == second["_id"] and view["id"] != first["_id"]
assert rj.connected_runner(db, "jack@example.com", "saapp", NOW) is None # two match and none is chosen: the card has to ask


def test_connected_runner_refuses_a_chosen_runner_that_is_not_connected():
db = FakeDB()
key = paired(db, name="tablet")
asleep = rj.authenticate(db, key["key"]) # paired, never said hello: not connected
connected(db, name="desktop", root="saapp")
assert rj.connected_runner(db, "jack@example.com", "saapp", NOW, runner_id=asleep["_id"]) is None # no fallback to the other runner


def test_connected_runner_refuses_another_persons_runner():
db = FakeDB()
theirs, _ = connected(db, username="someone@else.com", name="laptop", root="saapp")
connected(db, name="desktop", root="saapp")
assert rj.connected_runner(db, "jack@example.com", "saapp", NOW, runner_id=theirs["_id"]) is None


# ---- jobs ------------------------------------------------------------------------------------------------------------------------------------

def test_a_job_can_only_be_asked_of_a_connected_runner_for_a_check_it_has_with_plain_files_and_one_at_a_time():
Expand Down
23 changes: 21 additions & 2 deletions backend/utils/runner_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -602,10 +602,13 @@ def runners_for(db: Any, username: str, now: Optional[datetime] = None) -> List[
return [public_runner(key, db[RUNNERS].find_one({"_id": key["_id"]}) or {}, now) for key in _active_keys(db, username)]


def connected_runner(db: Any, username: str, folder_name: str = "", now: Optional[datetime] = None) -> Optional[Dict[str, Any]]:
def connected_runner(db: Any, username: str, folder_name: str = "", now: Optional[datetime] = None, runner_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
"""The connected runner's project a check should go to, as a `runner_view`: the project named like the folder connected in chat (`folder_name`); failing that, the only project of the only connected
runner. None when none is connected or more than one could be meant (the card has to ask). Blocking."""
runner. None when none is connected or more than one could be meant (the card has to ask). With `runner_id` (the computer the person picked), only that runner is considered, and None when it is not
connected: no fallback to another computer. Blocking."""
live = [r for r in runners_for(db, username, now) if r["connected"]]
if runner_id:
live = [r for r in live if r["id"] == runner_id]
named = [(r, p) for r in live for p in r["projects"] if folder_name and p["name"].lower() == folder_name.lower()]
if len(named) == 1:
return runner_view(*named[0])
Expand All @@ -614,6 +617,22 @@ def connected_runner(db: Any, username: str, folder_name: str = "", now: Optiona
return None


def chosen_runner_problem(db: Any, username: str, folder_name: str, runner_id: str, now: Optional[datetime] = None) -> str:
"""Why the computer the person picked has nothing a check could go to (`connected_runner` returned None for it), as one sentence for Sonic. Only their own runners are looked at, so another
person's id reads as one that is gone. Blocking."""
chosen = next((r for r in runners_for(db, username, now) if r["id"] == runner_id), None)
if chosen is None:
return "The computer they picked for checks is no longer one of their runners."
name = chosen["name"]
if not chosen["connected"]:
return f'The computer they picked for checks, "{name}", is not connected.'
if not chosen["projects"]:
return f'The computer they picked for checks, "{name}", has no project added.'
if folder_name:
return f'The computer they picked for checks, "{name}", has no single project named "{folder_name}".'
return f'The computer they picked for checks, "{name}", serves more than one project and no folder is connected to say which.'


# ---------------------------------------------------------------------------------------------------------------
# Jobs
# ---------------------------------------------------------------------------------------------------------------
Expand Down
Loading
Loading