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(computers): clearer connect dialog with a visible connection check
rubenluetke10-beep55f752adb4bc
diff --git a/jarvis/computers/service.py b/jarvis/computers/service.pyindex 3d6de137db..39519f9a5a 100644--- a/jarvis/computers/service.py+++ b/jarvis/computers/service.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport asyncioimport contextlibimport dataclasses+import importlib.utilimport loggingimport reimport secrets@@ -468,6 +469,14 @@ class ComputerService:passphrase: str | None = None,) -> dict[str, Any]:"""Try a login WITHOUT saving anything; nothing is planted on the server."""+ if importlib.util.find_spec("asyncssh") is None:+ # A base dependency missing from an older install: say so in the+ # form instead of failing the request with a bare 500.+ return _test_result(+ False,+ "protocol",+ "SSH support is missing from this installation. Update the app to install it.",+ )try:base = SshTarget(host=_check_host(host), port=port, username=_check_user(username))if auth == "password":diff --git a/jarvis/computers/ssh.py b/jarvis/computers/ssh.pyindex 83c2069423..4a8a5ed537 100644--- a/jarvis/computers/ssh.py+++ b/jarvis/computers/ssh.py@@ -94,6 +94,14 @@ def _classify(exc: BaseException) -> SshError:return SshError("unreachable", "This address could not be found.")if isinstance(exc, ConnectionRefusedError):return SshError("unreachable", "The server refused the connection on this port.")+ if isinstance(exc, (ConnectionResetError, ConnectionAbortedError)):+ # The TCP connection was up, so the address is right: the SSH service+ # itself hung up (a crashing sshd, a login rule, fail2ban-style blocks).+ return SshError(+ "protocol",+ "The server answered, then its SSH service closed the connection. "+ "Check that SSH login is allowed for this account on that computer.",+ )if isinstance(exc, OSError):return SshError("unreachable", "The server could not be reached.")if isinstance(exc, asyncssh.Error):diff --git a/jarvis/ui/web/frontend/src/i18n/locales/computers/de.json b/jarvis/ui/web/frontend/src/i18n/locales/computers/de.jsonindex 7d0721dbe4..d22f452458 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/computers/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/computers/de.json@@ -283,7 +283,7 @@"wz_next_ide_body": "Wähle in der Agentic IDE beim Öffnen eines Workspaces „Läuft auf: {computer}“.","wz_open": "{computer} öffnen","cx_title": "Computer verbinden",- "cx_subtitle": "{name} braucht nur die Adresse des Servers und einen Weg hinein.",+ "cx_subtitle": "Gib die Adresse ein und wähle, wie {name} sich anmeldet. {name} testet die Verbindung, bevor etwas gespeichert wird.","cx_address": "Server-Adresse","cx_address_hint": "Die IP aus deinem Anbieter-Panel, z. B. 203.0.113.10 – oder füge eine ganze „ssh root@…“-Zeile ein.","cx_login": "Anmeldung",@@ -298,9 +298,8 @@"cx_key_too_big": "Diese Datei ist zu groß für einen SSH-Schlüssel.","cx_own_key_hint": "Öffentlicher Schlüssel von {name} – er muss schon in authorized_keys auf dem Server stehen","cx_key_already_there": "Der Schlüssel von {name} ist schon auf dem Server",- "cx_use_password": "Stattdessen Passwort verwenden","cx_more": "Weitere Optionen",- "cx_keep_password": "Weiter mit Passwort statt Schlüssel anmelden",+ "cx_keep_password": "Passwort behalten, statt den Schlüssel von {name} zu hinterlegen","cx_connect": "Verbinden","cx_accounts_title": "Oder ein Hosting-Konto verbinden","cx_accounts_body": "Sieh alle deine Server in einer Liste und wähle einen aus – ohne IP abzutippen.",@@ -313,14 +312,39 @@"cx_fail_host_key_changed": "Die Identität des Servers hat sich seit der letzten Verbindung geändert.","cx_fail_protocol": "Die SSH-Verbindung ist fehlgeschlagen.","cx_fail_bad_key": "Das sieht nicht nach einem gültigen privaten Schlüssel aus, oder der Passwortsatz stimmt nicht.",- "cx_setup_title": "Am einfachsten: Einrichten lassen",- "cx_setup_body": "Kopiere diesen Prompt in Claude Code, Codex oder einen anderen Coding-Agenten AUF dem Zielcomputer. Er schaltet SSH ein, hinterlegt den Schlüssel von {name} und endet mit einer Zeile, die du unten einfügst.",- "cx_setup_copy": "Setup-Prompt kopieren",- "cx_paste": "Server",- "cx_paste_hint": "Eine IP, user@IP, ein ganzer ssh-Befehl – oder füge das Ergebnis des Agenten bzw. einen Block mit deinem Schlüssel ein. {name} sucht sich heraus, was es braucht.",+ "cx_paste": "Server-Adresse",+ "cx_paste_hint": "Eine IP oder ein Hostname, z. B. 203.0.113.10. Eine ganze „ssh user@host“-Zeile geht auch.","cx_detected": "Erkannt:","cx_key_found": "Privater Schlüssel",- "cx_setup_done": "Schlüssel von {name} ist eingerichtet",- "cx_have_key": "Ich habe einen SSH-Schlüssel"+ "cx_login_title": "Wie soll {name} sich anmelden?",+ "cx_method_password": "Passwort",+ "cx_method_key": "SSH-Schlüssel",+ "cx_method_agent": "Per Agent",+ "cx_key_own": "Mein eigener Schlüssel",+ "cx_key_own_body": "Ein privater Schlüssel, den du für diesen Server schon nutzt.",+ "cx_key_assistant": "Schlüssel von {name}",+ "cx_key_assistant_body": "Du hinterlegst den öffentlichen Schlüssel von {name} einmal auf dem Server.",+ "cx_key_assistant_hint": "Trage ihn auf dem Server in ~/.ssh/authorized_keys ein oder im Hosting-Panel unter „SSH-Schlüssel“. Dann auf Verbinden drücken.",+ "cx_key_from_paste": "Der private Schlüssel aus dem Adressfeld wird verwendet.",+ "cx_agent_step1": "Kopiere die Einrichtungs-Anleitung.",+ "cx_agent_copy": "Anleitung kopieren",+ "cx_agent_show": "Anzeigen",+ "cx_agent_hide": "Ausblenden",+ "cx_agent_step2": "Füge sie auf dem anderen Computer in Claude Code, Codex oder einen anderen Coding-Agenten ein. Er schaltet SSH ein und hinterlegt den Schlüssel von {name}.",+ "cx_agent_step3": "Der Agent endet mit einer Zeile, die mit JARVIS-CONNECT beginnt. Füge diese Zeile oben bei „Server-Adresse“ ein.",+ "cx_agent_done": "Die Zeile des Agenten ist drin: Der Schlüssel von {name} liegt auf dem Computer. Jetzt auf Verbinden drücken.",+ "cx_connect_hint": "Gespeichert wird erst, wenn der Test klappt.",+ "cx_check_failed": "Die Verbindung klappt noch nicht",+ "cx_check_title": "Verbindung wird geprüft",+ "cx_step_reach": "{host} erreichen",+ "cx_step_login": "Als {user} anmelden",+ "cx_step_probe": "Testbefehl ausführen",+ "cx_step_probe_warn": "Angemeldet, aber der Testbefehl kam ohne Antwort zurück. Die Verbindung funktioniert trotzdem.",+ "cx_step_save": "Verbindung speichern",+ "cx_step_save_key": "Schlüssel von {name} hinterlegen und speichern",+ "cx_step_save_warn": "Gespeichert, aber die Nachprüfung meldet den Computer nicht als online.",+ "cx_edit": "Angaben ändern",+ "cx_retry": "Erneut versuchen",+ "cx_verified_body": "{name} hat ihn erreicht, sich angemeldet und einen Testbefehl ausgeführt."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/computers/en.json b/jarvis/ui/web/frontend/src/i18n/locales/computers/en.jsonindex 1432aac6a6..df9ebfe0b5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/computers/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/computers/en.json@@ -283,7 +283,7 @@"wz_next_ide_body": "In the Agentic IDE, choose “Runs on: {computer}” when you open a workspace.","wz_open": "Open {computer}","cx_title": "Connect a computer",- "cx_subtitle": "All {name} needs is the server's address and a way in.",+ "cx_subtitle": "Enter the address and choose how {name} logs in. {name} tests the connection before it saves anything.","cx_address": "Server address","cx_address_hint": "The IP your provider shows, e.g. 203.0.113.10 — or paste a whole \"ssh root@…\" line.","cx_login": "How to log in",@@ -298,9 +298,8 @@"cx_key_too_big": "That file is too large to be an SSH key.","cx_own_key_hint": "{name}'s public key — it must already be in the server's authorized_keys","cx_key_already_there": "{name}'s key is already on the server",- "cx_use_password": "Use a password instead","cx_more": "More options",- "cx_keep_password": "Keep using the password instead of a key",+ "cx_keep_password": "Keep the password instead of installing {name}'s key","cx_connect": "Connect","cx_accounts_title": "Or connect a hosting account","cx_accounts_body": "See all your servers in one list and pick one — no IP to copy.",@@ -313,14 +312,39 @@"cx_fail_host_key_changed": "The server's identity changed since the last connection.","cx_fail_protocol": "The SSH connection failed.","cx_fail_bad_key": "This does not look like a valid private key, or the passphrase is wrong.",- "cx_setup_title": "Easiest: let an agent set it up",- "cx_setup_body": "Copy this prompt into Claude Code, Codex or any coding agent running ON that computer. It turns on SSH, adds {name}'s key and ends with one line to paste below.",- "cx_setup_copy": "Copy setup prompt",- "cx_paste": "Server",- "cx_paste_hint": "An IP, user@IP, a whole ssh command — or paste the agent's result or a block with your key. {name} picks out what it needs.",+ "cx_paste": "Server address",+ "cx_paste_hint": "An IP or host name, like 203.0.113.10. A whole “ssh user@host” line works too.","cx_detected": "Found:","cx_key_found": "Private key",- "cx_setup_done": "{name}'s key is set up",- "cx_have_key": "I have an SSH key"+ "cx_login_title": "How should {name} log in?",+ "cx_method_password": "Password",+ "cx_method_key": "SSH key",+ "cx_method_agent": "Agent setup",+ "cx_key_own": "My own key",+ "cx_key_own_body": "A private key you already use for this server.",+ "cx_key_assistant": "{name}'s key",+ "cx_key_assistant_body": "You add {name}'s public key to the server once.",+ "cx_key_assistant_hint": "Add it to ~/.ssh/authorized_keys on the server, or in your hosting panel under “SSH keys”. Then press Connect.",+ "cx_key_from_paste": "Using the private key from the address box.",+ "cx_agent_step1": "Copy the setup instructions.",+ "cx_agent_copy": "Copy instructions",+ "cx_agent_show": "Show them",+ "cx_agent_hide": "Hide them",+ "cx_agent_step2": "On that computer, paste them into Claude Code, Codex or another coding agent. It turns on SSH and adds {name}'s key.",+ "cx_agent_step3": "The agent ends with one line that starts with JARVIS-CONNECT. Paste that line into “Server address” above.",+ "cx_agent_done": "The agent's line is in: {name}'s key is on that computer. Press Connect.",+ "cx_connect_hint": "Nothing is saved until the test works.",+ "cx_check_failed": "The connection does not work yet",+ "cx_check_title": "Checking the connection",+ "cx_step_reach": "Reach {host}",+ "cx_step_login": "Log in as {user}",+ "cx_step_probe": "Run a test command",+ "cx_step_probe_warn": "Logged in, but the test command gave no answer. The connection still works.",+ "cx_step_save": "Save the connection",+ "cx_step_save_key": "Install {name}'s key and save",+ "cx_step_save_warn": "Saved, but the follow-up check did not come back online.",+ "cx_edit": "Change details",+ "cx_retry": "Try again",+ "cx_verified_body": "{name} reached it, logged in and ran a test command."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/computers/es.json b/jarvis/ui/web/frontend/src/i18n/locales/computers/es.jsonindex 75d8ff03ce..b3ae66d234 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/computers/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/computers/es.json@@ -283,7 +283,7 @@"wz_next_ide_body": "En el Agentic IDE, elige «Se ejecuta en: {computer}» al abrir un espacio de trabajo.","wz_open": "Abrir {computer}","cx_title": "Conectar un ordenador",- "cx_subtitle": "{name} solo necesita la dirección del servidor y una forma de entrar.",+ "cx_subtitle": "Escribe la dirección y elige cómo entra {name}. {name} prueba la conexión antes de guardar nada.","cx_address": "Dirección del servidor","cx_address_hint": "La IP que muestra tu proveedor, p. ej. 203.0.113.10, o pega una línea «ssh root@…» completa.","cx_login": "Inicio de sesión",@@ -298,9 +298,8 @@"cx_key_too_big": "Ese archivo es demasiado grande para ser una clave SSH.","cx_own_key_hint": "Clave pública de {name}: ya debe estar en authorized_keys del servidor","cx_key_already_there": "La clave de {name} ya está en el servidor",- "cx_use_password": "Usar contraseña","cx_more": "Más opciones",- "cx_keep_password": "Seguir entrando con contraseña en lugar de clave",+ "cx_keep_password": "Mantener la contraseña en lugar de instalar la clave de {name}","cx_connect": "Conectar","cx_accounts_title": "O conecta una cuenta de hosting","cx_accounts_body": "Ve todos tus servidores en una lista y elige uno, sin copiar la IP.",@@ -313,14 +312,39 @@"cx_fail_host_key_changed": "La identidad del servidor ha cambiado desde la última conexión.","cx_fail_protocol": "La conexión SSH falló.","cx_fail_bad_key": "No parece una clave privada válida, o la frase de contraseña es incorrecta.",- "cx_setup_title": "Lo más fácil: que un agente lo configure",- "cx_setup_body": "Copia este prompt en Claude Code, Codex u otro agente de código que se ejecute EN ese ordenador. Activa SSH, añade la clave de {name} y termina con una línea que pegas abajo.",- "cx_setup_copy": "Copiar prompt de configuración",- "cx_paste": "Servidor",- "cx_paste_hint": "Una IP, usuario@IP, un comando ssh completo, o pega el resultado del agente o un bloque con tu clave. {name} extrae lo que necesita.",+ "cx_paste": "Dirección del servidor",+ "cx_paste_hint": "Una IP o un nombre de host, como 203.0.113.10. También sirve una línea «ssh usuario@host» completa.","cx_detected": "Detectado:","cx_key_found": "Clave privada",- "cx_setup_done": "La clave de {name} está configurada",- "cx_have_key": "Tengo una clave SSH"+ "cx_login_title": "¿Cómo debe entrar {name}?",+ "cx_method_password": "Contraseña",+ "cx_method_key": "Clave SSH",+ "cx_method_agent": "Con un agente",+ "cx_key_own": "Mi propia clave",+ "cx_key_own_body": "Una clave privada que ya usas para este servidor.",+ "cx_key_assistant": "Clave de {name}",+ "cx_key_assistant_body": "Añades una vez la clave pública de {name} al servidor.",+ "cx_key_assistant_hint": "Añádela en ~/.ssh/authorized_keys del servidor o en tu panel de hosting, en «Claves SSH». Después pulsa Conectar.",+ "cx_key_from_paste": "Se usa la clave privada del campo de dirección.",+ "cx_agent_step1": "Copia las instrucciones de configuración.",+ "cx_agent_copy": "Copiar instrucciones",+ "cx_agent_show": "Mostrar",+ "cx_agent_hide": "Ocultar",+ "cx_agent_step2": "En ese ordenador, pégalas en Claude Code, Codex u otro agente de código. Activa SSH y añade la clave de {name}.",+ "cx_agent_step3": "El agente termina con una línea que empieza por JARVIS-CONNECT. Pega esa línea arriba en «Dirección del servidor».",+ "cx_agent_done": "La línea del agente está dentro: la clave de {name} ya está en ese ordenador. Pulsa Conectar.",+ "cx_connect_hint": "No se guarda nada hasta que la prueba funcione.",+ "cx_check_failed": "La conexión aún no funciona",+ "cx_check_title": "Comprobando la conexión",+ "cx_step_reach": "Llegar a {host}",+ "cx_step_login": "Entrar como {user}",+ "cx_step_probe": "Ejecutar un comando de prueba",+ "cx_step_probe_warn": "Ha entrado, pero el comando de prueba no respondió. La conexión funciona igualmente.",+ "cx_step_save": "Guardar la conexión",+ "cx_step_save_key": "Instalar la clave de {name} y guardar",+ "cx_step_save_warn": "Guardado, pero la comprobación posterior no lo ve en línea.",+ "cx_edit": "Cambiar datos",+ "cx_retry": "Reintentar",+ "cx_verified_body": "{name} lo alcanzó, entró y ejecutó un comando de prueba."}}diff --git a/jarvis/ui/web/frontend/src/views/ComputersView.test.tsx b/jarvis/ui/web/frontend/src/views/ComputersView.test.tsxindex c82b4fbecf..aa19c95f70 100644--- a/jarvis/ui/web/frontend/src/views/ComputersView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ComputersView.test.tsx@@ -165,6 +165,13 @@ describe("ComputersView", () => {fireEvent.change(screen.getByTestId("cx-password"), { target: { value: "hunter2" } });fireEvent.click(connect);+ // The check is visible: every step resolves, the machine's facts prove it.+ expect(await screen.findByTestId("cx-facts")).toBeTruthy();+ for (const step of ["reach", "login", "probe", "save"]) {+ expect(screen.getByTestId(`cx-step-${step}`).getAttribute("data-state")).toBe("ok");+ }+ expect(screen.getByText("srv17923")).toBeTruthy();+ fireEvent.click(screen.getByTestId("cx-open"));expect(await screen.findByTestId("computer-detail")).toBeTruthy();const post = calls.find((c) => c.method === "POST" && c.url === "/api/computers");expect(post?.body).toMatchObject({@@ -203,8 +210,11 @@ describe("ComputersView", () => {expect(screen.queryByTestId("cx-password")).toBeNull();expect(screen.getByTestId("cx-detected").textContent).toContain("[email protected]");+ // A pasted key switches the login to "SSH key" by itself.+ expect(screen.getByTestId("cx-method-key").getAttribute("aria-selected")).toBe("true");fireEvent.click(screen.getByTestId("cx-connect"));+ fireEvent.click(await screen.findByTestId("cx-open"));expect(await screen.findByTestId("computer-detail")).toBeTruthy();const post = calls.find((c) => c.method === "POST" && c.url === "/api/computers");expect(post?.body).toMatchObject({ host: "192.168.178.132", username: "Administrator", auth: "private_key" });@@ -246,7 +256,39 @@ describe("ComputersView", () => {fireEvent.click(screen.getByTestId("cx-connect"));expect(await screen.findByText(/refused the login/)).toBeTruthy();+ // The server was reached; the login step is the one that failed.+ expect(screen.getByTestId("cx-step-reach").getAttribute("data-state")).toBe("ok");+ expect(screen.getByTestId("cx-step-login").getAttribute("data-state")).toBe("fail");expect(calls.some((c) => c.method === "POST" && c.url === "/api/computers")).toBe(false);+ // "Change details" returns to the form with everything kept.+ fireEvent.click(screen.getByTestId("cx-edit"));+ expect((screen.getByTestId("cx-password") as HTMLInputElement).value).toBe("wrong");+ });++ it("shows every way in as a visible choice", async () => {+ installFetch({+ "GET /api/computers": () => ({ computers: [] }),+ "GET /api/computers/providers": () => ({ providers: PROVIDERS }),+ "GET /api/computers/identity": () => IDENTITY,+ });+ renderView();++ fireEvent.click(await screen.findByTestId("computers-add-first"));+ fireEvent.change(await screen.findByTestId("cx-address"), { target: { value: "192.168.1.20" } });++ fireEvent.click(screen.getByTestId("cx-method-key"));+ expect(screen.getByTestId("cx-private-key")).toBeTruthy();+ fireEvent.click(screen.getByTestId("cx-key-assistant"));+ expect((await screen.findByTestId("cx-assistant-key")).textContent).toContain(IDENTITY.public_key);+ // The assistant's key needs nothing typed: Connect is ready.+ expect((screen.getByTestId("cx-connect") as HTMLButtonElement).disabled).toBe(false);++ fireEvent.click(screen.getByTestId("cx-method-agent"));+ expect(screen.getByTestId("cx-copy-prompt")).toBeTruthy();+ fireEvent.change(screen.getByTestId("cx-address"), {+ target: { value: "Done.\nJARVIS-CONNECT [email protected]:22" },+ });+ expect(screen.getByTestId("cx-agent").textContent).toMatch(/key is on that computer/);});it("lists a machine, opens it and runs a console command", async () => {diff --git a/jarvis/ui/web/frontend/src/views/computers/ConnectCheck.tsx b/jarvis/ui/web/frontend/src/views/computers/ConnectCheck.tsxnew file mode 100644index 0000000000..bce9e9c3bc--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/computers/ConnectCheck.tsx@@ -0,0 +1,184 @@+/**+ * The visible connection check behind "Connect". It shows the four things the+ * backend really does, in order: reach the server, log in, run a test command,+ * then save (planting the assistant's key when a password was used). Each row+ * resolves from a real answer — the dry-run test settles the first three, the+ * save call the last — so a green tick always means that step happened.+ *+ * On success the machine's own facts (host name, OS, cores, memory, response+ * time) prove the login reached the right computer; on failure the failed row+ * says what to fix and the user goes back to the form with everything kept.+ */+import type { ReactNode } from "react";+import { ArrowRight, Circle, CircleAlert, CircleCheck, CircleX, Loader2, RotateCcw, Wrench } from "lucide-react";+import { Button } from "@/components/ui/button";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import type { Computer, ComputerFacts } from "@/lib/computersApi";+import { formatMemory } from "./parts";++export type StepState = "wait" | "run" | "ok" | "warn" | "fail";+export type StepId = "reach" | "login" | "probe" | "save";++export interface CheckState {+ steps: Record<StepId, StepState>;+ /** The line under the step that failed or warned. */+ notes: Partial<Record<StepId, string>>;+ facts: ComputerFacts | null;+ latencyMs: number | null;+ computer: Computer | null;+}++export const STEP_ORDER: StepId[] = ["reach", "login", "probe", "save"];++export function startCheck(): CheckState {+ return {+ steps: { reach: "run", login: "wait", probe: "wait", save: "wait" },+ notes: {},+ facts: null,+ latencyMs: null,+ computer: null,+ };+}++export function checkFailed(check: CheckState): boolean {+ return STEP_ORDER.some((id) => check.steps[id] === "fail");+}++export function checkRunning(check: CheckState): boolean {+ return STEP_ORDER.some((id) => check.steps[id] === "run");+}++function StepIcon({ state }: { state: StepState }) {+ const cls = "h-[18px] w-[18px] shrink-0";+ switch (state) {+ case "run":+ return <Loader2 className={cn(cls, "animate-spin text-foreground-secondary")} aria-hidden />;+ case "ok":+ return <CircleCheck className={cn(cls, "text-success")} aria-hidden />;+ case "warn":+ return <CircleAlert className={cn(cls, "text-warning")} aria-hidden />;+ case "fail":+ return <CircleX className={cn(cls, "text-destructive")} aria-hidden />;+ default:+ return <Circle className={cn(cls, "text-foreground-faint")} aria-hidden />;+ }+}++function Fact({ label, children }: { label: string; children: ReactNode }) {+ return (+ <div className="min-w-0">+ <dt className="text-xs text-muted-foreground">{label}</dt>+ <dd className="mt-0.5 truncate text-sm text-foreground-strong">{children}</dd>+ </div>+ );+}++export function ConnectCheck({+ check,+ labels,+ onEdit,+ onRetry,+ onOpen,+}: {+ check: CheckState;+ labels: Record<StepId, string>;+ onEdit: () => void;+ onRetry: () => void;+ onOpen: (computer: Computer, tab: "overview" | "agents") => void;+}) {+ const t = useT();+ const failed = checkFailed(check);+ const running = checkRunning(check);+ const facts = check.facts;+ const computer = check.computer;++ return (+ <div className="space-y-5" data-testid="cx-check">+ <ol className="space-y-1" aria-live="polite">+ {STEP_ORDER.map((id) => {+ const state = check.steps[id];+ return (+ <li+ key={id}+ data-testid={`cx-step-${id}`}+ data-state={state}+ className={cn(+ "flex items-start gap-3 rounded-md px-3 py-2.5",+ state === "fail" && "bg-destructive/10",+ state === "warn" && "bg-warning/10",+ )}+ >+ <span className="mt-px">+ <StepIcon state={state} />+ </span>+ <div className="min-w-0 flex-1">+ <div+ className={cn(+ "text-sm",+ state === "wait" ? "text-muted-foreground" : "text-foreground-strong",+ state === "run" && "font-medium",+ )}+ >+ {labels[id]}+ </div>+ {check.notes[id] && (+ <p role={state === "fail" ? "alert" : undefined} className="mt-0.5 text-sm text-foreground-secondary">+ {check.notes[id]}+ </p>+ )}+ </div>+ </li>+ );+ })}+ </ol>++ {computer && facts && (+ <dl+ className="grid grid-cols-2 gap-x-4 gap-y-3 rounded-lg border border-border bg-secondary/40 p-4"+ data-testid="cx-facts"+ >+ <Fact label={t("computers.fact_hostname")}>+ <span className="font-mono">{facts.hostname ?? computer.host}</span>+ </Fact>+ <Fact label={t("computers.fact_os")}>{facts.os_name ?? facts.os_id ?? "—"}</Fact>+ <Fact label={t("computers.fact_cpu")}>+ {facts.cpu_count ? `${facts.cpu_count} ${t("computers.unit_cpu")}` : "—"}+ {facts.arch ? ` · ${facts.arch}` : ""}+ </Fact>+ <Fact label={t("computers.fact_memory")}>{formatMemory(facts.mem_total_mb) ?? "—"}</Fact>+ {check.latencyMs !== null && (+ <Fact label={t("computers.latency")}>+ <span className="tabular-nums">{Math.round(check.latencyMs)} ms</span>+ </Fact>+ )}+ </dl>+ )}++ {failed && (+ <div className="flex flex-wrap gap-2">+ <Button type="button" variant="outline" onClick={onEdit} data-testid="cx-edit">+ <Wrench />+ {t("computers.cx_edit")}+ </Button>+ <Button type="button" onClick={onRetry} data-testid="cx-retry">+ <RotateCcw />+ {t("computers.cx_retry")}+ </Button>+ </div>+ )}++ {computer && !running && !failed && (+ <div className="flex flex-col gap-2 sm:flex-row">+ <Button type="button" className="sm:flex-1" onClick={() => onOpen(computer, "overview")} data-testid="cx-open">+ {fill(t("computers.wz_open"), { computer: computer.name })}+ <ArrowRight />+ </Button>+ <Button type="button" variant="outline" className="sm:flex-1" onClick={() => onOpen(computer, "agents")}>+ {t("computers.wz_next_agents")}+ </Button>+ </div>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/computers/ConnectDialog.tsx b/jarvis/ui/web/frontend/src/views/computers/ConnectDialog.tsxindex dad87f1bc2..37c42c13b3 100644--- a/jarvis/ui/web/frontend/src/views/computers/ConnectDialog.tsx+++ b/jarvis/ui/web/frontend/src/views/computers/ConnectDialog.tsx@@ -1,38 +1,109 @@/*** "Connect a computer" — one screen, because SSH needs only two things: where- * the server is, and a way in. The easiest way in is the copyable setup- * prompt: a coding agent on that computer installs the assistant's PUBLIC key- * and prints one line to paste back. The paste box also understands a bare IP,- * user@host, a whole ssh command or a block with a private key, so the user- * never has to split anything into fields. The password field appears only- * when nothing pasted says how to log in.+ * the server is, and a way in.+ *+ * The address box understands a bare IP, user@host, a whole ssh command, a+ * block with a private key, or the one line our setup instructions end with,+ * so the user never splits anything into fields. Below it, the way in is an+ * explicit choice of three equal tabs — password, SSH key, or "an agent sets+ * it up" — so no method hides behind a text link. Pasting a key or the agent's+ * line switches the tab by itself.+ *+ * "Connect" does not just spin: it opens a visible check (ConnectCheck) that+ * reaches the server, logs in, runs a test command and only then saves, so a+ * typo never leaves a broken entry behind and a success shows the machine's+ * own facts as proof. A password is used once to plant the assistant's own+ * key and is then forgotten, unless "keep" is ticked.** Two optional doors sit below the form: connect a hosting account to pick* from all its servers (no IP to copy), or create a virtual machine here.- *- * "Connect" tests first and saves only a connection that works, so a typo- * never leaves a broken entry behind. A password is used once to plant the- * assistant's own key and is then forgotten, unless "keep" is ticked.*/-import { useEffect, useMemo, useRef, useState } from "react";-import { ArrowLeft, Check, ChevronDown, Copy, KeyRound, Loader2, MonitorSmartphone, Plug, Sparkles, X } from "lucide-react";+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import {+ ArrowLeft,+ Check,+ ChevronDown,+ Copy,+ FileKey,+ KeyRound,+ Lock,+ MonitorSmartphone,+ Plug,+ SquareTerminal,+ X,+} from "lucide-react";import { Button } from "@/components/ui/button";import { ProviderLogo } from "@/components/providers/ProviderLogo";import { useIdentity, useProviderCatalog, useUpsertComputer } from "@/hooks/useComputers";-import { useT } from "@/i18n";+import { fill, useT } from "@/i18n";import { cn } from "@/lib/utils";import { robustCopy } from "@/lib/clipboard";import { useEventStore } from "@/store/events";import { computersApi, type AddServerInput, type Computer, type ProviderInfo } from "@/lib/computersApi";import { parseConnection, setupPrompt } from "./connection";-import { Field, inputClass } from "./parts";+import { checkFailed, ConnectCheck, startCheck, type CheckState, type StepId } from "./ConnectCheck";+import { CopyField, Field, inputClass } from "./parts";import { ApiImportStep } from "./wizard/ApiImportStep";import { LocalVmStep } from "./wizard/LocalVmStep";-import { ErrorNote, errorText } from "./wizard/shared";+import { errorText } from "./wizard/shared";-type Screen = { kind: "form" } | { kind: "account"; provider: ProviderInfo } | { kind: "vm" };+type Screen = { kind: "form" } | { kind: "check" } | { kind: "account"; provider: ProviderInfo } | { kind: "vm" };+type Method = "password" | "ssh_key" | "agent";+type KeySource = "own" | "assistant";type Login = "password" | "private_key" | "key";+const REACH_FAILURES = new Set(["unreachable", "timeout", "protocol", "host_key_changed"]);++/** One tab of the "how to log in" switch. */+function MethodTab({+ active,+ onClick,+ icon,+ label,+ testId,+}: {+ active: boolean;+ onClick: () => void;+ icon: ReactNode;+ label: string;+ testId: string;+}) {+ return (+ <button+ type="button"+ role="tab"+ aria-selected={active}+ onClick={onClick}+ data-testid={testId}+ className={cn(+ "flex min-w-0 flex-1 items-center justify-center gap-2 rounded-md px-2 py-2 text-sm font-medium transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&>svg]:h-4 [&>svg]:w-4 [&>svg]:shrink-0",+ active+ ? "bg-popover text-foreground-strong shadow-sm ring-1 ring-border"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {icon}+ <span className="truncate">{label}</span>+ </button>+ );+}++/** A numbered instruction row for the agent route. */+function AgentStep({ n, children }: { n: number; children: ReactNode }) {+ return (+ <li className="flex gap-3">+ <span+ aria-hidden+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border-strong text-xs font-medium tabular-nums text-foreground-secondary"+ >+ {n}+ </span>+ <div className="min-w-0 flex-1 pt-0.5 text-sm text-foreground-secondary">{children}</div>+ </li>+ );+}+export function ConnectDialog({onClose,onOpen,@@ -47,7 +118,8 @@ export function ConnectDialog({const [screen, setScreen] = useState<Screen>({ kind: "form" });const assistantName = useEventStore((s) => s.assistantName) || "Jarvis";const [pasted, setPasted] = useState("");- const [manualKey, setManualKey] = useState(false);+ const [method, setMethod] = useState<Method>("password");+ const [keySource, setKeySource] = useState<KeySource>("own");const [password, setPassword] = useState("");const [privateKey, setPrivateKey] = useState("");const [passphrase, setPassphrase] = useState("");@@ -56,9 +128,10 @@ export function ConnectDialog({const [username, setUsername] = useState("");const [port, setPort] = useState("");const [keepPassword, setKeepPassword] = useState(false);- const [busy, setBusy] = useState(false);- const [error, setError] = useState<string | null>(null);+ const [keyError, setKeyError] = useState<string | null>(null);const [promptCopied, setPromptCopied] = useState(false);+ const [showPrompt, setShowPrompt] = useState(false);+ const [check, setCheck] = useState<CheckState | null>(null);const fileInput = useRef<HTMLInputElement>(null);useEffect(() => {@@ -70,22 +143,38 @@ export function ConnectDialog({}, [onClose]);const accounts = useMemo(() => (catalog.data ?? []).filter((p) => p.api), [catalog.data]);- // Everything the paste box understood: address, login, port, a key.+ // Everything the address box understood: address, login, port, a key.const detected = useMemo(() => parseConnection(pasted), [pasted]);const pastedKey = detected.privateKey;- // The login follows what was pasted: a key block wins, then our own setup- // prompt's result (the assistant's key is installed), else the password.- const login: Login = pastedKey || manualKey ? "private_key" : detected.fromSetupPrompt ? "key" : "password";++ // What was pasted picks the tab: a key block means "SSH key", the agent's+ // closing line means the agent route is done.+ useEffect(() => {+ if (pastedKey) {+ setMethod("ssh_key");+ setKeySource("own");+ } else if (detected.fromSetupPrompt) {+ setMethod("agent");+ }+ }, [pastedKey, detected.fromSetupPrompt]);++ const login: Login =+ method === "password" ? "password" : method === "ssh_key" && keySource === "own" ? "private_key" : "key";const effectiveUser = username.trim() || detected.user || "root";const effectivePort = Number(port) || detected.port || 22;const keyText = pastedKey ?? privateKey;const ready =Boolean(detected.host) &&(login === "key" || (login === "password" ? password.length > 0 : keyText.trim().length > 0));+ const plantsKey = login === "password" && !keepPassword;- const finish = (computer: Computer) => {- upsert(computer);- onOpen(computer, "overview");+ const stepLabels: Record<StepId, string> = {+ reach: fill(t("computers.cx_step_reach"), {+ host: `${detected.host ?? ""}${effectivePort !== 22 ? `:${effectivePort}` : ""}`,+ }),+ login: fill(t("computers.cx_step_login"), { user: effectiveUser }),+ probe: t("computers.cx_step_probe"),+ save: plantsKey ? t("computers.cx_step_save_key") : t("computers.cx_step_save"),};async function copyPrompt() {@@ -97,9 +186,7 @@ export function ConnectDialog({}async function connect() {- if (!ready || busy || !detected.host) return;- setBusy(true);- setError(null);+ if (!ready || !detected.host) return;const input: AddServerInput = {name: name.trim() || detected.host,host: detected.host,@@ -112,29 +199,84 @@ export function ConnectDialog({passphrase: login === "private_key" && passphrase ? passphrase : undefined,provider: "generic",};+ let state = startCheck();+ const show = (next: CheckState) => {+ state = next;+ setCheck(next);+ };+ show(state);+ setScreen({ kind: "check" });++ // Steps 1-3: a dry-run login that saves and plants nothing.try {const test = await computersApi.test(input);if (!test.ok) {- setError(test.message || t(`computers.cx_fail_${test.kind ?? "protocol"}`));+ const note = test.message || t(`computers.cx_fail_${test.kind ?? "protocol"}`);+ const atReach = !test.kind || REACH_FAILURES.has(test.kind);+ show({+ ...state,+ steps: atReach+ ? { reach: "fail", login: "wait", probe: "wait", save: "wait" }+ : { reach: "ok", login: "fail", probe: "wait", save: "wait" },+ notes: { [atReach ? "reach" : "login"]: note },+ });return;}- finish(await computersApi.add(input));+ show({+ ...state,+ steps: { reach: "ok", login: "ok", probe: test.facts ? "ok" : "warn", save: "run" },+ notes: test.facts ? {} : { probe: t("computers.cx_step_probe_warn") },+ facts: test.facts,+ latencyMs: test.latency_ms,+ });} catch (e) {- setError(errorText(e));- } finally {- setBusy(false);+ show({ ...state, steps: { ...state.steps, reach: "fail" }, notes: { reach: errorText(e) } });+ return;+ }++ // Step 4: save for real (and plant the key when a password was used).+ try {+ const computer = await computersApi.add(input);+ upsert(computer);+ const healthy = computer.health.status === "online";+ show({+ ...state,+ steps: { ...state.steps, save: healthy ? "ok" : "warn" },+ notes: healthy+ ? state.notes+ : { ...state.notes, save: computer.health.message || t("computers.cx_step_save_warn") },+ facts: state.facts ?? computer.facts,+ latencyMs: state.latencyMs ?? computer.health.latency_ms,+ computer,+ });+ } catch (e) {+ show({ ...state, steps: { ...state.steps, save: "fail" }, notes: { ...state.notes, save: errorText(e) } });}}async function pickKeyFile(file: File | undefined) {if (!file) return;if (file.size > 64 * 1024) {- setError(t("computers.cx_key_too_big"));+ setKeyError(t("computers.cx_key_too_big"));return;}+ setKeyError(null);setPrivateKey(await file.text());}+ const title =+ screen.kind === "account"+ ? t("computers.cx_account_title").replace("{provider}", screen.provider.name)+ : screen.kind === "vm"+ ? t("computers.cx_vm_title")+ : screen.kind === "check"+ ? check?.computer+ ? fill(t("computers.wz_done_title"), { computer: check.computer.name })+ : check && checkFailed(check)+ ? t("computers.cx_check_failed")+ : t("computers.cx_check_title")+ : t("computers.cx_title");+return (<div className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/50 p-4 backdrop-blur-sm"><div@@ -145,7 +287,7 @@ export function ConnectDialog({className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden rounded-xl border border-border bg-popover shadow-float"><header className="flex items-start gap-3 border-b border-border px-6 py-5">- {screen.kind !== "form" && (+ {screen.kind !== "form" && !(screen.kind === "check" && check?.computer) && (<buttontype="button"onClick={() => setScreen({ kind: "form" })}@@ -156,16 +298,13 @@ export function ConnectDialog({</button>)}<div className="min-w-0 flex-1">- <h2 className="text-lg font-semibold text-foreground-strong">- {screen.kind === "account"- ? t("computers.cx_account_title").replace("{provider}", screen.provider.name)- : screen.kind === "vm"- ? t("computers.cx_vm_title")- : t("computers.cx_title")}- </h2>+ <h2 className="text-lg font-semibold text-foreground-strong">{title}</h2>{screen.kind === "form" && (<p className="mt-0.5 text-sm text-muted-foreground">{t("computers.cx_subtitle")}</p>)}+ {screen.kind === "check" && check?.computer && (+ <p className="mt-0.5 text-sm text-muted-foreground">{t("computers.cx_verified_body")}</p>+ )}</div><buttontype="button"@@ -182,11 +321,31 @@ export function ConnectDialog({<ApiImportStepprovider={screen.provider}onBack={() => setScreen({ kind: "form" })}- onAdded={finish}+ onAdded={(computer) => {+ upsert(computer);+ onOpen(computer, "overview");+ }}onProviderChanged={() => void catalog.refetch()}/>)}- {screen.kind === "vm" && <LocalVmStep onBack={() => setScreen({ kind: "form" })} onAdded={finish} />}+ {screen.kind === "vm" && (+ <LocalVmStep+ onBack={() => setScreen({ kind: "form" })}+ onAdded={(computer) => {+ upsert(computer);+ onOpen(computer, "overview");+ }}+ />+ )}+ {screen.kind === "check" && check && (+ <ConnectCheck+ check={check}+ labels={stepLabels}+ onEdit={() => setScreen({ kind: "form" })}+ onRetry={() => void connect()}+ onOpen={onOpen}+ />+ )}{screen.kind === "form" && (<form@@ -196,154 +355,289 @@ export function ConnectDialog({void connect();}}>- <div className="rounded-lg border border-border bg-secondary/40 p-4" data-testid="cx-setup">- <div className="flex items-start gap-3">- <Sparkles className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />- <div className="min-w-0 flex-1">- <div className="text-sm font-medium text-foreground-strong">{t("computers.cx_setup_title")}</div>- <p className="mt-0.5 text-xs text-muted-foreground">{t("computers.cx_setup_body")}</p>+ <div>+ <Field label={t("computers.cx_paste")} hint={t("computers.cx_paste_hint")}>+ <textarea+ className={cn(inputClass, "h-auto min-h-[40px] resize-none py-2 font-mono text-sm")}+ rows={pasted.includes("\n") ? 4 : 1}+ value={pasted}+ onChange={(e) => setPasted(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey && !pasted.includes("\n")) {+ e.preventDefault();+ void connect();+ }+ }}+ placeholder="203.0.113.10"+ autoFocus+ spellCheck={false}+ autoComplete="off"+ data-testid="cx-address"+ />+ </Field>+ {detected.host && (+ <div className="mt-2 flex flex-wrap items-center gap-1.5 text-xs" data-testid="cx-detected">+ <span className="text-muted-foreground">{t("computers.cx_detected")}</span>+ <span className="rounded bg-secondary px-1.5 py-0.5 font-mono text-foreground-secondary">+ {effectiveUser}@{detected.host}+ {effectivePort !== 22 ? `:${effectivePort}` : ""}+ </span>+ {pastedKey && (+ <span className="inline-flex items-center gap-1 rounded bg-success/15 px-1.5 py-0.5 text-success">+ <KeyRound className="h-3 w-3" aria-hidden />+ {t("computers.cx_key_found")}+ </span>+ )}</div>- <Button- type="button"- variant="outline"- size="sm"- disabled={!identity.data}- onClick={() => void copyPrompt()}- data-testid="cx-copy-prompt"- >- {promptCopied ? <Check className="text-success" /> : <Copy />}- {promptCopied ? t("computers.copied") : t("computers.cx_setup_copy")}- </Button>- </div>+ )}</div>- <Field label={t("computers.cx_paste")} hint={t("computers.cx_paste_hint")}>- <textarea- className={cn(inputClass, "h-auto min-h-[40px] resize-none py-2 font-mono text-sm")}- rows={pasted.includes("\n") ? 4 : 1}- value={pasted}- onChange={(e) => setPasted(e.target.value)}- placeholder="203.0.113.10"- autoFocus- spellCheck={false}- autoComplete="off"- data-testid="cx-address"- />- </Field>+ <div>+ <div className="mb-1.5 text-sm font-medium text-foreground-secondary" id="cx-login-label">+ {t("computers.cx_login_title")}+ </div>+ <div+ role="tablist"+ aria-labelledby="cx-login-label"+ className="flex gap-1 rounded-lg bg-secondary p-1"+ >+ <MethodTab+ active={method === "password"}+ onClick={() => setMethod("password")}+ icon={<Lock />}+ label={t("computers.cx_method_password")}+ testId="cx-method-password"+ />+ <MethodTab+ active={method === "ssh_key"}+ onClick={() => setMethod("ssh_key")}+ icon={<KeyRound />}+ label={t("computers.cx_method_key")}+ testId="cx-method-key"+ />+ <MethodTab+ active={method === "agent"}+ onClick={() => setMethod("agent")}+ icon={<SquareTerminal />}+ label={t("computers.cx_method_agent")}+ testId="cx-method-agent"+ />+ </div>- {detected.host && (- <div className="flex flex-wrap items-center gap-1.5 text-xs" data-testid="cx-detected">- <span className="text-muted-foreground">{t("computers.cx_detected")}</span>- <span className="rounded bg-secondary px-1.5 py-0.5 font-mono text-foreground-secondary">- {effectiveUser}@{detected.host}- {effectivePort !== 22 ? `:${effectivePort}` : ""}- </span>- {login === "private_key" && (- <span className="inline-flex items-center gap-1 rounded bg-success/15 px-1.5 py-0.5 text-success">- <KeyRound className="h-3 w-3" aria-hidden />- {t("computers.cx_key_found")}- </span>+ <div className="mt-4" role="tabpanel">+ {method === "password" && (+ <div className="space-y-3">+ <Field label={t("computers.cx_password")} hint={t("computers.cx_password_hint")}>+ <input+ type="password"+ className={cn(inputClass, "h-10")}+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ autoComplete="new-password"+ data-testid="cx-password"+ />+ </Field>+ <label className="flex items-center gap-2 text-sm text-foreground-secondary">+ <input+ type="checkbox"+ checked={keepPassword}+ onChange={(e) => setKeepPassword(e.target.checked)}+ className="h-4 w-4"+ />+ {t("computers.cx_keep_password")}+ </label>+ </div>)}- {login === "key" && (- <span className="inline-flex items-center gap-1 rounded bg-success/15 px-1.5 py-0.5 text-success">- <Check className="h-3 w-3" aria-hidden />- {t("computers.cx_setup_done")}- </span>- )}- </div>- )}- {login === "password" && (- <Field label={t("computers.cx_password")} hint={t("computers.cx_password_hint")}>- <input- type="password"- className={cn(inputClass, "h-10")}- value={password}- onChange={(e) => setPassword(e.target.value)}- autoComplete="new-password"- data-testid="cx-password"- />- </Field>- )}+ {method === "ssh_key" && (+ <div className="space-y-4">+ <div role="radiogroup" className="grid grid-cols-2 gap-2">+ {(["own", "assistant"] as const).map((source) => (+ <button+ key={source}+ type="button"+ role="radio"+ aria-checked={keySource === source}+ onClick={() => setKeySource(source)}+ data-testid={`cx-key-${source}`}+ className={cn(+ "rounded-md border px-3 py-2 text-left text-sm transition-colors",+ keySource === source+ ? "border-accent bg-accent-soft text-foreground-strong"+ : "border-border text-foreground-secondary hover:border-border-strong",+ )}+ >+ <span className="block font-medium">+ {source === "own" ? t("computers.cx_key_own") : t("computers.cx_key_assistant")}+ </span>+ <span className="mt-0.5 block text-xs text-muted-foreground">+ {source === "own"+ ? t("computers.cx_key_own_body")+ : t("computers.cx_key_assistant_body")}+ </span>+ </button>+ ))}+ </div>- {manualKey && login === "private_key" && !pastedKey && (- <div className="space-y-3">- <Field label={t("computers.cx_private_key")} hint={t("computers.cx_private_key_hint")}>- <textarea- className={cn(inputClass, "h-24 resize-none py-2 font-mono text-xs")}- value={privateKey}- onChange={(e) => setPrivateKey(e.target.value)}- placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"- spellCheck={false}- data-testid="cx-private-key"- />- </Field>- <Button type="button" variant="outline" size="sm" onClick={() => fileInput.current?.click()}>- {t("computers.cx_key_file")}- </Button>- <input ref={fileInput} type="file" className="hidden" onChange={(e) => void pickKeyFile(e.target.files?.[0])} />- </div>- )}+ {keySource === "own" && pastedKey && (+ <p className="flex items-center gap-2 text-sm text-foreground-secondary">+ <Check className="h-4 w-4 text-success" aria-hidden />+ {t("computers.cx_key_from_paste")}+ </p>+ )}- {login === "private_key" && (- <input- type="password"- className={cn(inputClass, "h-9 text-sm")}- value={passphrase}- onChange={(e) => setPassphrase(e.target.value)}- placeholder={t("computers.cx_passphrase")}- aria-label={t("computers.cx_passphrase")}- autoComplete="off"- />- )}+ {keySource === "own" && !pastedKey && (+ <div className="space-y-2">+ <Field label={t("computers.cx_private_key")} hint={t("computers.cx_private_key_hint")}>+ <textarea+ className={cn(inputClass, "h-24 resize-none py-2 font-mono text-xs")}+ value={privateKey}+ onChange={(e) => setPrivateKey(e.target.value)}+ placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"+ spellCheck={false}+ data-testid="cx-private-key"+ />+ </Field>+ <Button type="button" variant="outline" size="sm" onClick={() => fileInput.current?.click()}>+ <FileKey />+ {t("computers.cx_key_file")}+ </Button>+ <input+ ref={fileInput}+ type="file"+ className="hidden"+ onChange={(e) => void pickKeyFile(e.target.files?.[0])}+ />+ {keyError && (+ <p role="alert" className="text-sm text-destructive">+ {keyError}+ </p>+ )}+ </div>+ )}- <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">- {!pastedKey && !detected.fromSetupPrompt && (- <button- type="button"- onClick={() => setManualKey((v) => !v)}- className="text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"- >- {manualKey ? t("computers.cx_use_password") : t("computers.cx_have_key")}- </button>- )}+ {keySource === "own" && (+ <input+ type="password"+ className={cn(inputClass, "h-9 text-sm")}+ value={passphrase}+ onChange={(e) => setPassphrase(e.target.value)}+ placeholder={t("computers.cx_passphrase")}+ aria-label={t("computers.cx_passphrase")}+ autoComplete="off"+ />+ )}++ {keySource === "assistant" && identity.data && (+ <div className="space-y-2" data-testid="cx-assistant-key">+ <CopyField+ value={identity.data.public_key}+ label={t("computers.jarvis_key")}+ copyLabel={t("computers.copy")}+ copiedLabel={t("computers.copied")}+ />+ <p className="text-xs text-muted-foreground">{t("computers.cx_key_assistant_hint")}</p>+ </div>+ )}+ </div>+ )}++ {method === "agent" && (+ <div className="space-y-4" data-testid="cx-agent">+ {detected.fromSetupPrompt ? (+ <p className="flex items-start gap-2 rounded-md bg-success/10 px-3 py-2.5 text-sm text-foreground">+ <Check className="mt-0.5 h-4 w-4 shrink-0 text-success" aria-hidden />+ {t("computers.cx_agent_done")}+ </p>+ ) : (+ <ol className="space-y-3">+ <AgentStep n={1}>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">+ <span>{t("computers.cx_agent_step1")}</span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={!identity.data}+ onClick={() => void copyPrompt()}+ data-testid="cx-copy-prompt"+ >+ {promptCopied ? <Check className="text-success" /> : <Copy />}+ {promptCopied ? t("computers.copied") : t("computers.cx_agent_copy")}+ </Button>+ <button+ type="button"+ onClick={() => setShowPrompt((v) => !v)}+ aria-expanded={showPrompt}+ className="text-xs text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"+ >+ {showPrompt ? t("computers.cx_agent_hide") : t("computers.cx_agent_show")}+ </button>+ </div>+ {showPrompt && identity.data && (+ <pre className="mt-2 max-h-48 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-raised p-3 font-mono text-xs text-foreground-secondary scrollbar-jarvis">+ {setupPrompt(assistantName, identity.data.public_key)}+ </pre>+ )}+ </AgentStep>+ <AgentStep n={2}>{t("computers.cx_agent_step2")}</AgentStep>+ <AgentStep n={3}>{t("computers.cx_agent_step3")}</AgentStep>+ </ol>+ )}+ </div>+ )}+ </div>+ </div>++ <div><buttontype="button"onClick={() => setMore((v) => !v)}aria-expanded={more}- className="inline-flex items-center gap-1 text-muted-foreground hover:text-foreground"+ className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"><ChevronDown className={cn("h-3.5 w-3.5 transition-transform", more && "rotate-180")} aria-hidden />{t("computers.cx_more")}</button>+ {more && (+ <div className="mt-3 grid gap-3 sm:grid-cols-[minmax(0,1fr)_110px_80px]">+ <Field label={t("computers.field_name")}>+ <input+ className={inputClass}+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={detected.host || t("computers.field_name_placeholder")}+ />+ </Field>+ <Field label={t("computers.field_username")}>+ <input+ className={cn(inputClass, "font-mono")}+ value={username}+ onChange={(e) => setUsername(e.target.value)}+ placeholder={detected.user || "root"}+ spellCheck={false}+ />+ </Field>+ <Field label={t("computers.field_port")}>+ <input+ className={cn(inputClass, "font-mono")}+ value={port}+ inputMode="numeric"+ onChange={(e) => setPort(e.target.value.replace(/[^0-9]/g, ""))}+ placeholder={String(detected.port ?? 22)}+ />+ </Field>+ </div>+ )}</div>- {more && (- <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_110px_80px]">- <Field label={t("computers.field_name")}>- <input className={inputClass} value={name} onChange={(e) => setName(e.target.value)} placeholder={detected.host || t("computers.field_name_placeholder")} />- </Field>- <Field label={t("computers.field_username")}>- <input className={cn(inputClass, "font-mono")} value={username} onChange={(e) => setUsername(e.target.value)} placeholder={detected.user || "root"} spellCheck={false} />- </Field>- <Field label={t("computers.field_port")}>- <input className={cn(inputClass, "font-mono")} value={port} inputMode="numeric" onChange={(e) => setPort(e.target.value.replace(/[^0-9]/g, ""))} placeholder={String(detected.port ?? 22)} />- </Field>- {login === "password" && (- <label className="col-span-full flex items-center gap-2 text-sm text-foreground-secondary">- <input type="checkbox" checked={keepPassword} onChange={(e) => setKeepPassword(e.target.checked)} className="h-4 w-4" />- {t("computers.cx_keep_password")}- </label>- )}- </div>- )}-- <ErrorNote message={error} />-- <Button type="submit" className="h-10 w-full" disabled={!ready || busy} data-testid="cx-connect">- {busy ? <Loader2 className="animate-spin" /> : <Plug />}- {busy ? t("computers.connecting") : t("computers.cx_connect")}- </Button>+ <div>+ <Button type="submit" className="h-10 w-full" disabled={!ready} data-testid="cx-connect">+ <Plug />+ {t("computers.cx_connect")}+ </Button>+ <p className="mt-2 text-center text-xs text-muted-foreground">{t("computers.cx_connect_hint")}</p>+ </div></form>)}</div>