Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Batch 9 UI: "Sign in with Claude" in Settings → Engines

Lin (kwant bot)3fd2eda60b7c
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index c1d43df8..7e6e5a4d 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -137,6 +137,16 @@ export const App: React.FC = () => {
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
// Bumped when Settings closes, so open kwant forms read engine status again.
const [settingsClosedCount, setSettingsClosedCount] = useState(0);
+ // Set when Settings opens from a "Sign in with Claude" hint, to focus that button.
+ const [claudeSignInFocus, setClaudeSignInFocus] = useState(0);
+ const openSettings = () => {
+ setClaudeSignInFocus(0);
+ setIsSettingsOpen(true);
+ };
+ const openClaudeSignIn = () => {
+ setClaudeSignInFocus(Date.now());
+ setIsSettingsOpen(true);
+ };
const [isMcpOpen, setIsMcpOpen] = useState(false);
const [isProfilesOpen, setIsProfilesOpen] = useState(false);
const [isSearchOpen, setIsSearchOpen] = useState(false);
@@ -1808,7 +1818,7 @@ export const App: React.FC = () => {
<div className="h-screen w-screen flex flex-col bg-zinc-950 text-zinc-100 overflow-hidden font-sans">
{/* Modern App Header */}
<AppHeader
- onOpenSettings={() => setIsSettingsOpen(true)}
+ onOpenSettings={openSettings}
onOpenTools={() => setIsMcpOpen(true)}
onOpenSearch={() => setIsSearchOpen(true)}
onOpenRoutines={() => setIsRoutinesOpen(true)}
@@ -1819,7 +1829,8 @@ export const App: React.FC = () => {
{/* Main Workspace Shell */}
<div className="flex-1 flex overflow-hidden">
<Sidebar
- onOpenSettings={() => setIsSettingsOpen(true)}
+ onOpenSettings={openSettings}
+ onSignInClaude={openClaudeSignIn}
enginesRefreshKey={settingsClosedCount}
kwants={kwants}
channels={channels}
@@ -1950,7 +1961,8 @@ export const App: React.FC = () => {
profiles={profiles}
onManageProfiles={() => setIsProfilesOpen(true)}
onManageServers={() => setIsMcpOpen(true)}
- onOpenSettings={() => setIsSettingsOpen(true)}
+ onOpenSettings={openSettings}
+ onSignInClaude={openClaudeSignIn}
enginesRefreshKey={settingsClosedCount}
onSubmit={handleCreateAgent}
/>
@@ -1965,7 +1977,8 @@ export const App: React.FC = () => {
profiles={profiles}
onManageProfiles={() => setIsProfilesOpen(true)}
onManageServers={() => setIsMcpOpen(true)}
- onOpenSettings={() => setIsSettingsOpen(true)}
+ onOpenSettings={openSettings}
+ onSignInClaude={openClaudeSignIn}
enginesRefreshKey={settingsClosedCount}
initialTab={editingTab}
pendingSkills={editingKwant ? pendingSkillCounts[editingKwant.id] ?? 0 : 0}
@@ -1996,6 +2009,7 @@ export const App: React.FC = () => {
<Suspense fallback={null}>
<SettingsModal
isOpen={isSettingsOpen}
+ focusClaudeSignIn={claudeSignInFocus}
onClose={() => {
setIsSettingsOpen(false);
setSettingsClosedCount((n) => n + 1);
diff --git a/frontend/src/claudeLogin.ts b/frontend/src/claudeLogin.ts
new file mode 100644
index 00000000..c979723f
--- /dev/null
+++ b/frontend/src/claudeLogin.ts
@@ -0,0 +1,88 @@
+// "Sign in with Claude" for the Claude engine: the server runs Claude Code's own `auth login`,
+// we open the claude.ai link it prints and send back the code claude.ai shows. The UI never sees a
+// token; the code only ever goes in a POST body.
+
+import type { EngineInfo } from './engines';
+
+export type ClaudeLoginState = 'starting' | 'waiting_for_code' | 'verifying' | 'done' | 'failed' | 'expired' | 'cancelled';
+
+/** Shaped like SessionView in src/server/engine_login.rs. */
+export interface ClaudeLoginSession {
+ session_id: string;
+ state: ClaudeLoginState;
+ detail: string | null;
+ /** The claude.ai link; null once the sign-in has finished. */
+ url: string | null;
+ expires_at: string;
+}
+
+export class ClaudeLoginError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ /** On 409: the sign-in that's already running. */
+ readonly sessionId: string | null = null,
+ ) {
+ super(message);
+ }
+}
+
+const BASE = '/api/engines/claude';
+
+async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
+ let r: Response;
+ try {
+ r = await fetch(`${BASE}${path}`, {
+ method,
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch {
+ throw new ClaudeLoginError('Couldn’t reach the server.', 0);
+ }
+ if (r.status === 204) return undefined as T;
+ const d = await r.json().catch(() => null);
+ if (!r.ok) {
+ const msg = typeof d?.error === 'string' && d.error ? d.error : `HTTP ${r.status}`;
+ throw new ClaudeLoginError(msg, r.status, typeof d?.session_id === 'string' ? d.session_id : null);
+ }
+ return d as T;
+}
+
+export const claudeLoginApi = {
+ start: () => request<ClaudeLoginSession>('POST', '/login'),
+ get: (sid: string) => request<ClaudeLoginSession>('GET', `/login/${encodeURIComponent(sid)}`),
+ submitCode: (sid: string, code: string) => request<ClaudeLoginSession>('POST', `/login/${encodeURIComponent(sid)}/code`, { code }),
+ cancel: (sid: string) => request<void>('DELETE', `/login/${encodeURIComponent(sid)}`),
+ logout: () => request<{ engines: EngineInfo[] }>('POST', '/logout'),
+};
+
+/** Still going: the CLI is waiting for a code or checking one. */
+export const isLoginActive = (s: ClaudeLoginState) => s === 'starting' || s === 'waiting_for_code' || s === 'verifying';
+
+/** What to tell the user when a sign-in ended without signing in; null when there's nothing to say. */
+export function loginFailure(s: Pick<ClaudeLoginSession, 'state' | 'detail'>): string | null {
+ switch (s.state) {
+ case 'failed':
+ return s.detail || 'Sign-in failed. Start it again.';
+ case 'expired':
+ return s.detail || 'Sign-in timed out. Start it again.';
+ default:
+ return null;
+ }
+}
+
+/** Only https links to Anthropic's own sign-in pages are opened. */
+export function isClaudeSignInUrl(url: string | null | undefined): url is string {
+ if (!url) return false;
+ try {
+ const u = new URL(url);
+ return u.protocol === 'https:' && /(^|\.)(claude\.ai|claude\.com|anthropic\.com)$/.test(u.hostname);
+ } catch {
+ return false;
+ }
+}
+
+/** The Claude Code CLI is installed and switched on but signed out, so "Sign in with Claude" fixes it. */
+export const claudeNeedsSignIn = (engines: EngineInfo[] | null | undefined) =>
+ !!engines?.some((e) => e.id === 'claude' && e.enabled !== false && e.status === 'signed_out');
diff --git a/frontend/src/components/ClaudeSignIn.tsx b/frontend/src/components/ClaudeSignIn.tsx
new file mode 100644
index 00000000..e45a7fb5
--- /dev/null
+++ b/frontend/src/components/ClaudeSignIn.tsx
@@ -0,0 +1,393 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { AlertTriangle, ExternalLink, Loader2, LogIn, LogOut, RotateCcw } from 'lucide-react';
+import { ClaudeLoginError, ClaudeLoginSession, claudeLoginApi, isClaudeSignInUrl, isLoginActive, loginFailure } from '../claudeLogin';
+import type { EngineInfo } from '../engines';
+import { playSfx } from '../audio/chiptune';
+
+const POLL_MS = 2000;
+
+const primaryBtn =
+ 'inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-sky-600 hover:bg-sky-500 disabled:opacity-50 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
+const quietBtn =
+ 'inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[11px] font-medium text-zinc-300 border border-zinc-700 hover:text-zinc-100 hover:border-zinc-500 disabled:opacity-50 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
+const link = 'inline-flex items-center gap-1 font-medium text-sky-300 underline underline-offset-2 hover:text-sky-200';
+
+/** A blank tab opened while the click still counts as a user gesture, so popup blockers allow it.
+ * `noopener` would make window.open return null, so the opener is cut by hand before navigating. */
+function openBlankTab(): Window | null {
+ try {
+ const tab = window.open('about:blank', '_blank');
+ if (tab) tab.opener = null;
+ return tab;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The Claude row's "Sign in with Claude": starts Claude Code's sign-in on the server, opens the
+ * claude.ai link in a new tab and takes the code claude.ai shows back. `onSignedIn` runs once the
+ * server has re-checked Claude, so reloading the engines shows it Ready.
+ */
+export const ClaudeSignIn: React.FC<{ onSignedIn: () => void; focusRequest?: number }> = ({ onSignedIn, focusRequest }) => {
+ const [session, setSession] = useState<ClaudeLoginSession | null>(null);
+ const [code, setCode] = useState('');
+ const [busy, setBusy] = useState<'start' | 'code' | 'cancel' | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ /** The new tab didn't open: show the link instead. */
+ const [blocked, setBlocked] = useState(false);
+ const tab = useRef<Window | null>(null);
+ const startRef = useRef<HTMLButtonElement>(null);
+ const codeRef = useRef<HTMLInputElement>(null);
+ const retryRef = useRef<HTMLButtonElement>(null);
+ const alive = useRef(true);
+ useEffect(() => {
+ alive.current = true;
+ return () => void (alive.current = false);
+ }, []);
+
+ const state = session?.state ?? null;
+ const active = state !== null && isLoginActive(state);
+
+ /** Sends the blank tab to the link once there is one; once only. */
+ const showLink = useCallback((s: ClaudeLoginSession) => {
+ const t = tab.current;
+ if (!t || !isClaudeSignInUrl(s.url)) return;
+ tab.current = null;
+ if (t.closed) setBlocked(true);
+ else t.location.replace(s.url);
+ }, []);
+
+ const start = async () => {
+ playSfx('click');
+ const t = openBlankTab();
+ tab.current = t;
+ setBlocked(!t);
+ setBusy('start');
+ setError(null);
+ setCode('');
+ try {
+ let s: ClaudeLoginSession;
+ try {
+ s = await claudeLoginApi.start();
+ } catch (e) {
+ // One is already running (another tab, or before Settings was closed): carry on with it.
+ if (e instanceof ClaudeLoginError && e.status === 409 && e.sessionId) s = await claudeLoginApi.get(e.sessionId);
+ else throw e;
+ }
+ if (!alive.current) return;
+ setSession(s);
+ if (isLoginActive(s.state)) showLink(s);
+ else t?.close();
+ } catch (e) {
+ t?.close();
+ tab.current = null;
+ if (alive.current) setError(e instanceof Error ? e.message : 'Couldn’t start the sign-in.');
+ } finally {
+ if (alive.current) setBusy(null);
+ }
+ };
+
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ const c = code.trim();
+ if (!session || !c || busy) return;
+ playSfx('click');
+ setBusy('code');
+ setError(null);
+ setSession({ ...session, state: 'verifying' });
+ try {
+ const s = await claudeLoginApi.submitCode(session.session_id, c);
+ if (!alive.current) return;
+ setCode('');
+ setSession(s);
+ } catch (err) {
+ if (!alive.current) return;
+ if (err instanceof ClaudeLoginError && err.status === 404) {
+ setCode('');
+ setSession({ ...session, state: 'expired', detail: 'This sign-in has stopped. Start it again.' });
+ } else {
+ // A malformed code: the sign-in is still waiting for a good one.
+ setSession({ ...session, state: 'waiting_for_code' });
+ setError(err instanceof Error ? err.message : 'Couldn’t send the code.');
+ }
+ } finally {
+ if (alive.current) setBusy(null);
+ }
+ };
+
+ const cancel = async () => {
+ if (!session) return;
+ playSfx('click');
+ setBusy('cancel');
+ setError(null);
+ try {
+ await claudeLoginApi.cancel(session.session_id);
+ } catch (err) {
+ // Already gone is as good as cancelled.
+ if (!(err instanceof ClaudeLoginError && err.status === 404)) {
+ if (alive.current) setError(err instanceof Error ? err.message : 'Couldn’t cancel the sign-in.');
+ if (alive.current) setBusy(null);
+ return;
+ }
+ }
+ tab.current?.close();
+ tab.current = null;
+ if (!alive.current) return;
+ setBusy(null);
+ setSession(null);
+ setCode('');
+ setBlocked(false);
+ // Focus goes back to where it started.
+ requestAnimationFrame(() => startRef.current?.focus());
+ };
+
+ // While it's running, look again: it can time out, or finish from another tab.
+ useEffect(() => {
+ if (!session || !active || busy) return;
+ const sid = session.session_id;
+ const t = window.setTimeout(async () => {
+ try {
+ const s = await claudeLoginApi.get(sid);
+ if (!alive.current) return;
+ setSession((cur) => (cur?.session_id === sid ? s : cur));
+ if (s.state === 'waiting_for_code') showLink(s);
+ } catch (err) {
+ if (alive.current && err instanceof ClaudeLoginError && err.status === 404) {
+ setSession((cur) => (cur?.session_id === sid ? { ...cur, state: 'expired', detail: 'This sign-in has stopped. Start it again.' } : cur));
+ }
+ // Anything else: try again next time.
+ }
+ }, POLL_MS);
+ return () => window.clearTimeout(t);
+ }, [session, active, busy, showLink]);
+
+ // Done: the server has re-checked Claude already.
+ const doneFor = useRef<string | null>(null);
+ useEffect(() => {
+ if (session?.state === 'done' && doneFor.current !== session.session_id) {
+ doneFor.current = session.session_id;
+ playSfx('coin');
+ onSignedIn();
+ }
+ }, [session, onSignedIn]);
+
+ // Focus follows the step: the code box once the link is out, Try again after a failure.
+ useEffect(() => {
+ if (state === 'waiting_for_code' && busy === null) codeRef.current?.focus();
+ if (state === 'failed' || state === 'expired') retryRef.current?.focus();
+ }, [state, busy]);
+
+ // "Sign in with Claude" from a warning elsewhere: bring the button into view and focus it.
+ useEffect(() => {
+ if (!focusRequest) return;
+ const b = startRef.current;
+ if (!b) return;
+ b.scrollIntoView?.({ block: 'center', behavior: 'smooth' });
+ b.focus({ preventScroll: true });
+ }, [focusRequest]);
+
+ const failure = session ? loginFailure(session) : null;
+ const showStart = !session || state === 'cancelled';
+ const url = session && isClaudeSignInUrl(session.url) ? session.url : null;
+
+ return (
+ <div className="mt-2 space-y-2" data-login-state={state ?? 'idle'}>
+ {showStart && (
+ <div className="flex items-center gap-2 flex-wrap">
+ <button ref={startRef} type="button" onClick={start} disabled={busy === 'start'} className={primaryBtn}>
+ {busy === 'start' ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <LogIn size={12} aria-hidden="true" />}
+ {busy === 'start' ? 'Starting…' : 'Sign in with Claude'}
+ </button>
+ <span className="text-[10.5px] text-zinc-500">Opens claude.ai in a new tab.</span>
+ </div>
+ )}
+
+ {state === 'starting' && (
+ <div className="flex items-center gap-2 flex-wrap">
+ <p className="flex items-center gap-1.5 text-[11px] text-zinc-300" role="status">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Starting Claude Code’s sign-in…
+ </p>
+ <button type="button" onClick={cancel} disabled={busy === 'cancel'} className={quietBtn}>
+ Cancel
+ </button>
+ </div>
+ )}
+
+ {(state === 'waiting_for_code' || state === 'verifying') && session && (
+ <form onSubmit={submit} className="rounded-lg border border-sky-500/30 bg-sky-500/5 p-2.5 space-y-2">
+ <p id={`claude-code-help-${session.session_id}`} className="text-[11px] text-zinc-200 leading-snug">
+ Finish signing in on claude.ai, then paste the code it shows you here.
+ </p>
+ {url && (
+ <p className="text-[11px] text-zinc-400">
+ {blocked ? 'Your browser didn’t open a new tab. ' : 'Closed the tab? '}
+ <a href={url} target="_blank" rel="noopener noreferrer" className={link} onClick={() => setBlocked(false)}>
+ {blocked ? 'Open claude.ai to sign in' : 'Open claude.ai again'} <ExternalLink size={10} aria-hidden="true" />
+ </a>
+ </p>
+ )}
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <label htmlFor={`claude-code-${session.session_id}`} className="sr-only">
+ Code from claude.ai
+ </label>
+ <input
+ ref={codeRef}
+ id={`claude-code-${session.session_id}`}
+ aria-describedby={`claude-code-help-${session.session_id}`}
+ autoComplete="off"
+ autoCapitalize="off"
+ autoCorrect="off"
+ spellCheck={false}
+ value={code}
+ onChange={(e) => setCode(e.target.value)}
+ readOnly={state === 'verifying'}
+ placeholder="Paste the code"
+ className="flex-1 min-w-[10rem] bg-zinc-950 border border-zinc-700 rounded-md px-2 py-1 text-[11px] font-mono text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus:border-sky-500 select-text"
+ />
+ <button type="submit" disabled={state === 'verifying' || !code.trim()} className={primaryBtn}>
+ {state === 'verifying' && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {state === 'verifying' ? 'Checking…' : 'Finish sign-in'}
+ </button>
+ <button type="button" onClick={cancel} disabled={busy === 'cancel' || busy === 'code'} className={quietBtn}>
+ Cancel
+ </button>
+ </div>
+ <p className="sr-only" role="status">
+ {state === 'verifying' ? 'Checking the code with Claude…' : ''}
+ </p>
+ </form>
+ )}
+
+ {state === 'done' && (
+ <p className="flex items-center gap-1.5 text-[11px] text-emerald-300" role="status">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Signed in. Updating…
+ </p>
+ )}
+
+ {failure && (
+ <div className="flex items-center gap-2 flex-wrap">
+ <p className="flex items-center gap-1.5 text-[11px] text-rose-300" role="alert">
+ <AlertTriangle size={12} className="shrink-0" aria-hidden="true" /> {failure}
+ </p>
+ <button ref={retryRef} type="button" onClick={start} disabled={busy === 'start'} className={quietBtn}>
+ <RotateCcw size={11} aria-hidden="true" /> Try again
+ </button>
+ </div>
+ )}
+
+ {error && (
+ <p className="flex items-center gap-1.5 text-[11px] text-rose-300" role="alert">
+ <AlertTriangle size={12} className="shrink-0" aria-hidden="true" /> {error}
+ </p>
+ )}
+ </div>
+ );
+};
+
+/** "Sign out" on a Ready Claude row, behind a confirm dialog. `onSignedOut` gets the new engine list. */
+export const ClaudeSignOut: React.FC<{ onSignedOut: (engines: EngineInfo[]) => void }> = ({ onSignedOut }) => {
+ const [open, setOpen] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const cancelRef = useRef<HTMLButtonElement>(null);
+ const confirmRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ if (open) cancelRef.current?.focus();
+ }, [open]);
+
+ const close = () => {
+ if (busy) return;
+ setOpen(false);
+ setError(null);
+ requestAnimationFrame(() => triggerRef.current?.focus());
+ };
+
+ const confirm = async () => {
+ playSfx('click');
+ setBusy(true);
+ setError(null);
+ try {
+ const d = await claudeLoginApi.logout();
+ setBusy(false);
+ setOpen(false);
+ if (Array.isArray(d?.engines)) onSignedOut(d.engines);
+ } catch (e) {
+ setBusy(false);
+ setError(e instanceof Error ? e.message : 'Couldn’t sign out.');
+ }
+ };
+
+ // Keyboard: Escape closes (without closing Settings too), Tab stays on the two buttons.
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ close();
+ } else if (e.key === 'Tab') {
+ const items = [cancelRef.current, confirmRef.current].filter((x): x is HTMLButtonElement => !!x && !x.disabled);
+ if (items.length === 0) return e.preventDefault();
+ const i = items.indexOf(document.activeElement as HTMLButtonElement);
+ const next = e.shiftKey ? (i <= 0 ? items.length - 1 : i - 1) : i === items.length - 1 ? 0 : i + 1;
+ e.preventDefault();
+ items[next].focus();
+ }
+ };
+
+ return (
+ <>
+ <button
+ ref={triggerRef}
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ setOpen(true);
+ }}
+ className="mt-1 inline-flex items-center gap-1 text-[10.5px] text-zinc-500 hover:text-rose-300 underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 rounded"
+ >
+ <LogOut size={10} aria-hidden="true" /> Sign out
+ </button>
+ {open && (
+ <div className="fixed inset-0 z-[60] bg-black/60 flex items-center justify-center p-4" onMouseDown={(e) => e.target === e.currentTarget && close()}>
+ <div
+ role="alertdialog"
+ aria-modal="true"
+ aria-labelledby="claude-signout-title"
+ aria-describedby="claude-signout-desc"
+ onKeyDown={onKeyDown}
+ className="w-full max-w-sm bg-zinc-900 border border-zinc-700 rounded-xl p-4 shadow-2xl space-y-3 text-zinc-100"
+ >
+ <h4 id="claude-signout-title" className="text-sm font-semibold">
+ Sign out of Claude?
+ </h4>
+ <div id="claude-signout-desc" className="space-y-1.5 text-xs text-zinc-300 leading-relaxed">
+ <p>Every kwant on this server will stop using Claude until you sign in again.</p>
+ <p className="text-zinc-400">This signs Claude Code out on this computer, so anything else here that uses the same Claude Code login is signed out too.</p>
+ </div>
+ {error && (
+ <p className="flex items-center gap-1.5 text-[11px] text-rose-300" role="alert">
+ <AlertTriangle size={12} className="shrink-0" aria-hidden="true" /> {error}
+ </p>
+ )}
+ <div className="flex justify-end gap-2 pt-1">
+ <button ref={cancelRef} type="button" onClick={close} disabled={busy} className={quietBtn}>
+ Cancel
+ </button>
+ <button
+ ref={confirmRef}
+ type="button"
+ onClick={confirm}
+ disabled={busy}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-rose-600 hover:bg-rose-500 disabled:opacity-50 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-rose-400"
+ >
+ {busy && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {busy ? 'Signing out…' : 'Sign out'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </>
+ );
+};
diff --git a/frontend/src/components/EnginesPanel.tsx b/frontend/src/components/EnginesPanel.tsx
index 3d327f9f..d9d2d8e8 100644
--- a/frontend/src/components/EnginesPanel.tsx
+++ b/frontend/src/components/EnginesPanel.tsx
@@ -3,6 +3,8 @@ import { AlertTriangle, ChevronDown, ChevronRight, Cpu, Key, Loader2, RefreshCw,
import { EngineInfo, Tone, checkedAgo, isAbsent, onlyCliReady, sortEngines, statusView } from '../engines';
import { playSfx } from '../audio/chiptune';
import type { EnginesApi } from '../useEngines';
+import { claudeNeedsSignIn } from '../claudeLogin';
+import { ClaudeSignIn, ClaudeSignOut } from './ClaudeSignIn';
const DOT: Record<Tone, string> = {
ok: 'bg-emerald-400 shadow-sm shadow-emerald-500/50',
@@ -32,64 +34,78 @@ const withCode = (text: string) =>
),
);
-export const EngineRow: React.FC<{ engine: EngineInfo; onToggle?: (on: boolean) => void }> = ({ engine, onToggle }) => {
+export const EngineRow: React.FC<{ engine: EngineInfo; onToggle?: (on: boolean) => void; children?: React.ReactNode }> = ({ engine, onToggle, children }) => {
const view = statusView(engine);
const Icon = KIND_ICON[engine.kind] ?? Cpu;
const off = engine.enabled === false;
const labelId = `engine-${engine.id}-name`;
- const showDetail = !off && engine.detail && engine.status !== 'ready';
+ // A sign-in button replaces "run `claude auth login`".
+ const showDetail = !off && engine.detail && engine.status !== 'ready' && !(children && engine.status === 'signed_out');
return (
<li
data-engine={engine.id}
data-status={off ? 'off' : engine.status}
- className="flex items-start gap-2.5 bg-zinc-900/90 px-3 py-2 rounded-lg border border-zinc-800 text-xs"
+ className="bg-zinc-900/90 px-3 py-2 rounded-lg border border-zinc-800 text-xs"
>
- <span className={`mt-1 w-2 h-2 shrink-0 rounded-full ${DOT[view.tone]}`} aria-hidden="true" />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-1.5 flex-wrap">
- <Icon size={12} className="text-zinc-500 shrink-0" aria-hidden="true" />
- <span id={labelId} className={`font-medium ${off ? 'text-zinc-500' : 'text-zinc-200'}`}>
- {engine.name}
- </span>
- {engine.version && <span className="text-[10px] font-mono text-zinc-500">v{engine.version}</span>}
+ <div className="flex items-start gap-2.5">
+ <span className={`mt-1 w-2 h-2 shrink-0 rounded-full ${DOT[view.tone]}`} aria-hidden="true" />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <Icon size={12} className="text-zinc-500 shrink-0" aria-hidden="true" />
+ <span id={labelId} className={`font-medium ${off ? 'text-zinc-500' : 'text-zinc-200'}`}>
+ {engine.name}
+ </span>
+ {engine.version && <span className="text-[10px] font-mono text-zinc-500">v{engine.version}</span>}
+ </div>
+ {showDetail && <p className="mt-0.5 text-[11px] text-zinc-400 leading-snug break-words">{withCode(engine.detail!)}</p>}
+ {!off && engine.status === 'ready' && engine.models.length > 0 && (
+ <p className="mt-0.5 text-[11px] text-zinc-500 truncate" title={engine.models.map((m) => m.label).join(', ')}>
+ {engine.models.length === 1 ? '1 model' : `${engine.models.length} models`}
+ {' · '}
+ {engine.models.slice(0, 3).map((m) => m.label).join(', ')}
+ {engine.models.length > 3 ? '…' : ''}
+ </p>
+ )}
</div>
- {showDetail && <p className="mt-0.5 text-[11px] text-zinc-400 leading-snug break-words">{withCode(engine.detail!)}</p>}
- {!off && engine.status === 'ready' && engine.models.length > 0 && (
- <p className="mt-0.5 text-[11px] text-zinc-500 truncate" title={engine.models.map((m) => m.label).join(', ')}>
- {engine.models.length === 1 ? '1 model' : `${engine.models.length} models`}
- {' · '}
- {engine.models.slice(0, 3).map((m) => m.label).join(', ')}
- {engine.models.length > 3 ? '…' : ''}
- </p>
+ <span className={`shrink-0 text-[11px] font-mono ${TEXT[view.tone]}`}>{view.label}</span>
+ {onToggle && typeof engine.enabled === 'boolean' && (
+ <button
+ type="button"
+ role="switch"
+ aria-checked={!off}
+ aria-labelledby={labelId}
+ title={off ? 'Off: kwnt never uses it' : 'On: kwnt may use it'}
+ onClick={() => {
+ playSfx('click');
+ onToggle(off);
+ }}
+ className={`relative shrink-0 mt-px w-8 h-[18px] rounded-full transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
+ off ? 'bg-zinc-700' : 'bg-sky-600'
+ }`}
+ >
+ <span
+ className={`absolute top-[2px] left-[2px] w-[14px] h-[14px] rounded-full bg-white transition-transform motion-reduce:transition-none ${off ? '' : 'translate-x-[14px]'}`}
+ />
+ </button>
)}
</div>
- <span className={`shrink-0 text-[11px] font-mono ${TEXT[view.tone]}`}>{view.label}</span>
- {onToggle && typeof engine.enabled === 'boolean' && (
- <button
- type="button"
- role="switch"
- aria-checked={!off}
- aria-labelledby={labelId}
- title={off ? 'Off: kwnt never uses it' : 'On: kwnt may use it'}
- onClick={() => {
- playSfx('click');
- onToggle(off);
- }}
- className={`relative shrink-0 mt-px w-8 h-[18px] rounded-full transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
- off ? 'bg-zinc-700' : 'bg-sky-600'
- }`}
- >
- <span
- className={`absolute top-[2px] left-[2px] w-[14px] h-[14px] rounded-full bg-white transition-transform motion-reduce:transition-none ${off ? '' : 'translate-x-[14px]'}`}
- />
- </button>
- )}
+ {/* Full width under the name, lined up with it */}
+ {!off && children && <div className="pl-[18px]">{children}</div>}
</li>
);
};
-/** The Settings "Engines" list: honest status per engine, ready ones first, with Re-check. */
-export const EnginesPanel: React.FC<{ api: EnginesApi; now?: number }> = ({ api, now = Date.now() }) => {
+/** Sign in or out of Claude Code from its row; nothing for other engines. */
+const accountAction = (e: EngineInfo, api: EnginesApi, focusClaudeSignIn?: number) => {
+ if (e.id !== 'claude' || e.enabled === false) return null;
+ if (e.status === 'signed_out') return <ClaudeSignIn onSignedIn={api.reload} focusRequest={focusClaudeSignIn} />;
+ if (e.status === 'ready') return <ClaudeSignOut onSignedOut={api.apply} />;
+ return null;
+};
+
+/** The Settings "Engines" list: honest status per engine, ready ones first, with Re-check.
+ * `focusClaudeSignIn` changes to bring "Sign in with Claude" into view and focus it. */
+export const EnginesPanel: React.FC<{ api: EnginesApi; now?: number; focusClaudeSignIn?: number }> = ({ api, now = Date.now(), focusClaudeSignIn }) => {
const { engines, error, rechecking, recheck, setEnabled } = api;
const [showAbsent, setShowAbsent] = useState(false);
const sorted = engines ? sortEngines(engines) : [];
@@ -124,7 +140,9 @@ export const EnginesPanel: React.FC<{ api: EnginesApi; now?: number }> = ({ api,
: engines.length === 0
? 'This server doesn’t report engine status yet.'
: readyCount === 0
- ? 'No engine can run right now. Sign in to a CLI below or add an API key.'
+ ? claudeNeedsSignIn(engines)
+ ? 'No engine can run right now. Sign in with Claude below, or add an API key.'
+ : 'No engine can run right now. Sign in to a CLI below or add an API key.'
: `${readyCount} ready${onlyCliReady(engines) ? ', all through your signed-in CLIs, so no API keys are needed' : ''}. Kwants only use engines that are ready.`}
{ago && <span className="text-zinc-500"> Checked {ago}.</span>}
</p>
@@ -138,7 +156,9 @@ export const EnginesPanel: React.FC<{ api: EnginesApi; now?: number }> = ({ api,
{present.length > 0 && (
<ul className="grid grid-cols-1 gap-2" aria-label="Engines on this computer">
{present.map((e) => (
- <EngineRow key={e.id} engine={e} onToggle={(on) => setEnabled(e.id, on)} />
+ <EngineRow key={e.id} engine={e} onToggle={(on) => setEnabled(e.id, on)}>
+ {accountAction(e, api, focusClaudeSignIn)}
+ </EngineRow>
))}
</ul>
)}
diff --git a/frontend/src/components/ModelPicker.tsx b/frontend/src/components/ModelPicker.tsx
index 6d14c5a4..572031b2 100644
--- a/frontend/src/components/ModelPicker.tsx
+++ b/frontend/src/components/ModelPicker.tsx
@@ -1,5 +1,6 @@
import React, { useId } from 'react';
import { AlertTriangle, ChevronRight, Loader2 } from 'lucide-react';
+import { claudeNeedsSignIn } from '../claudeLogin';
import {
EngineInfo,
FAMILIES,
@@ -21,13 +22,15 @@ interface ModelPickerProps {
engines: EngineInfo[] | null;
/** Opens Settings → Engines. */
onOpenSettings?: () => void;
+ /** Opens Settings at "Sign in with Claude". */
+ onSignInClaude?: () => void;
}
const SELECT =
'w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none transition-colors disabled:opacity-50';
/** One Engine → Model choice used wherever a kwant's model is set. Only engines that can run are offered. */
-export const ModelPicker: React.FC<ModelPickerProps> = ({ value, onChange, engines, onOpenSettings }) => {
+export const ModelPicker: React.FC<ModelPickerProps> = ({ value, onChange, engines, onOpenSettings, onSignInClaude }) => {
const id = useId();
const pick = parsePick(value);
// A server without engine checks: offer every family, as before.
@@ -101,7 +104,7 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ value, onChange, engin
</div>
</div>
- <PickHint id={hintId} health={health} onOpenSettings={onOpenSettings} />
+ <PickHint id={hintId} health={health} onOpenSettings={onOpenSettings} onSignInClaude={claudeNeedsSignIn(engines) ? onSignInClaude : undefined} />
</div>
);
};
@@ -115,7 +118,19 @@ const SettingsLink: React.FC<{ onOpenSettings?: () => void }> = ({ onOpenSetting
<span>Check Settings → Engines.</span>
);
-const PickHint: React.FC<{ id: string; health: ReturnType<typeof pickHealth>; onOpenSettings?: () => void }> = ({ id, health, onOpenSettings }) => {
+/** "Sign in with Claude", when that's what fixes it. */
+const SignInClaudeLink: React.FC<{ onSignInClaude: () => void }> = ({ onSignInClaude }) => (
+ <button type="button" onClick={onSignInClaude} className="inline-flex items-center gap-0.5 font-medium text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline">
+ Sign in with Claude <ChevronRight size={11} />
+ </button>
+);
+
+const PickHint: React.FC<{ id: string; health: ReturnType<typeof pickHealth>; onOpenSettings?: () => void; onSignInClaude?: () => void }> = ({
+ id,
+ health,
+ onOpenSettings,
+ onSignInClaude,
+}) => {
switch (health.kind) {
case 'ok':
return null;
@@ -132,7 +147,15 @@ const PickHint: React.FC<{ id: string; health: ReturnType<typeof pickHealth>; on
<AlertTriangle size={12} /> No engine can run right now
</p>
<p className="text-amber-200/80">
- Sign in to a CLI like Claude Code, or add an API key. <SettingsLink onOpenSettings={onOpenSettings} />
+ {onSignInClaude ? (
+ <>
+ Claude Code is installed but signed out. <SignInClaudeLink onSignInClaude={onSignInClaude} />
+ </>
+ ) : (
+ <>
+ Sign in to a CLI like Claude Code, or add an API key. <SettingsLink onOpenSettings={onOpenSettings} />
+ </>
+ )}
</p>
</div>
);
@@ -144,7 +167,8 @@ const PickHint: React.FC<{ id: string; health: ReturnType<typeof pickHealth>; on
</p>
<p className="text-amber-200/80">
{health.reason ? `${health.reason.replace(/`/g, '').replace(/\.$/, '')}. ` : ''}
- This kwant won't switch engine by itself: fix it, or pick another engine. <SettingsLink onOpenSettings={onOpenSettings} />
+ This kwant won't switch engine by itself: fix it, or pick another engine.{' '}
+ {health.family === 'claude' && onSignInClaude ? <SignInClaudeLink onSignInClaude={onSignInClaude} /> : <SettingsLink onOpenSettings={onOpenSettings} />}
</p>
</div>
);
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index 54371d51..a81241d7 100644
--- a/frontend/src/components/NewAgentModal.tsx
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -54,6 +54,8 @@ interface NewAgentModalProps {
onManageProfiles?: () => void;
/** Opens Settings → Engines. */
onOpenSettings?: () => void;
+ /** Opens Settings at "Sign in with Claude". */
+ onSignInClaude?: () => void;
/** Changes when Settings closes, so engine status is read again. */
enginesRefreshKey?: number;
/** Resolves to an error message when saving failed. */
@@ -78,6 +80,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
profiles = [],
onManageProfiles,
onOpenSettings,
+ onSignInClaude,
enginesRefreshKey,
onSubmit,
kwants = [],
@@ -367,7 +370,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
</div>
</div>
- <ModelPicker value={model} onChange={setModel} engines={engines.engines} onOpenSettings={onOpenSettings} />
+ <ModelPicker value={model} onChange={setModel} engines={engines.engines} onOpenSettings={onOpenSettings} onSignInClaude={onSignInClaude} />
{engine && (
<div>
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 96459eb3..edd9f95d 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -48,9 +48,11 @@ interface SettingsModalProps {
onClose: () => void;
onOpenTools?: () => void;
onOpenProfiles?: () => void;
+ /** Changes to focus "Sign in with Claude" in Engines. */
+ focusClaudeSignIn?: number;
}
-export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, onOpenTools, onOpenProfiles }) => {
+export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, onOpenTools, onOpenProfiles, focusClaudeSignIn }) => {
const { authRequired, signOut } = useAuth();
const computer = useComputerMode(isOpen);
const engines = useEngines(isOpen);
@@ -211,7 +213,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o
</button>
</div>
- <EnginesPanel api={engines} />
+ <EnginesPanel api={engines} focusClaudeSignIn={focusClaudeSignIn} />
{computer.state.settings && (
<div className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3">
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 303fc3d1..5a7a3a6b 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -5,6 +5,7 @@ import { playSfx } from '../audio/chiptune';
import { badgeText } from '../away';
import { isUsable, pickLabel } from '../engines';
import { useEngines } from '../useEngines';
+import { claudeNeedsSignIn } from '../claudeLogin';
export interface Kwant {
id: string;
@@ -69,6 +70,8 @@ export interface SidebarProps {
onOpenAway?: () => void;
/** Opens Settings → Engines from the footer. */
onOpenSettings?: () => void;
+ /** Opens Settings at "Sign in with Claude", when Claude being signed out is why nothing runs. */
+ onSignInClaude?: () => void;
/** Changes when Settings closes, so the footer reads engine status again. */
enginesRefreshKey?: number;
}
@@ -100,6 +103,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
awayActive = false,
onOpenAway,
onOpenSettings,
+ onSignInClaude,
enginesRefreshKey = 0,
}) => {
const engines = useEngines(true);
@@ -108,6 +112,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
if (enginesRefreshKey) reloadEngines();
}, [enginesRefreshKey, reloadEngines]);
const readyCount = engines.engines?.filter(isUsable).length ?? null;
+ // Nothing can run and Claude only needs signing in: the footer goes straight to that.
+ const offerClaude = readyCount === 0 && !!onSignInClaude && claudeNeedsSignIn(engines.engines);
const [teamsOpen, setTeamsOpen] = useState(true);
const [fleetOpen, setFleetOpen] = useState(() => localStorage.getItem('kwant.fleetOpen') === '1');
const [collapsedTeams, setCollapsedTeams] = useState<Set<string>>(new Set());
@@ -528,8 +534,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
<div className="p-3 border-t border-zinc-800/60 bg-zinc-950/40 text-[11px] text-zinc-500">
<button
type="button"
- onClick={onOpenSettings}
- disabled={!onOpenSettings}
+ onClick={offerClaude ? onSignInClaude : onOpenSettings}
+ disabled={!onOpenSettings && !offerClaude}
className="flex items-center gap-1.5 hover:text-zinc-300 disabled:hover:text-zinc-500 transition-colors"
>
{readyCount === null ? (
@@ -543,7 +549,9 @@ export const Sidebar: React.FC<SidebarProps> = ({
{readyCount === null
? 'Checking engines…'
: readyCount === 0
- ? 'No engine can run · check Settings'
+ ? offerClaude
+ ? 'No engine can run · Sign in with Claude'
+ : 'No engine can run · check Settings'
: `${readyCount} ${readyCount === 1 ? 'engine' : 'engines'} ready`}
</span>
</button>
diff --git a/frontend/src/useEngines.ts b/frontend/src/useEngines.ts
index 976835c1..8ef34e74 100644
--- a/frontend/src/useEngines.ts
+++ b/frontend/src/useEngines.ts
@@ -11,6 +11,8 @@ export interface EnginesApi {
/** Reads the cached status again, without re-running the checks. */
reload: () => Promise<void>;
setEnabled: (id: EngineInfo['id'], enabled: boolean) => Promise<void>;
+ /** Shows a list the server already answered with (e.g. after signing out). */
+ apply: (engines: EngineInfo[]) => void;
}
/** Loads /api/engines while `active`; polls briefly while any engine is still "checking". */
@@ -93,5 +95,10 @@ export function useEngines(active: boolean): EnginesApi {
[load],
);
- return { engines, error, rechecking, recheck, reload: load, setEnabled };
+ const apply = useCallback((list: EngineInfo[]) => {
+ setEngines(list);
+ setError(null);
+ }, []);
+
+ return { engines, error, rechecking, recheck, reload: load, setEnabled, apply };
}
diff --git a/frontend/tests/claudeLogin.test.mjs b/frontend/tests/claudeLogin.test.mjs
new file mode 100644
index 00000000..eb6e3b67
--- /dev/null
+++ b/frontend/tests/claudeLogin.test.mjs
@@ -0,0 +1,185 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+// The sound effects module reads its mute flag on load.
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+
+const m = await loadBundled(`
+ export * from './src/claudeLogin';
+ export { EnginesPanel } from './src/components/EnginesPanel';
+ export { ModelPicker } from './src/components/ModelPicker';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { createElement } from 'react';
+`);
+const h = m.createElement;
+
+// Shaped like SessionView in src/server/engine_login.rs.
+const session = (over = {}) => ({
+ session_id: 'lgn_1',
+ state: 'waiting_for_code',
+ detail: null,
+ url: 'https://claude.com/cai/oauth/authorize?code=true&client_id=x',
+ expires_at: '2026-10-17T21:10:00Z',
+ ...over,
+});
+
+/** Swaps in a fake fetch; returns the calls it saw. */
+function mockFetch(answer) {
+ const calls = [];
+ globalThis.fetch = async (url, init = {}) => {
+ calls.push({ url, method: init.method ?? 'GET', body: init.body ?? null });
+ const [status, body] = answer(url, init);
+ return new Response(body === undefined ? null : JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+ };
+ return calls;
+}
+
+test('start, poll, cancel and logout hit the engine sign-in routes', async () => {
+ const calls = mockFetch((url, init) => {
+ if (init.method === 'DELETE') return [204, undefined];
+ if (url.endsWith('/logout')) return [200, { engines: [] }];
+ return [200, session()];
+ });
+ await m.claudeLoginApi.start();
+ await m.claudeLoginApi.get('lgn_1');
+ await m.claudeLoginApi.cancel('lgn_1');
+ assert.deepEqual(await m.claudeLoginApi.logout(), { engines: [] });
+ assert.deepEqual(
+ calls.map((c) => `${c.method} ${c.url}`),
+ ['POST /api/engines/claude/login', 'GET /api/engines/claude/login/lgn_1', 'DELETE /api/engines/claude/login/lgn_1', 'POST /api/engines/claude/logout'],
+ );
+});
+
+test('the code goes only in the POST body, never in the URL', async () => {
+ const calls = mockFetch(() => [200, session({ state: 'done', url: null })]);
+ const s = await m.claudeLoginApi.submitCode('lgn_1', 'abc123#state-xyz');
+ assert.equal(s.state, 'done');
+ assert.equal(calls[0].method, 'POST');
+ assert.equal(calls[0].url, '/api/engines/claude/login/lgn_1/code');
+ assert.ok(!calls[0].url.includes('abc123'));
+ assert.deepEqual(JSON.parse(calls[0].body), { code: 'abc123#state-xyz' });
+});
+
+test('a 409 carries the running sign-in, so the UI can pick it up', async () => {
+ mockFetch(() => [409, { error: 'a Claude sign-in is already running', session_id: 'lgn_busy' }]);
+ await assert.rejects(m.claudeLoginApi.start(), (e) => {
+ assert.ok(e instanceof m.ClaudeLoginError);
+ assert.equal(e.status, 409);
+ assert.equal(e.sessionId, 'lgn_busy');
+ return true;
+ });
+});
+
+test('server errors keep their message; a dead server says so', async () => {
+ mockFetch(() => [400, { error: 'That doesn’t look like a code.' }]);
+ await assert.rejects(m.claudeLoginApi.submitCode('lgn_1', 'x'), { message: 'That doesn’t look like a code.', status: 400 });
+ mockFetch(() => [502, null]);
+ await assert.rejects(m.claudeLoginApi.logout(), { message: 'HTTP 502' });
+ globalThis.fetch = async () => {
+ throw new TypeError('fetch failed');
+ };
+ await assert.rejects(m.claudeLoginApi.start(), { message: 'Couldn’t reach the server.', status: 0 });
+});
+
+test('states: which are still running, and what a failure says', () => {
+ assert.deepEqual(
+ ['starting', 'waiting_for_code', 'verifying', 'done', 'failed', 'expired', 'cancelled'].filter(m.isLoginActive),
+ ['starting', 'waiting_for_code', 'verifying'],
+ );
+ assert.equal(m.loginFailure(session({ state: 'failed', detail: "Claude didn't accept that code. Start sign-in again." })), "Claude didn't accept that code. Start sign-in again.");
+ assert.equal(m.loginFailure(session({ state: 'failed' })), 'Sign-in failed. Start it again.');
+ assert.equal(m.loginFailure(session({ state: 'expired' })), 'Sign-in timed out. Start it again.');
+ assert.equal(m.loginFailure(session({ state: 'cancelled' })), null);
+ assert.equal(m.loginFailure(session({ state: 'done' })), null);
+});
+
+test('only https links on Anthropic hosts are opened', () => {
+ assert.ok(m.isClaudeSignInUrl('https://claude.com/cai/oauth/authorize?x=1'));
+ assert.ok(m.isClaudeSignInUrl('https://claude.ai/oauth/authorize'));
+ assert.ok(m.isClaudeSignInUrl('https://platform.claude.com/oauth/code/callback'));
+ assert.ok(!m.isClaudeSignInUrl('http://claude.ai/oauth/authorize'));
+ assert.ok(!m.isClaudeSignInUrl('https://claude.ai.evil.example/oauth'));
+ assert.ok(!m.isClaudeSignInUrl('https://notclaude.ai/'));
+ assert.ok(!m.isClaudeSignInUrl('javascript:alert(1)'));
+ assert.ok(!m.isClaudeSignInUrl(null));
+});
+
+// ---- Rendering ----
+
+const engine = (id, over = {}) => ({
+ id,
+ name: { claude: 'Claude Code CLI', anthropic_api: 'Anthropic API key', codex: 'Codex CLI' }[id],
+ kind: id.endsWith('_api') ? 'api' : 'cli',
+ status: 'ready',
+ detail: null,
+ version: null,
+ models: [],
+ checked_at: '2026-10-17T19:00:00Z',
+ enabled: true,
+ ...over,
+});
+const api = (engines) => ({ engines, error: null, rechecking: false, recheck: async () => {}, reload: async () => {}, setEnabled: async () => {}, apply: () => {} });
+const panel = (engines) => m.renderToStaticMarkup(h(m.EnginesPanel, { api: api(engines), now: Date.parse('2026-10-17T19:01:00Z') }));
+const signedOut = engine('claude', { status: 'signed_out', detail: 'Not signed in: run `claude login`' });
+
+test('claudeNeedsSignIn: only an installed, switched-on, signed-out Claude CLI', () => {
+ assert.ok(m.claudeNeedsSignIn([signedOut]));
+ assert.ok(!m.claudeNeedsSignIn([engine('claude')]));
+ assert.ok(!m.claudeNeedsSignIn([{ ...signedOut, enabled: false }]));
+ assert.ok(!m.claudeNeedsSignIn([engine('claude', { status: 'not_installed' })]));
+ assert.ok(!m.claudeNeedsSignIn([engine('anthropic_api', { status: 'signed_out' })]));
+ assert.ok(!m.claudeNeedsSignIn(null));
+});
+
+test('a signed-out Claude row offers "Sign in with Claude"; the summary points at it', () => {
+ const html = panel([signedOut, engine('codex', { status: 'not_installed' })]);
+ assert.match(html, /Sign in with Claude<\/button>/);
+ assert.match(html, /Opens claude.ai in a new tab/);
+ assert.match(html, /No engine can run right now\. Sign in with Claude below, or add an API key\./);
+ assert.doesNotMatch(html, />Sign out</);
+ // The button replaces "run `claude login`".
+ assert.doesNotMatch(html, /claude login/);
+});
+
+test('a ready Claude row offers Sign out instead', () => {
+ const html = panel([engine('claude')]);
+ assert.match(html, /Sign out<\/button>/);
+ assert.doesNotMatch(html, /Sign in with Claude/);
+});
+
+test('no account actions on a switched-off, missing or other engine', () => {
+ for (const list of [[{ ...signedOut, enabled: false }], [engine('claude', { status: 'not_installed' })], [engine('codex', { status: 'signed_out' })], [engine('anthropic_api')]]) {
+ const html = panel(list);
+ assert.doesNotMatch(html, /Sign in with Claude<\/button>/);
+ assert.doesNotMatch(html, />Sign out</);
+ }
+});
+
+const picker = (value, engines, extra = {}) =>
+ m.renderToStaticMarkup(h(m.ModelPicker, { value, onChange: () => {}, engines, onOpenSettings: () => {}, onSignInClaude: () => {}, ...extra }));
+
+test('a kwant pinned to Claude links to the sign-in when Claude is signed out', () => {
+ const html = picker('claude/opus', [signedOut, engine('codex')]);
+ assert.match(html, /Claude can&#x27;t run right now/);
+ assert.match(html, /Sign in with Claude/);
+ assert.doesNotMatch(html, /Open Settings/);
+});
+
+test('"No engine can run" links to the sign-in when Claude is the fix', () => {
+ const html = picker('auto', [signedOut]);
+ assert.match(html, /No engine can run right now/);
+ assert.match(html, /Claude Code is installed but signed out\./);
+ assert.match(html, /Sign in with Claude/);
+});
+
+test('other reasons keep "Open Settings"', () => {
+ // Pinned to Codex, which is signed out: the Claude link would be wrong.
+ assert.match(picker('codex', [signedOut, engine('codex', { status: 'signed_out' })]), /Open Settings/);
+ // Claude missing rather than signed out.
+ const missing = picker('claude', [engine('claude', { status: 'not_installed', detail: 'Claude Code isn’t installed' })]);
+ assert.match(missing, /Open Settings/);
+ assert.doesNotMatch(missing, /Sign in with Claude/);
+ // No onSignInClaude from the caller: fall back to Settings.
+ assert.match(picker('claude', [signedOut], { onSignInClaude: undefined }), /Open Settings/);
+});