Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agent-accounts): in-app guided sign-in with copyable OAuth link
rubenluetke10-beep8fd7c95347e1
diff --git a/jarvis/agent_accounts.py b/jarvis/agent_accounts.pyindex 4c52ccb20a..40e23b063b 100644--- a/jarvis/agent_accounts.py+++ b/jarvis/agent_accounts.py@@ -145,6 +145,7 @@ def _display(platform: Platform) -> str:entry = workspace_agents.get_agent(platform)return entry.display_name if entry is not None else platform+#: Bumped when the stored shape changes incompatibly. An unknown version reads#: as "no added accounts": half-understanding a newer build's file would offer#: accounts whose directories this build cannot interpret, and a pane would then@@ -514,9 +515,7 @@ def delete_account(account_id: str, *, remove_files: bool = False) -> AgentAccouif not (isinstance(entry, dict) and entry.get("id") == account_id)]state["active"] = {- platform: value- for platform, value in state["active"].items()- if value != account_id+ platform: value for platform, value in state["active"].items() if value != account_id}_write_store(state)if remove_files:@@ -932,9 +931,7 @@ def _describe_claude(account: AgentAccount) -> AccountSnapshot:account=account,connected=True,mode="subscription",- message=(- f"Signed in via {label} ({email})." if email else f"Signed in via {label}."- ),+ message=(f"Signed in via {label} ({email})." if email else f"Signed in via {label}."),email=email,tier=tier,)@@ -1000,9 +997,7 @@ def _not_signed_in_message(account: AgentAccount) -> str:"""if account.builtin:return f"Not signed in — use Sign in to connect this {_display(account.platform)} plan."- return (- "Not signed in yet — use Sign in, and finish the flow in the window that opens."- )+ return "Not signed in yet — use Sign in, and finish the flow in the window that opens."def _duplicate_warning(label: str) -> str:@@ -1085,28 +1080,20 @@ def _generic_login_argv(account: AgentAccount) -> list[str]:if binary is None:hint = workspace_agents.install_command(entry.name)raise FileNotFoundError(- f"{entry.display_name} is not installed"- + (f" (run: {hint})." if hint else ".")+ f"{entry.display_name} is not installed" + (f" (run: {hint})." if hint else "."))return [binary, *login_argv]-def start_login(account: AgentAccount) -> Any:- """Open the CLI's own sign-in flow POINTED AT this account's directory.+def login_command(account: AgentAccount) -> tuple[list[str], str]:+ """The CLI's own sign-in argv for *account*, plus a display title.- Nothing about the flow itself is reimplemented — it is each CLI's real- interactive login, in a real visible terminal, with one environment variable- set. That is what makes a second subscription cost a sign-in rather than a- credential-handling scheme of our own, and it is why the first account is- untouched while the second is being added.-- Raises ``FileNotFoundError`` when the CLI is absent and- ``InteractiveTerminalUnavailable`` on a headless host — both honest- capability answers rather than an invisible process nobody can complete.+ Shared by the two ways a sign-in can be presented — the external terminal+ window (:func:`start_login`) and the in-app guided flow+ (:mod:`jarvis.agent_login_flow`) — so the command they run can never drift+ apart. Raises ``FileNotFoundError`` when the CLI is absent and+ ``AccountError`` when the platform declares no login command."""- from jarvis.core.interactive_terminal import launch_interactive_terminal-- env = env_overrides(account.platform, account.id)if account.platform == "claude":from jarvis.claude_auth import (ClaudeAuthService,@@ -1132,9 +1119,7 @@ def start_login(account: AgentAccount) -> Any:service_codex = CodexAuthService()binary = service_codex._resolve_binary() # noqa: SLF001 — the module's own seamif binary is None:- raise FileNotFoundError(- "Codex CLI is not installed (run: npm i -g @openai/codex)."- )+ raise FileNotFoundError("Codex CLI is not installed (run: npm i -g @openai/codex).")argv = [binary, "login"]title = f"Codex sign-in — {account.label}"else:@@ -1144,12 +1129,39 @@ def start_login(account: AgentAccount) -> Any:# directory, and report success.argv = _generic_login_argv(account)title = f"{_display(account.platform)} sign-in — {account.label}"- # The directory must exist before the CLI writes into it; a login that fails- # on a missing folder looks to the user like a rejected account.+ return list(argv), title+++def ensure_config_dir(account: AgentAccount) -> None:+ """Create the account directory a sign-in is about to write into.++ The directory must exist before the CLI writes into it; a login that fails+ on a missing folder looks to the user like a rejected account.+ """try:account.config_dir.mkdir(parents=True, exist_ok=True)except OSError as exc:raise AccountError(f"The account folder is not usable: {exc}") from exc+++def start_login(account: AgentAccount) -> Any:+ """Open the CLI's own sign-in flow POINTED AT this account's directory.++ Nothing about the flow itself is reimplemented — it is each CLI's real+ interactive login, in a real visible terminal, with one environment variable+ set. That is what makes a second subscription cost a sign-in rather than a+ credential-handling scheme of our own, and it is why the first account is+ untouched while the second is being added.++ Raises ``FileNotFoundError`` when the CLI is absent and+ ``InteractiveTerminalUnavailable`` on a headless host — both honest+ capability answers rather than an invisible process nobody can complete.+ """+ from jarvis.core.interactive_terminal import launch_interactive_terminal++ argv, title = login_command(account)+ ensure_config_dir(account)+ env = env_overrides(account.platform, account.id)logger.info("Agent accounts: starting sign-in for {!r}", account.label)return launch_interactive_terminal(argv, title=title, env=env)@@ -1170,10 +1182,12 @@ __all__ = ["create_account","delete_account","describe",+ "ensure_config_dir","env_overrides","env_var","inherit_default_mode","list_accounts",+ "login_command","mode_file_name","native_dir","platforms",diff --git a/jarvis/agent_login_flow.py b/jarvis/agent_login_flow.pynew file mode 100644index 0000000000..5bbd493ee1--- /dev/null+++ b/jarvis/agent_login_flow.py@@ -0,0 +1,400 @@+"""In-app guided sign-in for agent accounts — the CLI's login over a hidden PTY.++Why this exists: the external sign-in window (:func:`jarvis.agent_accounts.+start_login`) opens the platform's raw console, and on Windows that console is+where the flow kept dying — pasting the OAuth code renders late or not at all,+Enter submits a half-arrived paste, and the single-use code is burned+("Invalid code" on every retry). On top of that the CLI auto-opens the OAuth+URL in the DEFAULT browser, which for a second subscription is usually signed+in as the WRONG account — the user needs the URL itself, to open in a private+window or another profile, and a console is the worst place to copy a+400-character line from.++So the same login runs here instead, invisibly, over the existing AD-6 PTY+seam (:func:`jarvis.terminal.backend.make_pty_backend`), and the app shows a+proper surface: the URL as a copyable link, an input for the code, and honest+progress. Nothing about the flow itself is reimplemented — it is still each+CLI's own interactive login pointed at the account's directory, the promise+:mod:`jarvis.agent_accounts` is built on. This module never parses, stores or+forwards a credential; the pasted code goes straight into the CLI's stdin and+success is judged by what the CLI wrote into the account directory+(:func:`jarvis.agent_accounts.describe`), never by trusting our own reading of+its output.++The PTY is deliberately WIDE (:data:`_COLS`): a terminal hard-wraps at its+width, and a wrapped OAuth URL scanned line-wise yields a truncated link — a+copy button that copies a broken URL is worse than no button. At 1000 columns+no real OAuth URL wraps.++Cross-platform: the PTY seam covers Windows (ConPTY), macOS and Linux, and —+unlike the external window — a headless server can complete this flow too (the+URL is copied out of the web UI into any browser anywhere). A host with no PTY+capability gets :class:`GuidedLoginUnavailable` with the external window as+the stated fallback, not a silent hang.+"""++from __future__ import annotations++import re+import threading+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any+from uuid import uuid4++from loguru import logger++from jarvis import agent_accounts+from jarvis.agent_accounts import AgentAccount++#: Wide enough that no OAuth URL is ever hard-wrapped by the terminal (module+#: docstring) — a wrapped URL is what breaks the copy button.+_COLS = 1000+_ROWS = 50+_READ_SIZE = 8192+#: Idle back-off between empty reads; also the cadence cancellation is noticed.+_POLL_S = 0.05+#: An OAuth code is only valid for minutes; a flow nobody finishes must not+#: keep a hidden CLI process alive forever.+_FLOW_TIMEOUT_S = 15 * 60+#: How often the account directory is re-checked for a completed login while+#: the child is still running (an old CLI's TUI keeps running after success).+_VERIFY_EVERY_S = 2.0+#: How much cleaned transcript the state carries for the UI ("what is the CLI+#: asking right now?") — display context, not a log.+_TAIL_CHARS = 1000+#: RAW transcript kept and re-stripped per read. Raw, because a PTY read can+#: end in the middle of an escape sequence — stripping per chunk would leak the+#: torn halves into the text, possibly inside the URL being scanned for.+_SCAN_CHARS = 32_000++_URL_RE = re.compile(r"https://[^\s\"'<>\\`]+")+#: Which of several printed URLs is THE sign-in link. Every supported CLI's+#: login URL carries one of these; docs or support links printed alongside+#: (e.g. an error's "see https://docs...") do not.+_AUTH_URL_HINT = re.compile(r"oauth|authorize|auth\.|login|device", re.IGNORECASE)+#: The CLI is asking for the code from the browser.+_CODE_PROMPT_RE = re.compile(+ r"paste\s+(?:the\s+)?code|code\s+here|authorization\s+code|enter\s+(?:the\s+)?code",+ re.IGNORECASE,+)++#: Terminal statuses — the flow is over and the child process is gone.+_FINISHED = frozenset({"success", "failed", "cancelled"})+++class GuidedLoginUnavailable(RuntimeError):+ """This host cannot run a hidden PTY — offer the external window instead."""+++@dataclass+class _Flow:+ """One guided sign-in in progress. All mutable state behind ``lock``."""++ flow_id: str+ account: AgentAccount+ lock: threading.Lock = field(default_factory=threading.Lock)+ #: starting → awaiting_input → verifying → success | failed | cancelled+ status: str = "starting"+ url: str | None = None+ #: True once the CLI asked for a code — the UI shows the input then.+ code_expected: bool = False+ message: str = ""+ tail: str = ""+ created_at: float = field(default_factory=time.monotonic)+ handle: Any = None+ tree: Any = None+ stop: threading.Event = field(default_factory=threading.Event)+ _raw: str = ""++ def to_dict(self) -> dict[str, Any]:+ with self.lock:+ return {+ "flow_id": self.flow_id,+ "account_id": self.account.id,+ "platform": self.account.platform,+ "label": self.account.label,+ "status": self.status,+ "url": self.url,+ "code_expected": self.code_expected,+ "message": self.message,+ "tail": self.tail,+ "finished": self.status in _FINISHED,+ }+++_REGISTRY: dict[str, _Flow] = {}+_REGISTRY_LOCK = threading.Lock()+++def _strip(text: str) -> str:+ from jarvis.agentic_ide.transcript import strip_ansi++ return strip_ansi(text)+++def _visible_tail(cleaned: str) -> str:+ """The last screenful of readable lines, CR-overwrites honoured.++ A TUI repaints by rewriting lines with a leading CR; only what survives the+ last CR on each line is what the user would see. Blank runs collapse so the+ tail is text, not layout.+ """+ lines: list[str] = []+ for physical in cleaned.replace("\r\n", "\n").split("\n"):+ visible = physical.rsplit("\r", 1)[-1].rstrip()+ if visible.strip():+ lines.append(visible)+ return "\n".join(lines)[-_TAIL_CHARS:]+++def _scan_for_url(cleaned: str) -> str | None:+ candidates = _URL_RE.findall(cleaned)+ if not candidates:+ return None+ trimmed = [c.rstrip(".,;:)]}\"'") for c in candidates]+ for candidate in trimmed:+ if _AUTH_URL_HINT.search(candidate):+ return candidate+ return trimmed[0]+++def _connected(account: AgentAccount) -> bool:+ """Has a login actually landed in the account directory? The honest check."""+ try:+ return bool(agent_accounts.describe(account).connected)+ except Exception as exc: # noqa: BLE001 — a probe failure is "not yet"+ logger.debug("Guided login: describe() failed during verify: {}", exc)+ return False+++def _finish(flow: _Flow, status: str, message: str) -> None:+ with flow.lock:+ if flow.status in _FINISHED:+ return+ flow.status = status+ flow.message = message+ handle = flow.handle+ if handle is not None:+ try:+ if handle.isalive():+ handle.terminate(force=True)+ except Exception: # noqa: BLE001, S110 — teardown is best-effort+ pass+ tree = flow.tree+ if tree is not None:+ flow.tree = None+ try:+ tree.close()+ except Exception as exc: # noqa: BLE001 — reaping is best-effort+ logger.debug("Guided login: process-tree teardown failed: {}", exc)+ logger.info("Guided login {} for {!r}: {}", status, flow.account.label, message or "—")+++def _ingest(flow: _Flow, data: str) -> None:+ """Fold one PTY read into the flow's visible state.++ The raw buffer is re-stripped as a whole each time (module constant) so an+ escape sequence torn across two reads never leaks its halves into the text+ the URL is scanned out of. Truncating the buffer can cut an old escape at+ the HEAD, which only garbles long-scrolled-away text, never the live tail.+ """+ with flow.lock:+ flow._raw = (flow._raw + data)[-_SCAN_CHARS:]+ cleaned = _strip(flow._raw)+ # A URL can arrive torn across two reads: the first half is already a+ # well-formed https URL, so "first match wins" would freeze a truncated+ # link into the copy button. Adopt a candidate that EXTENDS the current+ # one; an unrelated later URL never replaces the sign-in link.+ candidate = _scan_for_url(cleaned)+ if candidate is not None and (+ flow.url is None+ or (candidate.startswith(flow.url) and len(candidate) > len(flow.url))+ ):+ flow.url = candidate+ if not flow.code_expected and _CODE_PROMPT_RE.search(cleaned):+ flow.code_expected = True+ if flow.status == "starting" and (flow.url or flow.code_expected):+ flow.status = "awaiting_input"+ flow.tail = _visible_tail(cleaned)+++def _reader(flow: _Flow) -> None:+ """Drain the hidden PTY until the login concludes — its own daemon thread."""+ handle = flow.handle+ deadline = flow.created_at + _FLOW_TIMEOUT_S+ last_verify = 0.0+ while not flow.stop.is_set():+ now = time.monotonic()+ if now >= deadline:+ _finish(+ flow,+ "failed",+ "The sign-in timed out — start it again for a fresh code.",+ )+ return+ try:+ data = handle.read(_READ_SIZE)+ except EOFError:+ break+ except Exception as exc: # noqa: BLE001 — process died mid-read+ logger.debug("Guided login: PTY read ended: {}", exc)+ break+ if data:+ _ingest(flow, data)+ elif not handle.isalive():+ break+ else:+ flow.stop.wait(_POLL_S)+ # An old CLI's first-run TUI never exits after a successful login, and+ # codex signs in via a browser redirect with no code at all — so the+ # directory, not the process, is what says "done".+ if now - last_verify >= _VERIFY_EVERY_S:+ last_verify = now+ if _connected(flow.account):+ _finish(flow, "success", "Signed in.")+ return+ if flow.stop.is_set():+ return+ # The child exited by itself — the directory has the last word.+ if _connected(flow.account):+ _finish(flow, "success", "Signed in.")+ return+ with flow.lock:+ tail = flow.tail+ last_line = tail.splitlines()[-1].strip() if tail.splitlines() else ""+ _finish(+ flow,+ "failed",+ last_line or "The sign-in ended before a login was stored — try again.",+ )+++def _drop_finished(now: float) -> None:+ """Forget concluded flows so polling a stale id answers 404, not history."""+ with _REGISTRY_LOCK:+ stale = [+ fid+ for fid, flow in _REGISTRY.items()+ if flow.status in _FINISHED and now - flow.created_at > 30 * 60+ ]+ for fid in stale:+ _REGISTRY.pop(fid, None)+++def start_flow(account: AgentAccount) -> dict[str, Any]:+ """Begin a guided sign-in for *account*; any previous one is cancelled.++ Raises ``FileNotFoundError`` (CLI missing), ``AccountError`` (no login+ command / unusable directory) and :class:`GuidedLoginUnavailable` (no PTY+ capability on this host) — each a distinct, actionable answer.+ """+ from jarvis.core.process_tree import make_process_tree+ from jarvis.terminal.backend import make_pty_backend++ argv, _title = agent_accounts.login_command(account)+ agent_accounts.ensure_config_dir(account)+ env = agent_accounts.spawn_env(account.platform, account.id)++ now = time.monotonic()+ _drop_finished(now)+ with _REGISTRY_LOCK:+ running = [+ flow+ for flow in _REGISTRY.values()+ if flow.account.id == account.id and flow.status not in _FINISHED+ ]+ for flow in running:+ cancel_flow(flow.flow_id)++ try:+ handle = make_pty_backend().spawn(+ argv=tuple(argv),+ cwd=str(Path.home()),+ cols=_COLS,+ rows=_ROWS,+ env=env,+ )+ except RuntimeError as exc:+ raise GuidedLoginUnavailable(+ f"This host cannot run the sign-in in-app ({exc}) — "+ "use the terminal-window sign-in instead."+ ) from exc++ flow = _Flow(flow_id=uuid4().hex, account=account)+ flow.handle = handle+ flow.message = "Starting the sign-in…"+ flow.tree = make_process_tree(f"login:{account.id}")+ try:+ flow.tree.assign(int(getattr(handle, "pid", 0) or 0))+ except Exception as exc: # noqa: BLE001 — containment is a safeguard, not a gate+ logger.warning("Guided login could not be contained: {}", exc)+ with _REGISTRY_LOCK:+ _REGISTRY[flow.flow_id] = flow+ threading.Thread(+ target=_reader,+ name=f"login-flow-{flow.flow_id[:8]}",+ args=(flow,),+ daemon=True,+ ).start()+ logger.info("Guided login started for {!r} ({})", account.label, account.platform)+ return flow.to_dict()+++def flow_state(flow_id: str) -> dict[str, Any] | None:+ with _REGISTRY_LOCK:+ flow = _REGISTRY.get(flow_id)+ return flow.to_dict() if flow is not None else None+++def submit_code(flow_id: str, code: str) -> dict[str, Any] | None:+ """Hand the pasted code to the CLI, exactly as typing it would.++ The code is passed through untouched apart from surrounding whitespace —+ this module has no opinion about its shape, only the CLI does. Control+ characters are refused because no OAuth code contains one and a stray+ escape sequence pasted by accident would drive the TUI blind.+ """+ with _REGISTRY_LOCK:+ flow = _REGISTRY.get(flow_id)+ if flow is None:+ return None+ value = code.strip()+ if not value:+ raise ValueError("The code is empty — paste the code from the browser.")+ if any(ch < " " for ch in value):+ raise ValueError("The code contains control characters — copy it again.")+ with flow.lock:+ if flow.status in _FINISHED:+ return flow.to_dict()+ handle = flow.handle+ try:+ handle.write(value + "\r")+ except Exception as exc: # noqa: BLE001 — the child died under the write+ _finish(flow, "failed", f"The sign-in process is gone ({exc}) — try again.")+ return flow.to_dict()+ with flow.lock:+ if flow.status not in _FINISHED:+ flow.status = "verifying"+ flow.message = "Code sent — waiting for the CLI to confirm…"+ return flow.to_dict()+++def cancel_flow(flow_id: str) -> dict[str, Any] | None:+ with _REGISTRY_LOCK:+ flow = _REGISTRY.get(flow_id)+ if flow is None:+ return None+ flow.stop.set()+ _finish(flow, "cancelled", "Sign-in cancelled.")+ return flow.to_dict()+++__all__ = [+ "GuidedLoginUnavailable",+ "cancel_flow",+ "flow_state",+ "start_flow",+ "submit_code",+]diff --git a/jarvis/ui/web/agent_accounts_routes.py b/jarvis/ui/web/agent_accounts_routes.pyindex e6a6abfdfa..815583ff65 100644--- a/jarvis/ui/web/agent_accounts_routes.py+++ b/jarvis/ui/web/agent_accounts_routes.py@@ -14,6 +14,7 @@ Mount alongside the other routers::Nothing here returns a credential. The snapshots carry booleans, the displayemail, and the tier — never a token, and never the contents of a config file."""+from __future__ import annotationsimport asyncio@@ -23,8 +24,9 @@ from typing import Anyfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field-from jarvis import agent_accounts+from jarvis import agent_accounts, agent_login_flowfrom jarvis.agent_accounts import MAX_LABEL_CHARS, AccountError, platforms+from jarvis.agent_login_flow import GuidedLoginUnavailablefrom jarvis.core.interactive_terminal import InteractiveTerminalUnavailablelog = logging.getLogger(__name__)@@ -47,16 +49,13 @@ class AccountCreateRequest(BaseModel):class AccountRenameRequest(BaseModel):- label: str = Field(- max_length=MAX_LABEL_CHARS, description="New display name for the account."- )+ label: str = Field(max_length=MAX_LABEL_CHARS, description="New display name for the account.")class ActiveRequest(BaseModel):platform: str = Field(description=(- "Which coding CLI to switch. GET this endpoint for the accepted "- "values on this build."+ "Which coding CLI to switch. GET this endpoint for the accepted values on this build."))account_id: str = Field(description="Id of the account new terminals should use.")@@ -121,9 +120,7 @@ async def create_account(req: AccountCreateRequest) -> dict[str, Any]:"""platform = _platform(req.platform)try:- account = await asyncio.to_thread(- agent_accounts.create_account, platform, req.label- )+ account = await asyncio.to_thread(agent_accounts.create_account, platform, req.label)except AccountError as exc:raise HTTPException(status_code=422, detail=str(exc)) from excsnapshot = await asyncio.to_thread(agent_accounts.describe, account)@@ -140,9 +137,7 @@ async def set_active(req: ActiveRequest) -> dict[str, Any]:"""platform = _platform(req.platform)try:- account = await asyncio.to_thread(- agent_accounts.set_active, platform, req.account_id- )+ account = await asyncio.to_thread(agent_accounts.set_active, platform, req.account_id)except AccountError as exc:raise HTTPException(status_code=404, detail=str(exc)) from excreturn {@@ -188,13 +183,85 @@ async def login(account_id: str) -> dict[str, Any]:}+class LoginFlowCodeRequest(BaseModel):+ code: str = Field(+ max_length=4096,+ description="The code the browser showed after approving the sign-in.",+ )+++def _flow_or_404(state: dict[str, Any] | None) -> dict[str, Any]:+ if state is None:+ raise HTTPException(+ status_code=404,+ detail="That sign-in is no longer running — start it again.",+ )+ return {"ok": True, "flow": state}+++ "/{account_id}/login-flow",+ summary="Start an in-app sign-in for one subscription",+)+async def start_login_flow(account_id: str) -> dict[str, Any]:+ """Run the CLI's own sign-in hidden in-app, surfaced as URL + code field.++ The browser link is returned as data so the user can open it in ANY+ browser profile or private window — the default browser is usually signed+ in as the wrong account when a second subscription is being added. 409+ when the CLI is missing or the host has no PTY capability; the external+ terminal-window sign-in remains the stated fallback.+ """+ account = await asyncio.to_thread(agent_accounts.resolve, account_id)+ if account is None:+ raise HTTPException(status_code=404, detail="That account no longer exists.")+ try:+ state = await asyncio.to_thread(agent_login_flow.start_flow, account)+ except FileNotFoundError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except GuidedLoginUnavailable as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except AccountError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ return {"ok": True, "flow": state}+++ "/login-flow/{flow_id}",+ summary="State of a running in-app sign-in",+)+async def get_login_flow(flow_id: str) -> dict[str, Any]:+ """Polled by the sign-in dialog: status, the sign-in URL, and what the CLI+ is currently showing. Never carries a credential."""+ return _flow_or_404(await asyncio.to_thread(agent_login_flow.flow_state, flow_id))+++ "/login-flow/{flow_id}/code",+ summary="Hand the pasted code to a running in-app sign-in",+)+async def submit_login_flow_code(flow_id: str, req: LoginFlowCodeRequest) -> dict[str, Any]:+ """The code goes straight into the CLI's stdin, exactly as typing it would."""+ try:+ state = await asyncio.to_thread(agent_login_flow.submit_code, flow_id, req.code)+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ return _flow_or_404(state)+++ "/login-flow/{flow_id}",+ summary="Cancel a running in-app sign-in",+)+async def cancel_login_flow(flow_id: str) -> dict[str, Any]:+ return _flow_or_404(await asyncio.to_thread(agent_login_flow.cancel_flow, flow_id))++@router.patch("/{account_id}", summary="Rename a subscription")async def rename(account_id: str, req: AccountRenameRequest) -> dict[str, Any]:"""Give an added subscription a different display name."""try:- account = await asyncio.to_thread(- agent_accounts.rename_account, account_id, req.label- )+ account = await asyncio.to_thread(agent_accounts.rename_account, account_id, req.label)except AccountError as exc:raise HTTPException(status_code=422, detail=str(exc)) from excreturn {"ok": True, "account": account.to_dict(), **await asyncio.to_thread(_collect)}diff --git a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsx b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsxindex 814eb00e0f..f9d1c7e639 100644--- a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsx@@ -11,10 +11,14 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/reimport { AgentAccountsPanel } from "@/components/AgentAccountsPanel";import {+ type LoginFlowState,createAgentAccount,fetchAgentAccounts,+ getLoginFlow,loginAgentAccount,setActiveAgentAccount,+ startLoginFlow,+ submitLoginFlowCode,} from "@/lib/agentAccountsApi";vi.mock("@/lib/agentAccountsApi", async () => {@@ -29,6 +33,10 @@ vi.mock("@/lib/agentAccountsApi", async () => {loginAgentAccount: vi.fn(),deleteAgentAccount: vi.fn(),renameAgentAccount: vi.fn(),+ startLoginFlow: vi.fn(),+ getLoginFlow: vi.fn(),+ submitLoginFlowCode: vi.fn(),+ cancelLoginFlow: vi.fn(),};});@@ -77,12 +85,31 @@ const secondSeat = account({email: "[email protected]",});+function flowState(over: Partial<LoginFlowState> = {}): LoginFlowState {+ return {+ flow_id: "flow-1",+ account_id: "claude:new1",+ platform: "claude",+ label: "Fresh seat",+ status: "awaiting_input",+ url: "https://claude.ai/oauth/authorize?client_id=abc&state=xyz",+ code_expected: true,+ message: "",+ tail: "Paste code here if prompted:",+ finished: false,+ ...over,+ };+}+afterEach(cleanup);beforeEach(() => {vi.mocked(fetchAgentAccounts).mockReset();vi.mocked(setActiveAgentAccount).mockReset();vi.mocked(createAgentAccount).mockReset();vi.mocked(loginAgentAccount).mockReset();+ vi.mocked(startLoginFlow).mockReset();+ vi.mocked(getLoginFlow).mockReset();+ vi.mocked(submitLoginFlowCode).mockReset();});describe("AgentAccountsPanel", () => {@@ -132,27 +159,91 @@ describe("AgentAccountsPanel", () => {});});- it("shows a registered-but-unsigned account honestly, with a way in", async () => {+ it("signs in IN-APP: link to copy, code field, code handed to the flow", async () => {+ /*+ * The old path opened a raw console window, and that console is where the+ * flow kept dying: the pasted OAuth code rendered late or not at all, and+ * the single-use code was burned. Sign in must therefore start the guided+ * flow — the external window survives only as the failure fallback below.+ */const fresh = account({id: "claude:new1",label: "Fresh seat",builtin: false,connected: false,mode: "unknown",- message: "Not signed in yet — use Sign in, and finish the flow in the window that opens.",+ message: "Not signed in yet.",email: null,tier: null,});vi.mocked(fetchAgentAccounts).mockResolvedValue(response([account(), fresh]) as never,);- vi.mocked(loginAgentAccount).mockResolvedValue({ message: "Sign-in started" } as never);+ vi.mocked(startLoginFlow).mockResolvedValue(flowState());+ vi.mocked(getLoginFlow).mockResolvedValue(flowState());+ vi.mocked(submitLoginFlowCode).mockResolvedValue(+ flowState({ status: "verifying", code_expected: true }),+ );render(<AgentAccountsPanel />);await waitFor(() => expect(screen.getByText("Fresh seat")).toBeTruthy());const row = screen.getByText("Fresh seat").closest("li")!;- expect(row.textContent).toContain("Not signed in yet");+ expect(row.textContent).toContain("Not signed in");fireEvent.click(screen.getByText("Sign in"));++ await waitFor(() => {+ expect(startLoginFlow).toHaveBeenCalledWith("claude:new1");+ });+ // The link is shown as DATA — with a second subscription the default+ // browser is signed in as the wrong account, so the URL must be copyable+ // into a private window, not auto-opened and gone.+ const url = await screen.findByTestId("login-flow-url");+ expect(url.textContent).toContain("claude.ai/oauth/authorize");++ fireEvent.change(+ screen.getByPlaceholderText("Paste the code from the browser here"),+ { target: { value: " code#state " } },+ );+ fireEvent.click(screen.getByText("Confirm code"));+ await waitFor(() => {+ expect(submitLoginFlowCode).toHaveBeenCalledWith("flow-1", "code#state");+ });+ });++ it("falls back to the terminal window only after the in-app flow failed", async () => {+ const fresh = account({+ id: "claude:new1",+ label: "Fresh seat",+ builtin: false,+ connected: false,+ mode: "unknown",+ message: "Not signed in yet.",+ email: null,+ tier: null,+ });+ vi.mocked(fetchAgentAccounts).mockResolvedValue(+ response([account(), fresh]) as never,+ );+ vi.mocked(startLoginFlow).mockResolvedValue(+ flowState({+ status: "failed",+ finished: true,+ code_expected: false,+ url: null,+ message: "OAuth error: Invalid code",+ }),+ );+ vi.mocked(loginAgentAccount).mockResolvedValue({+ message: "Sign-in started",+ } as never);+ render(<AgentAccountsPanel />);+ await waitFor(() => expect(screen.getByText("Fresh seat")).toBeTruthy());++ fireEvent.click(screen.getByText("Sign in"));+ await waitFor(() =>+ expect(screen.getByText("OAuth error: Invalid code")).toBeTruthy(),+ );+ fireEvent.click(screen.getByText("Use a terminal window instead"));await waitFor(() => {expect(loginAgentAccount).toHaveBeenCalledWith("claude:new1");});diff --git a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsxindex 73806619bc..03206afcf9 100644--- a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx@@ -19,16 +19,21 @@* exactly that instead of showing a hopeful green row.*/-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import {AlertTriangle,Check,+ ClipboardPaste,+ Copy,+ ExternalLink,KeyRound,+ Loader2,LogIn,Pencil,Plus,Trash2,Users,+ X,} from "lucide-react";import { useT } from "@/i18n";@@ -36,14 +41,20 @@ import {type AccountPlatform,type AgentAccount,type AgentAccountsResponse,+ type LoginFlowState,+ cancelLoginFlow,createAgentAccount,deleteAgentAccount,fetchAgentAccounts,+ getLoginFlow,groupFor,loginAgentAccount,renameAgentAccount,setActiveAgentAccount,+ startLoginFlow,+ submitLoginFlowCode,} from "@/lib/agentAccountsApi";+import { robustCopy, robustPaste } from "@/lib/clipboard";import { useEventStore } from "@/store/events";import { cn } from "@/lib/utils";@@ -274,6 +285,7 @@ function AccountRow({const pushToast = useEventStore((s) => s.pushToast);const [renaming, setRenaming] = useState(false);const [draft, setDraft] = useState(account.label);+ const [flow, setFlow] = useState<LoginFlowState | null>(null);const pending = busy?.endsWith(account.id) ?? false;async function use() {@@ -281,13 +293,65 @@ function AccountRow({await run(`active:${account.id}`, () => activate(account.platform, account.id));}+ /**+ * Sign-in runs IN-APP: the CLI's own login on a hidden PTY, surfaced as a+ * copyable link and a code field. The external terminal window survives only+ * as the stated fallback — pasting the OAuth code into a raw console is+ * exactly where this flow kept dying (frozen paste, burned single-use code).+ */async function signIn() {+ try {+ setFlow(await startLoginFlow(account.id));+ } catch (e) {+ pushToast("error", (e as Error).message);+ }+ }++ async function signInExternally() {+ setFlow(null);await run(`login:${account.id}`, async () => {const { message } = await loginAgentAccount(account.id);pushToast("info", message);});}+ const flowDone = useCallback(+ async (finished: LoginFlowState) => {+ if (finished.status === "success") {+ pushToast("success", `${account.label}: ${t("agent_accounts.flow.success")}`);+ setFlow(null);+ // An empty action makes `run` re-read the list, which is what flips+ // the row to its honest green state.+ await run(`flow:${account.id}`, async () => {});+ } else {+ setFlow(finished);+ }+ },+ [account.id, account.label, pushToast, run, t],+ );++ // Poll the running flow. The interval is re-armed per state snapshot, which+ // is cheap at this cadence and keeps the callback free of stale closures.+ const flowDoneRef = useRef(flowDone);+ flowDoneRef.current = flowDone;+ useEffect(() => {+ if (!flow || flow.finished) return;+ const flowId = flow.flow_id;+ const timer = setInterval(() => {+ void (async () => {+ try {+ const next = await getLoginFlow(flowId);+ if (next.finished) await flowDoneRef.current(next);+ else setFlow(next);+ } catch {+ // The flow evaporated (server restart) — the box would poll forever.+ setFlow(null);+ }+ })();+ }, 1200);+ return () => clearInterval(timer);+ }, [flow]);+async function rename() {const name = draft.trim();if (!name || name === account.label) {@@ -348,7 +412,7 @@ function AccountRow({<span className="chip-yellow shrink-0">{t("agent_accounts.in_use")}</span>)}- {!account.connected && (+ {!account.connected && !flow && (<buttontype="button"onClick={() => void signIn()}@@ -410,8 +474,210 @@ function AccountRow({<span className="min-w-0 break-words">{account.warning}</span></p>)}++ {flow && (+ <LoginFlowBox+ flow={flow}+ onFlow={setFlow}+ onClose={() => {+ if (!flow.finished) void cancelLoginFlow(flow.flow_id).catch(() => {});+ setFlow(null);+ }}+ onRetry={() => void signIn()}+ onFallback={() => void signInExternally()}+ />+ )}</li>);}+/**+ * The in-app sign-in surface: what used to require a raw console window.+ *+ * The link is DATA here, not a redirect — with several subscriptions the+ * default browser is usually signed in as the wrong account, so the user must+ * be able to copy the URL into a private window or another profile. The code+ * field replaces pasting into a TUI, which on Windows rendered late or not at+ * all and burned the single-use code.+ */+function LoginFlowBox({+ flow,+ onFlow,+ onClose,+ onRetry,+ onFallback,+}: {+ flow: LoginFlowState;+ onFlow: (next: LoginFlowState) => void;+ onClose: () => void;+ onRetry: () => void;+ onFallback: () => void;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [code, setCode] = useState("");+ const [sending, setSending] = useState(false);+ const failed = flow.status === "failed" || flow.status === "cancelled";++ async function copyUrl() {+ if (!flow.url) return;+ if (await robustCopy(flow.url)) {+ pushToast("success", t("agent_accounts.flow.copied"));+ } else {+ pushToast("error", t("agent_accounts.flow.copy_failed"));+ }+ }++ async function pasteCode() {+ const text = await robustPaste();+ if (text) setCode(text.trim());+ }++ async function submit() {+ const value = code.trim();+ if (!value || sending) return;+ setSending(true);+ try {+ onFlow(await submitLoginFlowCode(flow.flow_id, value));+ setCode("");+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setSending(false);+ }+ }++ return (+ <div+ data-testid={`login-flow-${flow.account_id}`}+ className="ml-6 space-y-2 rounded-xl border border-border/70 bg-background/50 p-3"+ >+ <div className="flex items-center gap-2">+ {!flow.finished && (+ <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-primary" />+ )}+ <span+ className={cn(+ "min-w-0 flex-1 break-words text-[11px]",+ failed ? "text-amber-600" : "text-muted-foreground",+ )}+ >+ {flow.status === "starting"+ ? t("agent_accounts.flow.starting")+ : flow.status === "awaiting_input" && !flow.code_expected+ ? t("agent_accounts.flow.waiting_browser")+ : flow.message || t("agent_accounts.flow.starting")}+ </span>+ <button+ type="button"+ onClick={onClose}+ aria-label={t("agent_accounts.flow.cancel")}+ title={t("agent_accounts.flow.cancel")}+ className="shrink-0 rounded-md p-1 text-muted-foreground hover:text-foreground"+ >+ <X className="h-3 w-3" />+ </button>+ </div>++ {flow.url && !failed && (+ <div className="space-y-1.5">+ <div className="flex items-center gap-1.5">+ <code+ data-testid="login-flow-url"+ className="min-w-0 flex-1 truncate rounded-md border border-border bg-background px-2 py-1 font-mono text-[10px] text-muted-foreground"+ title={flow.url}+ >+ {flow.url}+ </code>+ <button+ type="button"+ onClick={() => void copyUrl()}+ className="inline-flex shrink-0 items-center gap-1 rounded-lg border border-border px-2 py-1 text-[11px] hover:border-primary/40"+ >+ <Copy className="h-3 w-3" />+ {t("agent_accounts.flow.copy")}+ </button>+ <a+ href={flow.url}+ target="_blank"+ rel="noreferrer noopener"+ className="inline-flex shrink-0 items-center gap-1 rounded-lg border border-border px-2 py-1 text-[11px] hover:border-primary/40"+ >+ <ExternalLink className="h-3 w-3" />+ {t("agent_accounts.flow.open")}+ </a>+ </div>+ <p className="text-[10px] leading-relaxed text-muted-foreground">+ {t("agent_accounts.flow.link_hint")}+ </p>+ </div>+ )}++ {flow.code_expected && !flow.finished && (+ <div className="flex items-center gap-1.5">+ <input+ value={code}+ onChange={(e) => setCode(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void submit();+ }}+ placeholder={t("agent_accounts.flow.code_placeholder")}+ aria-label={t("agent_accounts.flow.code_placeholder")}+ spellCheck={false}+ autoComplete="off"+ className="min-w-0 flex-1 rounded-lg border border-border bg-background px-2 py-1.5 font-mono text-xs"+ />+ <button+ type="button"+ onClick={() => void pasteCode()}+ aria-label={t("agent_accounts.flow.paste")}+ title={t("agent_accounts.flow.paste")}+ className="shrink-0 rounded-lg border border-border p-1.5 hover:border-primary/40"+ >+ <ClipboardPaste className="h-3.5 w-3.5" />+ </button>+ <button+ type="button"+ onClick={() => void submit()}+ disabled={!code.trim() || sending}+ className="shrink-0 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"+ >+ {t("agent_accounts.flow.submit")}+ </button>+ </div>+ )}++ {failed && (+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={onRetry}+ className="rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground"+ >+ {t("agent_accounts.flow.retry")}+ </button>+ <button+ type="button"+ onClick={onFallback}+ className="rounded-lg border border-border px-3 py-1.5 text-xs hover:border-primary/40"+ >+ {t("agent_accounts.flow.fallback")}+ </button>+ </div>+ )}++ {flow.tail && !flow.finished && (+ <details className="text-[10px] text-muted-foreground">+ <summary className="cursor-pointer select-none">+ {t("agent_accounts.flow.show_cli")}+ </summary>+ <pre className="mt-1 max-h-32 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-border/60 bg-background/70 p-2">+ {flow.tail}+ </pre>+ </details>+ )}+ </div>+ );+}+export default AgentAccountsPanel;diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex a7db278475..551d1cba84 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -3737,7 +3737,24 @@"in_use": "aktiv","sign_in": "Anmelden","rename": "Umbenennen",- "remove": "Entfernen"+ "remove": "Entfernen",+ "flow": {+ "starting": "Anmeldung wird gestartet…",+ "waiting_browser": "Warte darauf, dass die Anmeldung im Browser abgeschlossen wird…",+ "link_hint": "Öffne diesen Link in dem Browser, in dem das RICHTIGE Konto angemeldet ist — für ein zweites Abo ein privates Fenster oder ein anderes Browser-Profil verwenden, sonst nutzt der Browser stillschweigend das bereits angemeldete Konto.",+ "copy": "Link kopieren",+ "copied": "Link kopiert.",+ "copy_failed": "Kopieren fehlgeschlagen — markiere den Link und kopiere ihn von Hand.",+ "open": "Öffnen",+ "code_placeholder": "Code aus dem Browser hier einfügen",+ "paste": "Aus der Zwischenablage einfügen",+ "submit": "Code bestätigen",+ "success": "Angemeldet.",+ "retry": "Erneut versuchen",+ "fallback": "Stattdessen Terminal-Fenster verwenden",+ "cancel": "Anmeldung abbrechen",+ "show_cli": "Anzeigen, was das CLI ausgibt"+ }},"agentic_grid": {"continue": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 320cbfe89e..9007476662 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -3737,7 +3737,24 @@"in_use": "in use","sign_in": "Sign in","rename": "Rename",- "remove": "Remove"+ "remove": "Remove",+ "flow": {+ "starting": "Starting the sign-in…",+ "waiting_browser": "Waiting for the sign-in to finish in the browser…",+ "link_hint": "Open this link in the browser where the RIGHT account is signed in — for a second subscription use a private window or another browser profile, otherwise the browser silently reuses the account you are already signed in with.",+ "copy": "Copy link",+ "copied": "Link copied.",+ "copy_failed": "Copying failed — select the link and copy it by hand.",+ "open": "Open",+ "code_placeholder": "Paste the code from the browser here",+ "paste": "Paste from clipboard",+ "submit": "Confirm code",+ "success": "Signed in.",+ "retry": "Try again",+ "fallback": "Use a terminal window instead",+ "cancel": "Cancel sign-in",+ "show_cli": "Show what the CLI displays"+ }},"agentic_grid": {"continue": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 2566772633..69e6a8ebfe 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -3737,7 +3737,24 @@"in_use": "en uso","sign_in": "Iniciar sesión","rename": "Renombrar",- "remove": "Eliminar"+ "remove": "Eliminar",+ "flow": {+ "starting": "Iniciando el inicio de sesión…",+ "waiting_browser": "Esperando a que el inicio de sesión termine en el navegador…",+ "link_hint": "Abre este enlace en el navegador donde esté conectada la cuenta CORRECTA — para una segunda suscripción usa una ventana privada u otro perfil del navegador; de lo contrario, el navegador reutiliza en silencio la cuenta ya conectada.",+ "copy": "Copiar enlace",+ "copied": "Enlace copiado.",+ "copy_failed": "No se pudo copiar — selecciona el enlace y cópialo a mano.",+ "open": "Abrir",+ "code_placeholder": "Pega aquí el código del navegador",+ "paste": "Pegar desde el portapapeles",+ "submit": "Confirmar código",+ "success": "Sesión iniciada.",+ "retry": "Intentar de nuevo",+ "fallback": "Usar una ventana de terminal en su lugar",+ "cancel": "Cancelar el inicio de sesión",+ "show_cli": "Mostrar lo que muestra la CLI"+ }},"agentic_grid": {"continue": {diff --git a/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.tsindex 51de916e8c..2e3b400633 100644--- a/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts@@ -112,6 +112,75 @@ export function loginAgentAccount(accountId: string): Promise<{ message: string);}+/**+ * One in-app guided sign-in, as the backend reports it.+ *+ * `url` is the point of the whole flow: shown as data so the user can copy it+ * into ANY browser profile or private window — the default browser is usually+ * signed in as the wrong account when a second subscription is being added.+ * `tail` is what the CLI is showing right now, for transparency when a flow+ * asks something unexpected. Nothing here ever carries a credential.+ */+export interface LoginFlowState {+ flow_id: string;+ account_id: string;+ platform: AccountPlatform;+ label: string;+ /** starting | awaiting_input | verifying | success | failed | cancelled */+ status: string;+ url: string | null;+ /** True once the CLI asked for a code — show the input then. */+ code_expected: boolean;+ message: string;+ tail: string;+ finished: boolean;+}++interface LoginFlowEnvelope {+ flow: LoginFlowState;+}++/** Begin the in-app sign-in; any previous flow for this account is cancelled. */+export async function startLoginFlow(accountId: string): Promise<LoginFlowState> {+ const body = await send<LoginFlowEnvelope>(+ `/api/agent-accounts/${encodeURIComponent(accountId)}/login-flow`,+ { method: "POST" },+ );+ return body.flow;+}++export async function getLoginFlow(flowId: string): Promise<LoginFlowState> {+ const body = await send<LoginFlowEnvelope>(+ `/api/agent-accounts/login-flow/${encodeURIComponent(flowId)}`,+ { method: "GET", cache: "no-store" },+ );+ return body.flow;+}++/** Hand the pasted code to the CLI, exactly as typing it into the terminal would. */+export async function submitLoginFlowCode(+ flowId: string,+ code: string,+): Promise<LoginFlowState> {+ const body = await send<LoginFlowEnvelope>(+ `/api/agent-accounts/login-flow/${encodeURIComponent(flowId)}/code`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ code }),+ },+ );+ return body.flow;+}++export async function cancelLoginFlow(flowId: string): Promise<LoginFlowState> {+ const body = await send<LoginFlowEnvelope>(+ `/api/agent-accounts/login-flow/${encodeURIComponent(flowId)}`,+ { method: "DELETE" },+ );+ return body.flow;+}+export function renameAgentAccount(accountId: string,label: string,diff --git a/tests/unit/test_agent_login_flow.py b/tests/unit/test_agent_login_flow.pynew file mode 100644index 0000000000..6c29be4f9a--- /dev/null+++ b/tests/unit/test_agent_login_flow.py@@ -0,0 +1,252 @@+"""The in-app guided sign-in, driven against a scripted fake PTY.++What these pin down is the contract the dialog depends on, not the CLI's+cosmetics: the sign-in URL survives ANSI noise and chunk boundaries intact (a+copy button that copies a truncated URL is the bug this flow replaces), the+pasted code reaches the child exactly as typed, and success is judged by the+account directory — never by trusting the transcript.+"""++from __future__ import annotations++import threading+import time+from pathlib import Path+from typing import Any++import pytest++from jarvis import agent_accounts, agent_login_flow+from jarvis.agent_accounts import AgentAccount+from jarvis.agent_login_flow import GuidedLoginUnavailable++_URL = (+ "https://claude.ai/oauth/authorize?code=true&client_id=abc123"+ "&redirect_uri=https%3A%2F%2Fclaude.ai%2Foauth&state=xyz789"+)+++class FakeHandle:+ """A scripted PTY child: hands out chunks, records writes."""++ def __init__(self, chunks: list[str]) -> None:+ self._chunks = list(chunks)+ self._lock = threading.Lock()+ self.writes: list[str] = []+ self.alive = True+ self.terminated = False+ self.pid = 4242+ self.exitstatus: int | None = None++ def read(self, size: int) -> str:+ with self._lock:+ if self._chunks:+ return self._chunks.pop(0)+ if not self.alive:+ raise EOFError+ return ""++ def feed(self, chunk: str) -> None:+ with self._lock:+ self._chunks.append(chunk)++ def isalive(self) -> bool:+ return self.alive++ def write(self, data: str) -> None:+ self.writes.append(data)++ def terminate(self, force: bool) -> None:+ self.terminated = True+ self.alive = False+++class FakeBackend:+ def __init__(self, handle: FakeHandle) -> None:+ self.handle = handle+ self.spawn_calls: list[dict[str, Any]] = []++ def spawn(self, **kwargs: Any) -> FakeHandle:+ self.spawn_calls.append(kwargs)+ return self.handle+++class FakeTree:+ def assign(self, pid: int) -> None: # pragma: no cover - trivial+ pass++ def close(self) -> None: # pragma: no cover - trivial+ pass++[email protected](autouse=True)+def _fast_and_isolated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):+ """No real CLI, no real PTY, no multi-second verify cadence."""+ monkeypatch.setattr(+ agent_accounts, "login_command", lambda account: (["fake-cli", "login"], "t")+ )+ monkeypatch.setattr(agent_login_flow, "_VERIFY_EVERY_S", 0.02)+ monkeypatch.setattr(agent_login_flow, "_POLL_S", 0.005)+ # Every test decides for itself when the login "landed".+ monkeypatch.setattr(agent_login_flow, "_connected", lambda account: False)+ monkeypatch.setattr("jarvis.core.process_tree.make_process_tree", lambda name: FakeTree())+ agent_login_flow._REGISTRY.clear()+ yield+ for flow_id in list(agent_login_flow._REGISTRY):+ agent_login_flow.cancel_flow(flow_id)+ agent_login_flow._REGISTRY.clear()+++def _account(tmp_path: Path) -> AgentAccount:+ return AgentAccount(+ id="claude:test1",+ platform="claude",+ label="Second seat",+ config_dir=tmp_path / "seat",+ )+++def _start(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, chunks: list[str]):+ handle = FakeHandle(chunks)+ backend = FakeBackend(handle)+ monkeypatch.setattr("jarvis.terminal.backend.make_pty_backend", lambda: backend)+ state = agent_login_flow.start_flow(_account(tmp_path))+ return handle, backend, state+++def _wait_for(condition, timeout: float = 3.0) -> None:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if condition():+ return+ time.sleep(0.01)+ raise AssertionError("condition not reached in time")+++def _state(flow_id: str) -> dict[str, Any]:+ state = agent_login_flow.flow_state(flow_id)+ assert state is not None+ return state+++# ------------------------------------------------------------------ the URL+++def test_url_survives_ansi_noise_and_a_chunk_boundary(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """The URL arrives coloured and torn across two PTY reads — the state must+ still carry it byte-for-byte, or the copy button copies a broken link."""+ first, second = _URL[:60], _URL[60:]+ handle, _backend, state = _start(+ monkeypatch,+ tmp_path,+ [+ "\x1b[2J\x1b[1mSign in\x1b[0m\r\nOpen this url:\r\n\x1b[36m" + first,+ second + "\x1b[0m\r\nPaste code here if prompted:\r\n",+ ],+ )+ _wait_for(lambda: _state(state["flow_id"])["url"] is not None)+ final = _state(state["flow_id"])+ assert final["url"] == _URL+ assert final["code_expected"] is True+ assert final["status"] == "awaiting_input"+++def test_the_sign_in_url_wins_over_a_docs_link_printed_first(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ handle, _backend, state = _start(+ monkeypatch,+ tmp_path,+ ["See https://docs.example.com/help for details.\r\nOpen " + _URL + "\r\n"],+ )+ _wait_for(lambda: _state(state["flow_id"])["url"] is not None)+ assert _state(state["flow_id"])["url"] == _URL+++def test_the_pty_is_wide_enough_that_no_oauth_url_wraps(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ handle, backend, _state_ = _start(monkeypatch, tmp_path, [])+ assert backend.spawn_calls[0]["cols"] >= 500+++# ------------------------------------------------------------------ the code+++def test_the_pasted_code_reaches_the_child_exactly_as_typed(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ handle, _backend, state = _start(monkeypatch, tmp_path, ["Paste code here if prompted:\r\n"])+ _wait_for(lambda: _state(state["flow_id"])["code_expected"])+ result = agent_login_flow.submit_code(state["flow_id"], " abc123#state456 ")+ assert result is not None and result["status"] == "verifying"+ assert handle.writes == ["abc123#state456\r"]+++def test_an_empty_or_control_character_code_is_refused(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ handle, _backend, state = _start(monkeypatch, tmp_path, [])+ with pytest.raises(ValueError):+ agent_login_flow.submit_code(state["flow_id"], " ")+ with pytest.raises(ValueError):+ agent_login_flow.submit_code(state["flow_id"], "abc\x1b[200~def")+ assert handle.writes == []+++# ------------------------------------------------------------------- verdicts+++def test_success_is_judged_by_the_account_directory_not_the_transcript(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """The CLI may print anything; only credentials on disk flip the flow."""+ handle, _backend, state = _start(monkeypatch, tmp_path, ["Login successful! Welcome back.\r\n"])+ time.sleep(0.1)+ assert _state(state["flow_id"])["status"] not in ("success", "failed")+ monkeypatch.setattr(agent_login_flow, "_connected", lambda account: True)+ _wait_for(lambda: _state(state["flow_id"])["status"] == "success")+ assert _state(state["flow_id"])["finished"] is True+++def test_a_child_that_exits_without_a_login_fails_with_its_last_words(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ handle, _backend, state = _start(monkeypatch, tmp_path, ["OAuth error: Invalid code\r\n"])+ _wait_for(lambda: "Invalid code" in _state(state["flow_id"])["tail"])+ handle.alive = False+ _wait_for(lambda: _state(state["flow_id"])["status"] == "failed")+ assert "Invalid code" in _state(state["flow_id"])["message"]+++def test_cancelling_terminates_the_hidden_child(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ handle, _backend, state = _start(monkeypatch, tmp_path, [])+ result = agent_login_flow.cancel_flow(state["flow_id"])+ assert result is not None and result["status"] == "cancelled"+ _wait_for(lambda: handle.terminated)+++def test_a_host_with_no_pty_capability_says_so(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ class NoPty:+ def spawn(self, **kwargs: Any) -> Any:+ raise RuntimeError("no PTY capability on this host")++ monkeypatch.setattr("jarvis.terminal.backend.make_pty_backend", lambda: NoPty())+ with pytest.raises(GuidedLoginUnavailable):+ agent_login_flow.start_flow(_account(tmp_path))+++def test_a_second_start_for_the_same_account_cancels_the_first(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ first_handle, _b, first = _start(monkeypatch, tmp_path, [])+ second_handle, _b2, second = _start(monkeypatch, tmp_path, [])+ assert first["flow_id"] != second["flow_id"]+ _wait_for(lambda: first_handle.terminated)+ assert _state(second["flow_id"])["status"] == "starting"