From e8e1458f9581d5b86bfc75c858a38055c20fea34 Mon Sep 17 00:00:00 2001 From: jack Date: Sun, 29 Nov 2026 19:29:52 -0600 Subject: [PATCH] feat: add runner pairing setup, runner pick and runner project choice Co-authored-by: Sonic Assistant --- app.py | 2 + backend/components/sonic_changelog.py | 14 ++ backend/services/agent_workflow.py | 12 +- backend/state/graph_state.py | 1 + backend/tests/test_after_edit_check.py | 16 +++ backend/tests/test_run_local_check_tool.py | 4 +- backend/tests/test_runner_choice.py | 125 ++++++++++++++++++ backend/tests/test_runner_jobs.py | 24 ++++ backend/utils/runner_jobs.py | 23 +++- local/src/api.ts | 5 +- local/src/components/RunnerPairingSetup.tsx | 95 +++++++++++++ local/src/components/RunnerSettingsCard.tsx | 76 +---------- local/src/components/SessionColumn.tsx | 68 ++++++++-- local/src/components/SessionRail.tsx | 5 +- .../components/__styles__/SessionColumn.css | 16 +++ local/src/components/folderCard.test.mjs | 91 ++++++++++++- local/src/components/helpTips.ts | 2 + local/src/components/runnerNudge.test.mjs | 2 +- local/src/components/runnerPairing.test.mjs | 98 ++++++++++++++ local/src/components/runnerPairing.ts | 54 ++++++++ local/src/components/runnerPick.test.mjs | 79 +++++++++++ local/src/components/runnerPick.ts | 47 +++++++ .../components/runnerProjectOffer.test.mjs | 11 +- local/src/components/sessionColumnLogic.ts | 30 +++-- local/src/components/terminalCard.test.mjs | 4 +- local/src/components/terminalLogic.ts | 5 +- local/src/hooks/useRunnerPick.ts | 14 ++ local/src/hooks/useRunnerPing.ts | 7 +- local/src/pages/Chat.tsx | 18 ++- local/src/runnerLogic.test.mjs | 2 +- local/src/sessionColumn.test.mjs | 2 +- local/src/welcomeCards.test.mjs | 2 +- 32 files changed, 836 insertions(+), 118 deletions(-) create mode 100644 backend/tests/test_runner_choice.py create mode 100644 local/src/components/RunnerPairingSetup.tsx create mode 100644 local/src/components/runnerPairing.test.mjs create mode 100644 local/src/components/runnerPairing.ts create mode 100644 local/src/components/runnerPick.test.mjs create mode 100644 local/src/components/runnerPick.ts create mode 100644 local/src/hooks/useRunnerPick.ts diff --git a/app.py b/app.py index 93c3eec3..13175801 100644 --- a/app.py +++ b/app.py @@ -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 @@ -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, diff --git a/backend/components/sonic_changelog.py b/backend/components/sonic_changelog.py index 4bec2e7c..cec1aa3c 100644 --- a/backend/components/sonic_changelog.py +++ b/backend/components/sonic_changelog.py @@ -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": [], + }, ] diff --git a/backend/services/agent_workflow.py b/backend/services/agent_workflow.py index b3c22c01..03883168 100644 --- a/backend/services/agent_workflow.py +++ b/backend/services/agent_workflow.py @@ -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): @@ -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, diff --git a/backend/state/graph_state.py b/backend/state/graph_state.py index 7a8229f5..a9d6b7d8 100644 --- a/backend/state/graph_state.py +++ b/backend/state/graph_state.py @@ -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 diff --git a/backend/tests/test_after_edit_check.py b/backend/tests/test_after_edit_check.py index 3e251fd7..26c9bfee 100644 --- a/backend/tests/test_after_edit_check.py +++ b/backend/tests/test_after_edit_check.py @@ -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() diff --git a/backend/tests/test_run_local_check_tool.py b/backend/tests/test_run_local_check_tool.py index 9e09aef4..1b1c118e 100644 --- a/backend/tests/test_run_local_check_tool.py +++ b/backend/tests/test_run_local_check_tool.py @@ -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 @@ -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 diff --git a/backend/tests/test_runner_choice.py b/backend/tests/test_runner_choice.py new file mode 100644 index 00000000..6a72afcd --- /dev/null +++ b/backend/tests/test_runner_choice.py @@ -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] diff --git a/backend/tests/test_runner_jobs.py b/backend/tests/test_runner_jobs.py index a3768ec4..af5d13ef 100644 --- a/backend/tests/test_runner_jobs.py +++ b/backend/tests/test_runner_jobs.py @@ -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(): diff --git a/backend/utils/runner_jobs.py b/backend/utils/runner_jobs.py index 1e6a1b2a..df789d9d 100644 --- a/backend/utils/runner_jobs.py +++ b/backend/utils/runner_jobs.py @@ -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]) @@ -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 # --------------------------------------------------------------------------------------------------------------- diff --git a/local/src/api.ts b/local/src/api.ts index 80970051..6738d42c 100644 --- a/local/src/api.ts +++ b/local/src/api.ts @@ -2665,7 +2665,8 @@ export async function sendChatMessage( runnerCards = false, demoProject = false, guestReplyModel: ReplyModel | null = null, - supportChoice: string | null = null + supportChoice: string | null = null, + runnerId: string | null = null ): Promise { const authHeaders = await getAuthHeaders(); // A deliberate Stop surfaces as an AbortError and is the caller's to handle; every other failure is a ChatSendError that says what is @@ -2703,6 +2704,8 @@ export async function sendChatMessage( reply_model: guestReplyModel, // This message is a tap on the support card (just listen / advice / help fixing it): which option it was (backend/utils/support_choice.py). Null for an ordinary message. support_choice: supportChoice, + // The computer picked for checks (components/runnerPick.ts): they go to it only. Null: the server picks. + runner_id: runnerId, }), signal, }); diff --git a/local/src/components/RunnerPairingSetup.tsx b/local/src/components/RunnerPairingSetup.tsx new file mode 100644 index 00000000..a01d3881 --- /dev/null +++ b/local/src/components/RunnerPairingSetup.tsx @@ -0,0 +1,95 @@ +import { useState } from 'react'; +import type { RunnerPairing, RunnerScript } from '../api'; +import { OS_LABEL, detectOs, minutesLeft, runHint, type OsKind } from '../runnerLogic'; +import './__styles__/RunnerSettingsCard.css'; + +function download(script: RunnerScript): void { + const url = URL.createObjectURL(new Blob([script.text], { type: 'text/plain' })); + const link = document.createElement('a'); + link.href = url; + link.download = script.filename; + document.body.appendChild(link); + link.click(); + link.remove(); + window.setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +interface Props { + pairing: RunnerPairing; + /** The caller's clock, so the minutes left keep moving. */ + now: number; + onDone: () => void; + /** Said once the code has expired, and beside Done: both depend on where this is shown. */ + expiredText: string; + doneHint: string; + /** Extra class for a narrower place (the Connection panel). */ + className?: string; +} + +/** + * What to do with a one-time pairing code: the code with Copy and the minutes left, the setup file for each system, the same setup as commands, and what to type for a runner already installed. + * Settings (components/RunnerSettingsCard.tsx) and the Connection panel (components/SessionColumn.tsx) both show this one. + */ +export default function RunnerPairingSetup({ pairing, now, onDone, expiredText, doneHint, className }: Props) { + const [os, setOs] = useState(() => detectOs(typeof navigator === 'undefined' ? '' : navigator.platform || '', typeof navigator === 'undefined' ? '' : navigator.userAgent)); + const [copied, setCopied] = useState(''); + const scripts = pairing.scripts ?? null; + const left = minutesLeft(pairing.expires_at, now); + + const copy = async (what: string, text: string) => { + try { + await navigator.clipboard.writeText(text); + setCopied(what); + window.setTimeout(() => setCopied(''), 2000); + } catch { + setCopied(''); + } + }; + + return ( +
+
+ Your one-time code + {pairing.code} + +
+
{left > 0 ? `It works once, for about ${left} more minute${left === 1 ? '' : 's'}.` : expiredText}
+ + {scripts ? ( + <> +
+ + Other systems: + {(Object.keys(OS_LABEL) as OsKind[]).filter(kind => kind !== os).map(kind => ( + + ))} +
+

{runHint(os, scripts[os].filename)}

+
+ View the script before you run it +
{scripts[os].text}
+
+

The script carries only this one-time code, never a key. It asks before it does anything, installs nothing system-wide, and makes a private environment in your home folder.

+ + ) : ( +

+ {pairing.install_problem || 'The install address could not be built, so there is no starter script to download.'}{' '} + If you installed the runner yourself, pair this computer with this code: saapp-runner pair --server {window.location.origin} {pairing.code} +

+ )} + + {pairing.commands && ( +
+ Prefer to type it? The same setup as commands +
{pairing.commands.join('\n')}
+ +
+ )} + +
+ + {doneHint} +
+
+ ); +} diff --git a/local/src/components/RunnerSettingsCard.tsx b/local/src/components/RunnerSettingsCard.tsx index 9bb71400..3f990928 100644 --- a/local/src/components/RunnerSettingsCard.tsx +++ b/local/src/components/RunnerSettingsCard.tsx @@ -1,21 +1,11 @@ import { useCallback, useEffect, useState } from 'react'; -import { api, disconnectLocalWorkspace, getLocalWorkspaceStatus, type LocalWorkspaceStatus, type ProjectSettings, type RunnerInfo, type RunnerList, type RunnerPairing, type RunnerProject, type RunnerScript } from '../api'; -import { OS_LABEL, browserLine, canShareFiles, checkIsOn, detectOs, launchHint, minutesLeft, noChecksLine, notConnectedReason, requestSentence, requestsOpen, requestsToShow, runnerCanShareFiles, sharingLine, runHint, statusSentence, updateNote, withAutoUpdate, withCheck, withAfterEditAuto, withFakeKeys, withReadOnlyAuto, type OsKind } from '../runnerLogic'; +import { api, disconnectLocalWorkspace, getLocalWorkspaceStatus, type LocalWorkspaceStatus, type ProjectSettings, type RunnerInfo, type RunnerList, type RunnerPairing, type RunnerProject } from '../api'; +import { browserLine, canShareFiles, checkIsOn, launchHint, noChecksLine, notConnectedReason, requestSentence, requestsOpen, requestsToShow, runnerCanShareFiles, sharingLine, statusSentence, updateNote, withAutoUpdate, withCheck, withAfterEditAuto, withFakeKeys, withReadOnlyAuto } from '../runnerLogic'; +import RunnerPairingSetup from './RunnerPairingSetup'; import './__styles__/RunnerSettingsCard.css'; const POLL_WHILE_PAIRING_MS = 4000; -function download(script: RunnerScript): void { - const url = URL.createObjectURL(new Blob([script.text], { type: 'text/plain' })); - const link = document.createElement('a'); - link.href = url; - link.download = script.filename; - document.body.appendChild(link); - link.click(); - link.remove(); - window.setTimeout(() => URL.revokeObjectURL(url), 1000); -} - /** * Asks for a project to be added to one of the person's computers. Only the folder's NAME goes to SAAPP; the runner then shows a window on that computer where the person chooses the folder (or says no). */ @@ -53,10 +43,8 @@ export default function RunnerSettingsCard() { const [list, setList] = useState(null); const [pairing, setPairing] = useState(null); const [name, setName] = useState(''); - const [os, setOs] = useState(() => detectOs(typeof navigator === 'undefined' ? '' : navigator.platform || '', typeof navigator === 'undefined' ? '' : navigator.userAgent)); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); - const [copied, setCopied] = useState(''); const [now, setNow] = useState(() => Date.now()); const [saving, setSaving] = useState(''); // Where Sonic's copy of the folder came from (the browser's open folder, or this person's runner on their say-so): a project whose files a runner sent shows "Sonic is reading N files" and a Stop sharing button. @@ -221,19 +209,7 @@ export default function RunnerSettingsCard() { } }; - const copy = async (what: string, text: string) => { - try { - await navigator.clipboard.writeText(text); - setCopied(what); - window.setTimeout(() => setCopied(''), 2000); - } catch { - setCopied(''); - } - }; - const atLimit = !!list && list.runners.length >= list.limit; - const scripts = pairing?.scripts ?? null; - const left = pairing ? minutesLeft(pairing.expires_at, now) : 0; return (
@@ -360,50 +336,8 @@ export default function RunnerSettingsCard() { {error &&
{error}
} {pairing && ( -
-
- Your one-time code - {pairing.code} - -
-
{left > 0 ? `It works once, for about ${left} more minute${left === 1 ? '' : 's'}.` : 'This code has expired. Choose Add a runner for a new one.'}
- - {scripts ? ( - <> -
- - Other systems: - {(Object.keys(OS_LABEL) as OsKind[]).filter(kind => kind !== os).map(kind => ( - - ))} -
-

{runHint(os, scripts[os].filename)}

-
- View the script before you run it -
{scripts[os].text}
-
-

The script carries only this one-time code, never a key. It asks before it does anything, installs nothing system-wide, and makes a private environment in your home folder.

- - ) : ( -

- {pairing.install_problem || 'The install address could not be built, so there is no starter script to download.'}{' '} - If you installed the runner yourself, pair this computer with this code: saapp-runner pair --server {window.location.origin} {pairing.code} -

- )} - - {pairing.commands && ( -
- Prefer to type it? The same setup as commands -
{pairing.commands.join('\n')}
- -
- )} - -
- - When the runner connects it shows above as Connected. -
-
+ setPairing(null)} + expiredText="This code has expired. Choose Add a runner for a new one." doneHint="When the runner connects it shows above as Connected." /> )}
); diff --git a/local/src/components/SessionColumn.tsx b/local/src/components/SessionColumn.tsx index 2e2a05fe..28ab2a03 100644 --- a/local/src/components/SessionColumn.tsx +++ b/local/src/components/SessionColumn.tsx @@ -1,10 +1,14 @@ -import React, { useEffect, useState } from 'react'; -import { api, type CodePlan, type MemorySources, type RunnerInfo } from '../api'; +import React, { useEffect, useState, useSyncExternalStore } from 'react'; +import { api, createRunnerPairing, type CodePlan, type MemorySources, type RunnerInfo } from '../api'; import type { RingView } from './budgetText'; import Ring from './Ring'; import { - APPROVAL_OPTIONS, GIT_OPTIONS, RUNNER_INSTALL_CMD, RUNNER_INSTALL_POWERSHELL, contextGauge, folderLight, folderLine, folderCard, gaugeSummary, memoryLine, parseCollapsed, planProgress, runnerLine, runnerProjectHint, runnerProjectOffer, serializeCollapsed, toggleCollapsed, + APPROVAL_OPTIONS, GIT_OPTIONS, RUNNER_INSTALL_CMD, RUNNER_INSTALL_POWERSHELL, contextGauge, folderLight, folderLine, folderCard, gaugeSummary, memoryLine, runnerPairingAllowed, parseCollapsed, planProgress, runnerLine, runnerProjectHint, runnerProjectOffer, serializeCollapsed, toggleCollapsed, type ContextUse, type Line, type Option, type RunnerProjectOffer, type RunnerStartPhase, type ScopeChoice, RUNNER_NUDGE_TEXT, RUNNER_NUDGE_TITLE } from './sessionColumnLogic'; +import { useRunnerPick } from '../hooks/useRunnerPick'; +import { runnersInUse } from './runnerPick'; +import { clearPairing, getPairingState, pairingStatus, startPairing, subscribePairing } from './runnerPairing'; +import RunnerPairingSetup from './RunnerPairingSetup'; import CompactionMeter from './CompactionMeter'; import ColumnResizer from './ColumnResizer'; import { gaugesSummary, isOverloaded, meterCaption, meterName, type CompactionView } from './compactionMeterLogic'; @@ -54,6 +58,8 @@ interface Props { plan: CodePlan | null; /** The scope Sonic answers from, as a dropdown right in the panel (it used to open the settings menu's picker down by the message box). null when there are none to pick. */ scope: ScopeControls | null; + /** The most runners this person may have; optional. Without it the panel does not refuse, and the server's own limit message is shown instead. */ + runnerLimit?: number | null; /** What the last reply drew on from memory. */ memory: MemorySources | null; /** The folder's actions and options; null where a folder cannot be connected (a guest). */ @@ -176,6 +182,8 @@ export interface ConnectionProps { runnerSetup?: RunnerSetup | null; /** Called after "Let the runner run checks here" asked a runner to add the open folder, so the page can ask which projects the runner has now every few seconds (hooks/useRunnerPing askSoon). */ onRunnerAsked?: () => void; + /** The most runners this person may have. Without it the panel does not refuse, and the server's own limit message is shown instead. */ + runnerLimit?: number | null; } export interface RunnerSetup { visible: boolean; onOpen: () => void; onDismiss: () => void; } @@ -232,22 +240,61 @@ function RunnerProjectAsk({ offer, onAsked }: { offer: RunnerProjectOffer; onAsk ); } -export function ConnectionPanel({ folder, runnerEnabled, runners, runnerStart, folderControls, runnerSetup, onRunnerAsked }: ConnectionProps) { +export function ConnectionPanel({ folder, runnerEnabled, runners, runnerStart, folderControls, runnerSetup, onRunnerAsked, runnerLimit }: ConnectionProps) { // "2s ago" goes stale on its own: redraw the times every few seconds. const [now, setNow] = useState(() => new Date()); useEffect(() => { const timer = window.setInterval(() => setNow(new Date()), 15_000); return () => window.clearInterval(timer); }, []); - const runner = runnerEnabled ? runnerLine(runners, now) : null; + // The computer picked for checks (components/runnerPick.ts): the status lines, the card and the add-folder button are about it. No pick: as before, the server's own rule. + const [pick, setPick] = useRunnerPick(runners); + const runner = runnerEnabled ? runnerLine(runnersInUse(runners, pick), now) : null; const folderRow = folderLine(folder.status, folder.name, folder.fileCount); - const projectOffer = runnerEnabled ? runnerProjectOffer(runners, folder.status, folder.name) : null; + const projectOffer = runnerEnabled ? runnerProjectOffer(runners, folder.status, folder.name, pick) : null; // With a folder open it is one card with two abilities (Files, Run); with none, the runner row and "No folder connected" stand alone as before. - const card = folderCard(runners, folder.status, folder.name, folder.fileCount, now); + const card = folderCard(runners, folder.status, folder.name, folder.fileCount, now, pick); + // Pairing another computer (components/runnerPairing.ts keeps the code, so closing the panel does not lose it): the code goes once it is used or expires. + const pairing = useSyncExternalStore(subscribePairing, getPairingState); + const pairingNow = pairing.entry ? pairingStatus(pairing.entry, runners, now.getTime()) : null; + const shownCode = pairingNow === 'waiting' ? pairing.entry!.pairing : null; + useEffect(() => { + if (pairingNow && pairingNow !== 'waiting') clearPairing(); + }, [pairingNow]); + // While a code is showing, ask about the runners every few seconds, so the new computer shows up as it connects (hooks/useRunnerPing askSoon lasts 45 seconds). + const waitingCode = shownCode?.code; + useEffect(() => { + if (!waitingCode) return undefined; + onRunnerAsked?.(); + const timer = window.setInterval(() => onRunnerAsked?.(), 40_000); + return () => window.clearInterval(timer); + }, [waitingCode, onRunnerAsked]); + const pairAllowed = runnerPairingAllowed(runners?.length ?? 0, runnerLimit ?? Infinity); return ( <> {card ? : null} {card ? (runnerEnabled ? : null) : (runner && )} + {runnerEnabled && runners !== null && runners.length > 0 && ( +
+ + + {!pairAllowed.allowed && {pairAllowed.message}} + {pairing.error && {pairing.error}} + {shownCode && ( + + )} +
+ )} {projectOffer && } {runner && runners !== null && runners.length === 0 && runnerSetup && (
@@ -303,7 +350,7 @@ export function ConnectionPanel({ folder, runnerEnabled, runners, runnerStart, f * controls, the gauges, the plan while there is one, and what this conversation is scoped to. It only shows what the page already knows; settings stay in the "..." menu (the scope row * opens that menu's own picker). A card with nothing to show is not drawn, and any card can be folded (remembered in this browser). */ -const SessionColumn: React.FC = ({ folder, runnerEnabled, runners, runnerStart, runnerSetup, onRunnerAsked, usage, context, compaction, onSwitchMeter, onFold, folding, plan, scope, memory, folderControls, repo, controls }) => { +const SessionColumn: React.FC = ({ folder, runnerEnabled, runners, runnerStart, runnerSetup, onRunnerAsked, runnerLimit, usage, context, compaction, onSwitchMeter, onFold, folding, plan, scope, memory, folderControls, repo, controls }) => { // "2s ago" goes stale on its own: redraw the times every few seconds. const [now, setNow] = useState(() => new Date()); useEffect(() => { @@ -323,7 +370,8 @@ const SessionColumn: React.FC = ({ folder, runnerEnabled, runners, runner }); }; - const runner = runnerEnabled ? runnerLine(runners, now) : null; + const [pick] = useRunnerPick(runners); + const runner = runnerEnabled ? runnerLine(runnersInUse(runners, pick), now) : null; const folderRow = folderLine(folder.status, folder.name, folder.fileCount); const folderLightKind = folderLight(folder.status); const contextView = contextGauge(context); @@ -346,7 +394,7 @@ const SessionColumn: React.FC = ({ folder, runnerEnabled, runners, runner )} > - + {repo && ( diff --git a/local/src/components/SessionRail.tsx b/local/src/components/SessionRail.tsx index 68c9272e..a783fd58 100644 --- a/local/src/components/SessionRail.tsx +++ b/local/src/components/SessionRail.tsx @@ -6,6 +6,8 @@ import { ConnectionPanel, Gauge, RepoFields, RunnerNudge, ScopeField, type Conne import { ChipChoices, ModelChoices, ModelGlyph, glyph, modelChip, type ChatSettings, type ChipControl } from './ComposerChips'; import { chipLabel, isChanged, type ChipKey } from './composerChipsLogic'; import { contextGauge, folderLine, gaugeSummary, runnerLine, type ContextUse } from './sessionColumnLogic'; +import { runnersInUse } from './runnerPick'; +import { useRunnerPick } from '../hooks/useRunnerPick'; import CompactionMeter from './CompactionMeter'; import { gaugesSummary, isOverloaded, meterCaption, meterName, meterTitle, type CompactionView } from './compactionMeterLogic'; import './__styles__/SessionRail.css'; @@ -48,6 +50,7 @@ function MiniRing({ fraction, level }: { fraction: number; level: string }) { */ const SessionRail: React.FC = ({ usage, context, compaction, onSwitchMeter, onFold, folding, scope, repo, settings, connection }) => { const [open, setOpen] = useState(null); + const [runnerPick] = useRunnerPick(connection?.runners ?? null); // the dot speaks about the computer picked for checks, as the card does const rail = useRef(null); const contextView = contextGauge(context); const hasGauges = !!(compaction || usage); @@ -69,7 +72,7 @@ const SessionRail: React.FC = ({ usage, context, compaction, onSwitchMete // The Connection button's dot: amber when the runner is not answering or the folder needs attention, green when either is connected and none is not, none when there is nothing connected. const connectionTone = (() => { if (!connection) return null; - const tones = [connection.runnerEnabled ? runnerLine(connection.runners).tone : 'off', folderLine(connection.folder.status, connection.folder.name, connection.folder.fileCount).tone]; + const tones = [connection.runnerEnabled ? runnerLine(runnersInUse(connection.runners, runnerPick)).tone : 'off', folderLine(connection.folder.status, connection.folder.name, connection.folder.fileCount).tone]; if (connection.runnerSetup?.visible) return 'warn'; // no runner set up and the nudge is due: the button asks for a look, like a runner that is not answering return tones.includes('warn') ? 'warn' : tones.includes('ok') ? 'ok' : null; })(); diff --git a/local/src/components/__styles__/SessionColumn.css b/local/src/components/__styles__/SessionColumn.css index 1c341d85..1644b602 100644 --- a/local/src/components/__styles__/SessionColumn.css +++ b/local/src/components/__styles__/SessionColumn.css @@ -139,3 +139,19 @@ div.chat-page.chat-page { position: relative; container: chatpage / inline-size; .sc-nudge-title { font-weight: 600; font-size: 0.9rem; } .sc-nudge-text { margin: 0; font-size: 0.8rem; line-height: 1.45; color: var(--text-muted); } .sc-nudge-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 2px; } + +/* Choosing the computer for checks and pairing another (SessionColumn.tsx ConnectionPanel). The setup block is the Settings card's (RunnerPairingSetup.tsx), sized for the column: the account-* classes + it uses belong to the Account page, whose styles are not loaded here. */ +.sc-runner-pick { display: flex; flex-direction: column; align-items: stretch; gap: 6px; min-width: 0; margin: 8px 0 4px 16px; } +.sc-runner-pick > .sc-btn { align-self: flex-start; } +.sc-runner-pick > .sc-option-hint { min-width: 0; overflow-wrap: anywhere; } +.runner-pairing.runner-pairing-panel { min-width: 0; margin-top: 4px; padding: 8px; font-size: 0.76rem; } +.runner-pairing-panel .account-label { font-size: 0.76rem; font-weight: 600; } +.runner-pairing-panel .account-hint, .runner-pairing-panel .account-note { margin: 6px 0 0; font-size: 0.72rem; line-height: 1.4; color: var(--text-muted); overflow-wrap: anywhere; } +.runner-pairing-panel .account-btn { min-height: 0; padding: 5px 10px; border: 1px solid var(--border-color); border-radius: 8px; background: none; color: var(--text-main); font: inherit; font-size: 0.76rem; cursor: pointer; } +.runner-pairing-panel .runner-primary { background: var(--accent-primary); border-color: transparent; color: var(--on-accent, #fff); text-align: left; } +.runner-pairing-panel .runner-code { font-size: 0.9rem; } +.runner-pairing-panel .runner-link, .runner-pairing-panel .runner-details summary { font-size: 0.72rem; } +.runner-pairing-panel code { overflow-wrap: anywhere; } +.runner-pairing-panel .runner-details pre { max-height: 10rem; font-size: 0.68rem; } +.runner-pairing-panel .runner-code-line, .runner-pairing-panel .runner-os, .runner-pairing-panel .runner-done { gap: 6px; } diff --git a/local/src/components/folderCard.test.mjs b/local/src/components/folderCard.test.mjs index c7b45014..21971568 100644 --- a/local/src/components/folderCard.test.mjs +++ b/local/src/components/folderCard.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { test } from 'node:test'; -import { folderCard, folderLine, runnerLine } from './sessionColumnLogic.ts'; +import { folderCard, folderLine, runnerLine, runnerPairingAllowed } from './sessionColumnLogic.ts'; const NOW = new Date('2026-11-12T12:00:00Z'); const runner = (over = {}) => ({ id: 'r1', name: 'my pc', connected: true, last_seen: '2026-11-12T11:59:50Z', projects: [], requests: [], ...over }); @@ -61,9 +61,96 @@ test('the Run line agrees with the button under it: the offer exists exactly whe test('the panel draws the card while a folder is open (hidden Run line for a guest) and the old rows when none is', () => { const column = readFileSync(new URL('./SessionColumn.tsx', import.meta.url), 'utf8'); - assert.match(column, /const card = folderCard\(runners, folder\.status, folder\.name, folder\.fileCount, now\);/); + assert.match(column, /const card = folderCard\(runners, folder\.status, folder\.name, folder\.fileCount, now, pick\);/); + assert.match(column, /aria-label="Runner for checks"/); + assert.match(column, /const \[pick, setPick\] = useRunnerPick\(runners\);/); assert.match(column, /\{card \? : null\}/); assert.match(column, /\{card \? \(runnerEnabled \? : null\) : \(runner && \)\}/); assert.match(column, /\{!card && \}/); assert.match(column, /\{projectOffer && \}/); }); + +test('chosen runner with the folder added is ready', () => { + const runners = [runner({ id: 'a', name: 'laptop', projects: [] }), runner({ id: 'b', name: 'desktop', projects: [project('store-api')] })]; + const card = folderCard(runners, 'connected', 'store-api', 3, NOW, 'b'); + assert.equal(card.runKind, 'ready'); + assert.equal(card.run.text, 'Run · ready'); +}); + +test('chosen runner without the folder is needs_project', () => { + const runners = [runner({ id: 'a', name: 'laptop', projects: [] }), runner({ id: 'b', name: 'desktop', projects: [project('store-api')] })]; + const card = folderCard(runners, 'connected', 'store-api', 3, NOW, 'a'); + assert.equal(card.runKind, 'needs_project'); +}); + +test('no pick keeps the old behaviour', () => { + const runners = [runner({ id: 'a', name: 'laptop', projects: [] }), runner({ id: 'b', name: 'desktop', projects: [project('store-api')] })]; + assert.equal(folderCard(runners, 'connected', 'store-api', 3, NOW).runKind, 'ready'); +}); + +test('a picked runner that is not answering is named on the Run line', () => { + const runners = [runner({ id: 'a', name: 'laptop', connected: false, projects: [] }), runner({ id: 'b', name: 'desktop', projects: [project('store-api')] })]; + const card = folderCard(runners, 'connected', 'store-api', 3, NOW, 'a'); + assert.equal(card.runKind, 'not_answering'); + assert.equal(card.run.text, 'Run · runner not answering'); + assert.match(card.run.detail, /laptop/); +}); + +test('pairing allowed below the maximum', () => { + const result = runnerPairingAllowed(2, 5); + assert.equal(result.allowed, true); +}); + +test('pairing refused at the maximum', () => { + const result = runnerPairingAllowed(5, 5); + assert.equal(result.allowed, false); + assert.equal(typeof result.message, 'string'); + assert.ok(result.message.length > 0); + assert.match(result.message, /5/); +}); + +test('pairing refused above the maximum', () => { + const result = runnerPairingAllowed(6, 5); + assert.equal(result.allowed, false); +}); + +test('the panel pairs through the shared code store and setup block, once per press, up to the limit', () => { + const column = readFileSync(new URL('./SessionColumn.tsx', import.meta.url), 'utf8'); + assert.match(column, /disabled=\{!pairAllowed\.allowed \|\| pairing\.asking \|\| shownCode !== null\}/); // not while asking, nor while a code is still good + assert.match(column, /onClick=\{\(\) => \{ void startPairing\(runners, folder\.name \?\? '', createRunnerPairing\)\.then\(\(\) => setNow\(new Date\(\)\)\); \}\}/); + assert.match(column, /\{!pairAllowed\.allowed && \{pairAllowed\.message\}<\/span>\}/); + assert.match(column, /\{pairing\.error && \{pairing\.error\}<\/span>\}/); + assert.match(column, / onRunnerAsked\?\.\(\), 40_000\);/); // the new computer shows up while the code does + assert.equal((column.match(/from '\.\.\/api';/g) ?? []).length, 1); +}); + +test('choosing and pairing need no folder, and Settings shows the same setup block', () => { + const column = readFileSync(new URL('./SessionColumn.tsx', import.meta.url), 'utf8'); + assert.match(column, /\{runnerEnabled && runners !== null && runners\.length > 0 && \(\s*
/); + assert.match(column, /