From 6e05a6176b878b58dbba311d0bd15f2aa4f43efa Mon Sep 17 00:00:00 2001 From: Vikram Date: Sat, 28 Nov 2026 21:22:17 +0530 Subject: [PATCH 1/2] Claude Code panel: Claude's look, and one-click sign-in - The panel takes Claude's warm palette (charcoal in dark mode, cream in light), serif answers and greeting, a large rounded message box with the model picker and a round send arrow, and a breathing sparkle while Claude thinks. Veyra's own sparkle, no Anthropic logo. - Sign in with Claude: one click runs Claude Code's own `claude auth login` in a terminal tab (the browser opens Claude's sign-in page); Veyra polls `claude auth status` (exit code 0 = signed in) and unlocks the panel by itself. The footer shows how you're signed in, with Sign out (`claude auth logout`). Veyra never sees the sign-in. - The selection is read when a prompt is sent, so it's attached even when you send right after selecting. Checked in the real app (tauri dev, driven through WebView2's debugging port) with a stand-in claude.cmd on PATH: sign-in, streaming, the permission card, the real file edit and editor reload, --resume and Stop all work. Tests: a Rust test for auth status, a new interface test for one-click sign-in; the full Playwright suite passes (59). Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/claude.rs | 34 +++++- src-tauri/src/lib.rs | 2 +- src/App.tsx | 2 +- src/claude/ClaudePanel.tsx | 101 ++++++++++++---- src/claude/claude.css | 242 +++++++++++++++++++++---------------- src/claude/protocol.ts | 2 +- src/lsp/tools.ts | 10 ++ tests/claude-panel.spec.ts | 35 ++++-- 8 files changed, 290 insertions(+), 138 deletions(-) diff --git a/src-tauri/src/claude.rs b/src-tauri/src/claude.rs index 95e23b3..c62d84e 100644 --- a/src-tauri/src/claude.rs +++ b/src-tauri/src/claude.rs @@ -5,7 +5,7 @@ //! (prompts, permission answers, stop) are written to the CLI's stdin as one JSON line each. The user signs in to //! Claude in the CLI itself; Veyra never sees or stores Claude credentials. use super::{err, plain, quiet, root, Workspace}; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, io::{BufRead, BufReader, Write}, @@ -125,6 +125,29 @@ pub fn claude_chat_send(state: State<'_, ClaudeState>, id: u32, message: String) #[tauri::command] pub fn claude_chat_stop(state: State<'_, ClaudeState>, id: u32) { if let Ok(mut chats) = state.chats.lock() { chats.remove(&id); } } +/// Whether Claude Code is installed and signed in, from `claude auth status` (JSON; exit code 0 when signed in). +#[derive(Serialize, Debug, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct AuthStatus { installed: bool, signed_in: bool, method: String, expires: Option } + +/// Reads `claude auth status`: the documented fields are authMethod (none, claude.ai, oauth_token, api_key, +/// api_key_helper, third_party) and loginExpiresAt. +pub(crate) fn parse_auth(success: bool, stdout: &str) -> AuthStatus { + let json: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or(serde_json::Value::Null); + let method = json.get("authMethod").and_then(|v| v.as_str()).unwrap_or("").to_string(); + let expires = json.get("loginExpiresAt").and_then(|v| v.as_str()).map(String::from); + AuthStatus { installed: true, signed_in: success && method != "none", method, expires } +} + +#[tauri::command] +pub async fn claude_auth_status() -> Result { + tauri::async_runtime::spawn_blocking(|| { + let Some(program) = super::cli::claude_path() else { return Ok(AuthStatus { installed: false, signed_in: false, method: String::new(), expires: None }); }; + let output = quiet(&program).args(["auth", "status"]).stdin(Stdio::null()).output().map_err(err)?; + Ok(parse_auth(output.status.success(), &String::from_utf8_lossy(&output.stdout))) + }).await.map_err(err)? +} + #[cfg(test)] mod tests { use super::*; @@ -149,6 +172,15 @@ mod tests { assert!(chat_args(&options("default", None, Some("claude-sonnet-5-5[1m]"))).is_ok()); } + #[test] fn auth_status_is_read_from_the_documented_fields() { + let signed = parse_auth(true, r#"{"authMethod":"claude.ai","configDirectory":"/home/a/.claude","loginExpiresAt":"2027-01-01T00:00:00Z"}"#); + assert_eq!(signed, AuthStatus { installed: true, signed_in: true, method: "claude.ai".into(), expires: Some("2027-01-01T00:00:00Z".into()) }); + assert!(parse_auth(true, r#"{"authMethod":"api_key","loginExpiresAt":null}"#).signed_in); + assert!(!parse_auth(false, r#"{"authMethod":"none"}"#).signed_in, "exit code 1: not signed in"); + assert!(!parse_auth(true, r#"{"authMethod":"none"}"#).signed_in); + assert!(!parse_auth(false, "not json").signed_in); + } + #[test] fn only_single_json_objects_are_written() { assert!(check_line(r#"{"type":"user"}"#).is_ok()); assert!(check_line("{\"a\":1}\n{\"b\":2}").is_err()); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 7e46f1a..a0d97a5 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -607,7 +607,7 @@ pub fn run() { Ok(()) }) .on_menu_event(|app,event|{let _=app.emit("menu-command",event.id().as_ref());}) - .invoke_handler(tauri::generate_handler![choose_folder, open_folder, platform_info, list_directory, read_file, read_file_base64, save_file, create_entry, rename_file, trash_file, copy_entry, duplicate_entry, reveal_in_finder, project_files, search_workspace, replace_in_files, git_status, git_diff, git_show, git_stage_all, git_unstage_all, git_discard_all, git_branches, git_switch, git_stash, git_file_history, health::health_check, lsp::lsp_status, lsp::lsp_install, lsp::lsp_uninstall, lsp::lsp_start, lsp::lsp_send, lsp::lsp_stop, lsp::prettier_format, cli::claude_code_status, claude::claude_chat_start, claude::claude_chat_send, claude::claude_chat_stop, dap::dap_status, dap::dap_install, dap::dap_uninstall, dap::dap_start, dap::dap_send, dap::dap_stop, live::live_start, live::live_stop, live::live_status, git_stage, git_unstage, git_discard, git_commit, git_log, git_graph, github_info, github_login, github_open, git_remote_action, terminal_start, terminal_write, terminal_resize, terminal_stop, set_dirty, quit, account::veyra_sign_in, account::veyra_account, account::veyra_sign_out]) + .invoke_handler(tauri::generate_handler![choose_folder, open_folder, platform_info, list_directory, read_file, read_file_base64, save_file, create_entry, rename_file, trash_file, copy_entry, duplicate_entry, reveal_in_finder, project_files, search_workspace, replace_in_files, git_status, git_diff, git_show, git_stage_all, git_unstage_all, git_discard_all, git_branches, git_switch, git_stash, git_file_history, health::health_check, lsp::lsp_status, lsp::lsp_install, lsp::lsp_uninstall, lsp::lsp_start, lsp::lsp_send, lsp::lsp_stop, lsp::prettier_format, cli::claude_code_status, claude::claude_chat_start, claude::claude_chat_send, claude::claude_chat_stop, claude::claude_auth_status, dap::dap_status, dap::dap_install, dap::dap_uninstall, dap::dap_start, dap::dap_send, dap::dap_stop, live::live_start, live::live_stop, live::live_status, git_stage, git_unstage, git_discard, git_commit, git_log, git_graph, github_info, github_login, github_open, git_remote_action, terminal_start, terminal_write, terminal_resize, terminal_stop, set_dirty, quit, account::veyra_sign_in, account::veyra_account, account::veyra_sign_out]) .on_window_event(|window, event| { if let tauri::WindowEvent::CloseRequested { api, .. } = event { if window.state::().dirty.load(Ordering::SeqCst) { api.prevent_close(); let _ = window.emit("confirm-quit", ()); } } }) .build(tauri::generate_context!()).expect("error while running Veyra") .run(|app, event| { if let tauri::RunEvent::ExitRequested { api, .. } = event { if app.state::().dirty.load(Ordering::SeqCst) { api.prevent_exit(); let _ = app.emit("confirm-quit", ()); } } }); diff --git a/src/App.tsx b/src/App.tsx index 27b215a..714aef1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -853,7 +853,7 @@ export default function App() { {claudeMounted&&
e.currentTarget.setPointerCapture(e.pointerId)} onPointerMove={e=>{if(!e.currentTarget.hasPointerCapture(e.pointerId))return;const right=e.currentTarget.parentElement!.getBoundingClientRect().right;setClaudeWidth(Math.round(Math.max(300,Math.min(760,right-e.clientX))));}} onPointerUp={e=>{e.currentTarget.releasePointerCapture(e.pointerId);localStorage.setItem("veyra.claude.width",String(claudeWidth));}}/> - setClaudeOpen(false)} onOpenFile={(path,line)=>void openFile(path,line)} onFilesChanged={()=>{void diskCheck.current();void refreshGit();void refresh();}}/> + editorContext()} request={claudeRequest} onClose={()=>setClaudeOpen(false)} onOpenFile={(path,line)=>void openFile(path,line)} onFilesChanged={()=>{void diskCheck.current();void refreshGit();void refresh();}}/>
}
diff --git a/src/claude/ClaudePanel.tsx b/src/claude/ClaudePanel.tsx index 9514596..f222b6b 100644 --- a/src/claude/ClaudePanel.tsx +++ b/src/claude/ClaudePanel.tsx @@ -3,8 +3,8 @@ import { Channel, invoke } from "@tauri-apps/api/core"; import { openUrl } from "@tauri-apps/plugin-opener"; import { marked } from "marked"; import DOMPurify from "dompurify"; -import { Bot, Check, ChevronDown, ChevronRight, CircleAlert, Download, FileCode2, FilePen, Globe, History, ListChecks, LoaderCircle, LogIn, Plus, RefreshCw, Search, Send, ShieldAlert, Sparkles, Square, SquareTerminal, X } from "lucide-react"; -import { installTool, onToolsChange, openClaudeCode, refreshTools, toolState } from "../lsp/tools"; +import { ArrowUp, Bot, Check, ChevronDown, ChevronRight, CircleAlert, CircleCheck, Download, FileCode2, FilePen, Globe, History, ListChecks, LoaderCircle, LogIn, Plus, RefreshCw, Search, ShieldAlert, Sparkles, Square, SquareTerminal, X } from "lucide-react"; +import { installTool, onToolsChange, refreshTools, signInClaude, signOutClaude, toolState } from "../lsp/tools"; import { MODES, apply, ask, contextLabel, decide, describeTool, editLines, emptyChat, interruptMessage, modeMessage, permissionAnswer, promptWithContext, todos, toSaved, upsertSaved, userMessage, type Chat, type EditorContext, type Item, type Mode, type Saved, @@ -19,6 +19,8 @@ type Props = { visible: boolean; /** What's selected in the editor now, offered as a chip on the next prompt. */ context?: EditorContext; + /** Reads the editor's selection at the moment a prompt is sent (the chip can lag by a moment). */ + currentContext?: () => EditorContext | undefined; request: ClaudeRequest | null; onClose: () => void; /** Opens a workspace-relative file, optionally at a line. */ @@ -77,7 +79,7 @@ function Diff({ name, input, open }: { name: string; input: Record name === "Read" ? FileCode2 : ["Edit", "MultiEdit", "Write", "NotebookEdit"].includes(name) ? FilePen : name === "Bash" ? SquareTerminal : name === "Grep" || name === "Glob" ? Search : name.startsWith("Web") ? Globe : name === "TodoWrite" ? ListChecks : name === "Task" || name === "Agent" ? Bot : Sparkles; -export function ClaudePanel({ root, visible, context, request, onClose, onOpenFile, onFilesChanged }: Props) { +export function ClaudePanel({ root, visible, context, currentContext, request, onClose, onOpenFile, onFilesChanged }: Props) { const [chat, setChat] = useState(emptyChat); const [draft, setDraft] = useState(""); const [useContext, setUseContext] = useState(true); @@ -88,6 +90,10 @@ export function ClaudePanel({ root, visible, context, request, onClose, onOpenFi const [historyOpen, setHistoryOpen] = useState(false); const [saved, setSaved] = useState(() => readSaved(root)); const [extraContext, setExtraContext] = useState(); + /** From `claude auth status`: null until known (or when Claude Code can't tell), then signed in or not. */ + const [auth, setAuth] = useState<{ signedIn: boolean | null; method: string }>({ signedIn: null, method: "" }); + const [signingIn, setSigningIn] = useState(false); + const poll = useRef(undefined); const list = useRef(null); const input = useRef(null); const runningRef = useRef(false); @@ -103,6 +109,42 @@ export function ClaudePanel({ root, visible, context, request, onClose, onOpenFi return onToolsChange(update); }, []); + /** Asks Claude Code whether someone is signed in. Returns the answer, or null when it can't tell. */ + const checkAuth = useCallback(async (): Promise => { + try { + const status = await invoke<{ installed: boolean; signedIn: boolean; method: string } | null>("claude_auth_status"); + if (!status) return null; + if (!status.installed) { setInstalled(false); return null; } + setAuth({ signedIn: status.signedIn, method: status.method }); + return status.signedIn; + } catch { return null; } + }, []); + useEffect(() => { if (installed) void checkAuth(); }, [installed, checkAuth]); + useEffect(() => () => clearInterval(poll.current), []); + + /** One click: Claude Code's own sign-in opens in the browser; Veyra notices when it's done. */ + function signIn() { + try { signInClaude(); } catch { setInstalled(false); return; } + setSigningIn(true); + clearInterval(poll.current); + let tries = 0; + poll.current = window.setInterval(async () => { + const signed = await checkAuth(); + if (signed) { + clearInterval(poll.current); setSigningIn(false); + setChat(c => ({ ...c, items: [...c.items.filter(i => !(i.kind === "notice" && i.tone === "signin")), ...(c.items.length ? [{ kind: "notice", id: "signed-in-" + Date.now(), tone: "success", text: "Signed in to Claude. Send your message again." } as Item] : [])] })); + setTimeout(() => input.current?.focus(), 0); + } else if (++tries > 150) { clearInterval(poll.current); setSigningIn(false); } // stop after 5 minutes + }, 2000); + } + function signOut() { + try { signOutClaude(); } catch { return; } + stopProcess(); + let tries = 0; + clearInterval(poll.current); + poll.current = window.setInterval(async () => { const signed = await checkAuth(); if (signed === false || ++tries > 15) clearInterval(poll.current); }, 1500); + } + const stopProcess = useCallback(() => { generation.current++; runningRef.current = false; setRunning(false); void invoke("claude_chat_stop", { id: CHAT_ID }).catch(() => { }); }, []); // A new folder is a new conversation list. @@ -149,7 +191,7 @@ export function ClaudePanel({ root, visible, context, request, onClose, onOpenFi async function send(text: string, attached?: EditorContext) { const body = text.trim(); if (!body || chatRef.current.busy || !root) return; - const c = attached ?? (useContext ? context : undefined); + const c = attached ?? (useContext ? (currentContext?.() ?? context) : undefined); setChat(chat => ask(chat, body, c ? [contextLabel(c)] : undefined)); setDraft(""); setExtraContext(undefined); pinned.current = true; if (!(await start())) return; @@ -196,7 +238,7 @@ export function ClaudePanel({ root, visible, context, request, onClose, onOpenFi const askedFirst = new Set(chat.items.flatMap(i => (i.kind === "permission" ? [i.toolUseId] : []))); const pendingPermission = chat.items.find(i => i.kind === "permission" && !i.decision) as Extract | undefined; const chip = extraContext ?? (useContext ? context : undefined); - const status = !root ? "No folder" : installed === false ? "Not installed" : starting ? "Starting…" : pendingPermission ? "Waiting for you" : chat.busy ? "Working…" : running ? "Ready" : "Idle"; + const status = !root ? "No folder" : installed === false ? "Not installed" : auth.signedIn === false ? (signingIn ? "Signing in…" : "Not signed in") : starting ? "Starting…" : pendingPermission ? "Waiting for you" : chat.busy ? "Working…" : running ? "Ready" : "Idle"; const renderItem = (item: Item, index: number) => { switch (item.kind) { @@ -244,54 +286,63 @@ export function ClaudePanel({ root, visible, context, request, onClose, onOpenFi {item.ok ? : }{item.turns ? `${item.turns} step${item.turns === 1 ? "" : "s"}` : ""}{item.ms ? ` · ${(item.ms / 1000).toFixed(1)}s` : ""}{item.cost && chat.keySource && chat.keySource !== "none" ? ` · $${item.cost.toFixed(3)}` : ""} ; case "notice": - if (item.tone === "signin") return
Sign in to ClaudeClaude Code opens in a terminal: type /login, sign in in your browser, then come back here.
; - return
{item.tone === "error" ? : }{item.text}
; + if (item.tone === "signin") return
Sign in to Claude{signingIn ? "Finish signing in in your browser. This updates by itself." : "Your browser opens Claude's sign-in page. Come back here when you're done."}
; + return
{item.tone === "error" ? : item.tone === "success" ? : }{item.text}
; } }; + const greeting = (() => { const h = new Date().getHours(); return h < 5 ? "Working late" : h < 12 ? "Good morning" : h < 18 ? "Good afternoon" : "Good evening"; })(); + const needsSignIn = installed !== false && auth.signedIn === false; + const accountLabel = auth.method === "claude.ai" ? "your Claude account" : auth.method === "api_key" || auth.method === "api_key_helper" ? "an Anthropic API key" : auth.method === "oauth_token" ? "a Claude token" : auth.method === "third_party" ? "your cloud provider" : ""; + return