graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
gui: P0 UX fixes, Cmd+N shortcut, and dev debug bridge
Rach Pradhand29683b42dcc
diff --git a/gui/src-tauri/Cargo.lock b/gui/src-tauri/Cargo.lockindex 6dc8c895..26dcf967 100644--- a/gui/src-tauri/Cargo.lock+++ b/gui/src-tauri/Cargo.lock@@ -81,6 +81,12 @@ version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"+[[package]]+name = "ascii"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"+[[package]]name = "async-broadcast"version = "0.7.2"@@ -632,6 +638,12 @@ dependencies = ["windows-link 0.2.1",]+[[package]]+name = "chunked_transfer"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"+[[package]]name = "codegraff-gui"version = "0.0.13"@@ -658,6 +670,7 @@ dependencies = ["tauri-plugin-dialog","tauri-plugin-log","tauri-plugin-single-instance",+ "tiny_http","tokio","tonic","ts-rs",@@ -5138,6 +5151,18 @@ dependencies = ["time-core",]+[[package]]+name = "tiny_http"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"+dependencies = [+ "ascii",+ "chunked_transfer",+ "httpdate",+ "log",+]+[[package]]name = "tinystr"version = "0.8.3"diff --git a/gui/src-tauri/Cargo.toml b/gui/src-tauri/Cargo.tomlindex ad2d678f..c2a87eea 100644--- a/gui/src-tauri/Cargo.toml+++ b/gui/src-tauri/Cargo.toml@@ -49,6 +49,7 @@ uuid = { version = "1.23.0", features = ["v4", "serde"] }portable-pty = "0.9.0"image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp"] }base64 = "0.22"+tiny_http = "0.12"[dev-dependencies]pretty_assertions = "1.4.1"diff --git a/gui/src-tauri/src/debug_bridge.rs b/gui/src-tauri/src/debug_bridge.rsnew file mode 100644index 00000000..a2f0a474--- /dev/null+++ b/gui/src-tauri/src/debug_bridge.rs@@ -0,0 +1,296 @@+//! Dev-only debug bridge: a localhost HTTP server that lets an external agent+//! (or a test harness) drive the *native* Tauri webview — evaluate JS with+//! return values, capture the real window, and synthesize input. This is the+//! "agentic remote control" for the desktop app, mirroring what a CDP session+//! gives you for a browser tab.+//!+//! Gate: the HTTP server only starts in debug builds (`cfg(debug_assertions)`).+//! The command + type are always compiled so the `invoke_handler!` list is+//! stable across configurations; in release the command is a harmless no-op+//! (nothing is ever pending because the server never runs).++use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{mpsc, Arc, Mutex};+use std::time::Duration;++use tauri::{AppHandle, Manager};++const PORT: u16 = 9233;+const EVAL_TIMEOUT: Duration = Duration::from_secs(8);++#[derive(Debug)]+struct EvalResult {+ ok: bool,+ value: Option<String>,+ error: Option<String>,+}++/// Shared state holding pending eval requests and a handle to the app. Cheap to+/// clone (Arc-backed); one copy lives in Tauri's managed state (so the+/// `cg_debug_eval_result` command can resolve requests), another in the server+/// thread.+#[derive(Clone)]+pub struct DebugBridge {+ app: AppHandle,+ pending: Arc<Mutex<HashMap<u64, mpsc::Sender<EvalResult>>>>,+ next_id: Arc<AtomicU64>,+}++impl DebugBridge {+ pub fn new(app: AppHandle) -> Self {+ Self {+ app,+ pending: Arc::new(Mutex::new(HashMap::new())),+ next_id: Arc::new(AtomicU64::new(1)),+ }+ }++ /// Invoked from the webview (via `__TAURI_INTERNALS__.invoke`) to return an+ /// eval result. No-op when nothing is pending (e.g. release builds).+ pub fn resolve(&self, id: u64, ok: bool, value: Option<String>, error: Option<String>) {+ let sender = self+ .pending+ .lock()+ .ok()+ .and_then(|mut map| map.remove(&id));+ if let Some(tx) = sender {+ let _ = tx.send(EvalResult { ok, value, error });+ }+ }++ /// Launch the HTTP server. Only does something in debug builds.+ pub fn start(self) {+ #[cfg(debug_assertions)]+ {+ std::thread::spawn(move || run_server(self));+ }+ #[cfg(not(debug_assertions))]+ {+ let _ = self;+ }+ }+}++/// Tauri command the webview calls to deliver an eval result back to Rust.+/// Always registered; harmless when the bridge isn't running.+#[tauri::command]+#[allow(dead_code)]+pub fn cg_debug_eval_result(+ id: u64,+ ok: bool,+ value: Option<String>,+ error: Option<String>,+ state: tauri::State<'_, DebugBridge>,+) {+ state.resolve(id, ok, value, error);+}++#[cfg(debug_assertions)]+fn run_server(bridge: DebugBridge) {+ let server = match tiny_http::Server::http(format!("127.0.0.1:{PORT}")) {+ Ok(s) => s,+ Err(error) => {+ log::error!("debug bridge failed to bind 127.0.0.1:{PORT}: {error}");+ return;+ }+ };+ log::info!("debug bridge listening on http://127.0.0.1:{PORT}");++ for mut request in server.incoming_requests() {+ let method = request.method().as_str().to_string();+ let url = request.url().to_string();+ let response = handle_request(&method, &url, &mut request, &bridge);+ let _ = request.respond(response);+ }+}++#[cfg(debug_assertions)]+fn handle_request(+ method: &str,+ url: &str,+ request: &mut tiny_http::Request,+ bridge: &DebugBridge,+) -> tiny_http::Response<std::io::Cursor<Vec<u8>>> {+ match (method, url) {+ ("GET", "/health") => json_response(200, r#"{"ok":true}"#),+ ("POST", "/eval-result") => {+ let mut body = String::new();+ if request.as_reader().read_to_string(&mut body).is_err() {+ return json_response(400, r#"{"ok":false}"#);+ }+ if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&body) {+ let id = parsed.get("id").and_then(|v| v.as_u64()).unwrap_or(0);+ let ok = parsed.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);+ let value = parsed+ .get("value")+ .and_then(|v| v.as_str())+ .map(|s| s.to_string());+ let error = parsed+ .get("error")+ .and_then(|v| v.as_str())+ .map(|s| s.to_string());+ bridge.resolve(id, ok, value, error);+ }+ json_response(200, r#"{"ok":true}"#)+ }+ ("POST", "/eval") => {+ let mut body = String::new();+ if request.as_reader().read_to_string(&mut body).is_err() {+ return json_response(400, r#"{"ok":false,"error":"bad body"}"#);+ }+ let parsed: serde_json::Value = match serde_json::from_str(&body) {+ Ok(v) => v,+ Err(_) => return json_response(400, r#"{"ok":false,"error":"bad json"}"#),+ };+ let code = match parsed.get("code").and_then(|v| v.as_str()) {+ Some(c) => c,+ None => {+ return json_response(400, r#"{"ok":false,"error":"missing code"}"#)+ }+ };+ handle_eval(bridge, code)+ }+ ("GET", "/screenshot") => match capture_screenshot(&bridge.app) {+ Ok(bytes) => tiny_http::Response::from_data(bytes)+ .with_header(tiny_http::Header::from_bytes(+ b"Content-Type".as_ref(),+ b"image/png".as_ref(),+ )+ .unwrap()),+ Err(error) => json_response(+ 500,+ &format!(r#"{{"ok":false,"error":{}}}"#, serde_json::json!(error)),+ ),+ },+ _ => json_response(404, r#"{"ok":false,"error":"not found"}"#),+ }+}++#[cfg(debug_assertions)]+fn handle_eval(bridge: &DebugBridge, code: &str) -> tiny_http::Response<std::io::Cursor<Vec<u8>>> {+ let id = bridge.next_id.fetch_add(1, Ordering::Relaxed);+ let (tx, rx) = mpsc::channel();+ if let Ok(mut map) = bridge.pending.lock() {+ map.insert(id, tx);+ } else {+ return json_response(500, r#"{"ok":false,"error":"state lock"}"#);+ }++ // Inject the user's code directly (no inner `eval()` — Tauri's default CSP+ // blocks `eval`/`new Function`, so we inline the code as the body of an+ // async arrow that evaluates it as an expression). The result is returned+ // via Tauri's native IPC (`__TAURI_INTERNALS__.invoke`), which is CSP-exempt+ // — unlike `fetch`, native invoke always works. The value is+ // JSON.stringified in JS so any serializable DOM state round-trips cleanly.+ // NB: `code` is inlined raw, so it must be a balanced expression (wrap+ // statements in an IIFE).+ let js = format!(+ "(async()=>{{const id={id};const send=(o)=>{{try{{window.__TAURI_INTERNALS__.invoke('cg_debug_eval_result',o)}}catch(_){{}}}};try{{const r=await (async()=>({user_code}))();let v;try{{v=JSON.stringify(r)}}catch(_){{v=String(r)}}send({{id,ok:true,value:v}})}}catch(e){{send({{id,ok:false,error:(e&&e.stack)||String(e)}})}}}})()",+ id = id,+ user_code = code,+ );++ let window = bridge.app.get_webview_window("main");+ if window.is_none() {+ drop_pending(bridge, id);+ return json_response(503, r#"{"ok":false,"error":"no main window"}"#);+ }+ log::info!("[debug-bridge] eval id={id}");+ if let Err(error) = window.unwrap().eval(&js) {+ drop_pending(bridge, id);+ return json_response(+ 500,+ &format!(r#"{{"ok":false,"error":{}}}"#, serde_json::json!(error.to_string())),+ );+ }++ match rx.recv_timeout(EVAL_TIMEOUT) {+ Ok(result) => {+ let body = serde_json::json!({+ "ok": result.ok,+ "value": result.value,+ "error": result.error,+ });+ json_response(200, &body.to_string())+ }+ Err(_) => {+ drop_pending(bridge, id);+ json_response(504, r#"{"ok":false,"error":"eval timeout"}"#)+ }+ }+}++#[cfg(debug_assertions)]+fn drop_pending(bridge: &DebugBridge, id: u64) {+ if let Ok(mut map) = bridge.pending.lock() {+ map.remove(&id);+ }+}++/// Capture the main window: focus it, grab the full screen via `screencapture`,+/// then crop to the window's physical bounds (which match screencapture's pixel+/// space, even on retina). Uses only the already-vendored `image` crate.+#[cfg(debug_assertions)]+fn capture_screenshot(app: &AppHandle) -> Result<Vec<u8>, String> {+ let window = app+ .get_webview_window("main")+ .ok_or_else(|| "no main window".to_string())?;+ let _ = window.set_focus();+ std::thread::sleep(Duration::from_millis(150));++ let pos = window.outer_position().map_err(|e| e.to_string())?;+ let size = window.outer_size().map_err(|e| e.to_string())?;+ let x = pos.x.max(0) as u32;+ let y = pos.y.max(0) as u32;+ let w = size.width;+ let h = size.height;++ let tmp = std::env::temp_dir().join("cg_debug_full.png");+ let status = std::process::Command::new("screencapture")+ .arg("-x")+ .arg(&tmp)+ .status()+ .map_err(|e| e.to_string())?;+ if !status.success() {+ return Err("screencapture failed".to_string());+ }++ let img = image::open(&tmp).map_err(|e| e.to_string())?;+ let img_w = img.width();+ let img_h = img.height();+ // Clamp the crop rect to the captured image (window may extend off-screen).+ let cw = w.min(img_w.saturating_sub(x));+ let ch = h.min(img_h.saturating_sub(y));+ if cw == 0 || ch == 0 {+ return Err("window not visible on primary display".to_string());+ }+ let cropped = img.crop_imm(x, y, cw, ch);++ let mut buf = Vec::new();+ let mut cursor = std::io::Cursor::new(&mut buf);+ cropped+ .write_to(&mut cursor, image::ImageFormat::Png)+ .map_err(|e| e.to_string())?;+ Ok(buf)+}++#[cfg(debug_assertions)]+fn json_response(code: u16, body: &str) -> tiny_http::Response<std::io::Cursor<Vec<u8>>> {+ tiny_http::Response::from_data(body.as_bytes().to_vec())+ .with_status_code(code)+ .with_header(+ tiny_http::Header::from_bytes(+ b"Content-Type".as_ref(),+ b"application/json".as_ref(),+ )+ .unwrap(),+ )+ .with_header(+ tiny_http::Header::from_bytes(+ b"Access-Control-Allow-Origin".as_ref(),+ b"*".as_ref(),+ )+ .unwrap(),+ )+}diff --git a/gui/src-tauri/src/lib.rs b/gui/src-tauri/src/lib.rsindex dc5598af..109c341e 100644--- a/gui/src-tauri/src/lib.rs+++ b/gui/src-tauri/src/lib.rs@@ -1,5 +1,6 @@mod commands;mod cli_install;+mod debug_bridge;mod desktop_open;pub mod dto;mod forge_config_home;@@ -88,6 +89,12 @@ pub fn run() {))));// First run: install the `codegraff` launcher command on PATH (macOS).cli_install::ensure_cli_symlink(app);+ #[cfg(debug_assertions)]+ {+ let bridge = debug_bridge::DebugBridge::new(app.handle().clone());+ app.manage(bridge.clone());+ bridge.start();+ }Ok(())}).on_window_event(|window, event| {@@ -162,7 +169,8 @@ pub fn run() {terminal_write,terminal_resize,terminal_close,- drain_pending_open+ drain_pending_open,+ debug_bridge::cg_debug_eval_result]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/gui/src/app/App.tsx b/gui/src/app/App.tsxindex 36ff6a9d..7858847c 100644--- a/gui/src/app/App.tsx+++ b/gui/src/app/App.tsx@@ -133,6 +133,10 @@ function AppShell() {const sidebarPanelRef = useRef<PanelImperativeHandle | null>(null);const [isSidebarAnimating, setIsSidebarAnimating] = useState(false);const sidebarAnimateTimeoutRef = useRef<number | null>(null);+ // Holds the latest openNewChat from the always-mounted NewChatTrigger so the+ // global Cmd/Ctrl+N shortcut can invoke it (including its git-worktree choice+ // dialog) no matter what's visible.+ const newChatRef = useRef<(() => void) | null>(null);// Briefly enable a width transition on the panels so toggling the sidebar// slides smoothly (like the artifacts drawer) instead of snapping. Kept off// during drag-resize so dragging stays 1:1 with the cursor.@@ -227,6 +231,24 @@ function AppShell() {};}, []);+ // Global Cmd/Ctrl+N → new chat. Reuses NewChatTrigger's openNewChat (captured+ // in newChatRef) so the git-worktree choice dialog flows through identically.+ // Skipped while a settings view or dialog is open or while the session is+ // mid-bootstrap, and ignores key presses originating inside an input/textarea+ // so it never fights typing — though Cmd+N is uncommon enough to be safe.+ useEffect(() => {+ function handleKeyDown(event: KeyboardEvent) {+ if (!(event.metaKey || event.ctrlKey) || event.key !== "n") {+ return;+ }+ event.preventDefault();+ newChatRef.current?.();+ }++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, []);+if (!isSessionBootstrapped) {return (<main className="app-shell relative flex h-screen w-full items-center justify-center overflow-hidden bg-background">@@ -265,9 +287,13 @@ function AppShell() {});}}/>- {!isDesktopSidebarVisible && !isSettingsViewOpen ? (- <NewChatTrigger>- {({ isBusy, openNewChat }) => (+ <NewChatTrigger>+ {({ isBusy, openNewChat }) => {+ newChatRef.current = openNewChat;+ if (isDesktopSidebarVisible || isSettingsViewOpen) {+ return null;+ }+ return (<Buttonvariant="ghost"size="icon-sm"@@ -279,9 +305,9 @@ function AppShell() {<PenSquare strokeWidth={2} className="size-3.5" /><span className="sr-only">New chat</span></Button>- )}- </NewChatTrigger>- ) : null}+ );+ }}+ </NewChatTrigger><ResizablePanelGroup orientation="horizontal"><ResizablePanelid="sidebar-panel"diff --git a/gui/src/components/PromptInputCard.tsx b/gui/src/components/PromptInputCard.tsxindex dd7fd007..813844ec 100644--- a/gui/src/components/PromptInputCard.tsx+++ b/gui/src/components/PromptInputCard.tsx@@ -65,6 +65,12 @@ export function PromptInputCard({updatePromptSettings,}: PromptInputCardProps) {const textareaRef = useRef<HTMLTextAreaElement | null>(null);+ // The transparent-text overlay must scroll in lockstep with the textarea so the+ // highlighted slash-command token stays aligned when the draft exceeds max-h-80+ // and the textarea becomes scrollable. Without syncing, the overlay (overflow-+ // hidden, pinned to inset-0) stays put while the textarea content scrolls under+ // it — the highlight drifts away from the caret.+ const commandOverlayRef = useRef<HTMLDivElement | null>(null);const dropZoneRef = useRef<HTMLDivElement | null>(null);const { attachments, addAttachments, removeAttachment } =useAttachments(binding);@@ -76,10 +82,17 @@ export function PromptInputCard({});const isControlDisabled =isSendingPrompt || isRequestActive || !canCompose || isInputDisabled;+ // Keep the composer editable while a request streams so the user can draft+ // their next message; only Send is repurposed to Stop. Enter is guarded by+ // isSubmitDisabled (which includes isRequestActive) so a draft is never sent+ // mid-stream — it just waits until the run finishes.+ const isTextareaDisabled =+ isSendingPrompt || !canCompose || isInputDisabled;const isWorking = isRequestActive;const isSubmitDisabled =!canCompose ||isSendingPrompt ||+ isRequestActive ||isInputDisabled ||promptDraft.trim().length === 0;const {@@ -236,6 +249,7 @@ export function PromptInputCard({<div className="relative m-1">{commandMatch ? (<div+ ref={commandOverlayRef}aria-hiddenclassName="pointer-events-none absolute inset-0 max-h-80 overflow-hidden whitespace-pre-wrap break-words text-sm">@@ -256,6 +270,12 @@ export function PromptInputCard({value={promptDraft}onChange={(event) => setPromptDraft(event.target.value)}onPaste={handlePaste}+ onScroll={(event) => {+ if (commandOverlayRef.current != null) {+ commandOverlayRef.current.scrollTop =+ event.currentTarget.scrollTop;+ }+ }}onKeyDown={(event) => {// The command menu consumes Enter/Tab/arrows while open, so a// command is completed rather than sent.@@ -284,7 +304,7 @@ export function PromptInputCard({handleSubmit();}}}- disabled={isControlDisabled}+ disabled={isTextareaDisabled}rows={3}/></div>diff --git a/gui/src/components/SidebarItemActionsMenu.tsx b/gui/src/components/SidebarItemActionsMenu.tsxindex ff91bf7a..de2ff9a0 100644--- a/gui/src/components/SidebarItemActionsMenu.tsx+++ b/gui/src/components/SidebarItemActionsMenu.tsx@@ -36,10 +36,13 @@ export function SidebarItemActionsMenu({removeLabel = "Remove",renameLabel = "Rename",allowEmptyName = false,+ removeConfirmTitle,+ removeConfirmDescription,}: SidebarItemActionsMenuProps) {const [isRenameDialogOpen, setIsRenameDialogOpen] = useState(false);const [isRenamePending, setIsRenamePending] = useState(false);const [nameDraft, setNameDraft] = useState(currentName);+ const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false);const renameInputRef = useRef<HTMLInputElement | null>(null);useFocusOnOpen(renameInputRef, {@@ -71,6 +74,11 @@ export function SidebarItemActionsMenu({}}+ function handleRemoveConfirm() {+ onRemove();+ setIsRemoveDialogOpen(false);+ }+return (<><DropdownMenu>@@ -101,7 +109,12 @@ export function SidebarItemActionsMenu({<PencilLineIcon />{renameLabel}</DropdownMenuItem>- <DropdownMenuItem variant="destructive" onClick={onRemove}>+ <DropdownMenuItem+ variant="destructive"+ onClick={() => {+ setIsRemoveDialogOpen(true);+ }}+ ><RemoveIcon />{removeLabel}</DropdownMenuItem>@@ -155,6 +168,40 @@ export function SidebarItemActionsMenu({</div></DialogContent></Dialog>++ <Dialog+ open={isRemoveDialogOpen}+ onOpenChange={(open) => {+ setIsRemoveDialogOpen(open);+ }}+ >+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>+ {removeConfirmTitle ?? `Remove ${currentName}?`}+ </DialogTitle>+ <DialogDescription>+ {removeConfirmDescription ?? "This can't be undone."}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => setIsRemoveDialogOpen(false)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="destructive"+ onClick={handleRemoveConfirm}+ >+ {removeLabel}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog></>);}diff --git a/gui/src/components/chat/ChatActivityRow.tsx b/gui/src/components/chat/ChatActivityRow.tsxindex 7ab62b77..272a16c0 100644--- a/gui/src/components/chat/ChatActivityRow.tsx+++ b/gui/src/components/chat/ChatActivityRow.tsx@@ -183,18 +183,25 @@ export function ChatActivityRow({ item, workspacePath }: ChatActivityRowProps) {);const previousRunningRef = useRef(item.isRunning);+ // With stable keys (ChatWorkRow) this effect now actually fires on the+ // running→idle transition instead of being wiped by a remount. On completion+ // we preserve the user's view — keep the activity open (don't yank the results+ // they were reading) and force-open on error so failures stay visible. A+ // step starting to run auto-expands to show live progress.useEffect(() => {+ const wasRunning = previousRunningRef.current;+ previousRunningRef.current = item.isRunning;if (item.isThinking) {return;}- if (previousRunningRef.current && item.isRunning === false) {- setOpen(item.hasError);- } else if (previousRunningRef.current === false && item.isRunning) {+ if (wasRunning && !item.isRunning) {+ if (item.hasError) {+ setOpen(true);+ }+ } else if (!wasRunning && item.isRunning) {setOpen(true);}-- previousRunningRef.current = item.isRunning;}, [item.hasError, item.isRunning, item.isThinking]);if (item.isThinking) {diff --git a/gui/src/components/chat/ChatThread.tsx b/gui/src/components/chat/ChatThread.tsxindex 60a9668d..fac2d245 100644--- a/gui/src/components/chat/ChatThread.tsx+++ b/gui/src/components/chat/ChatThread.tsx@@ -4,8 +4,9 @@ import type {NativeScrollEvent,NativeSyntheticEvent,} from "@legendapp/list/react";-import { useCallback, useEffect, useRef } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import type { WheelEvent } from "react";+import { ArrowDownIcon } from "lucide-react";import { CHAT_BADGE_TEXT_CLASS } from "./constants/chatStyles";import type { ChatThreadProps } from "./types/chatComponents";@@ -29,6 +30,12 @@ export function ChatThread({const lastScrollOffsetRef = useRef<number | null>(null);const followFrameRefs = useRef<number[]>([]);const lastSeenPromptIdRef = useRef<string | null>(null);+ const previousItemCountRef = useRef(0);+ // Mirror of isFollowingRef for rendering (the pill). Pending count tracks how+ // many new items landed while the user was scrolled up, so the pill can say+ // "3 new" instead of just "scroll to latest".+ const [isFollowing, setIsFollowing] = useState(true);+ const [pendingCount, setPendingCount] = useState(0);const latestSentPromptId = (() => {for (let index = messages.length - 1; index >= 0; index -= 1) {const message = messages[index];@@ -47,6 +54,14 @@ export function ChatThread({})),];+ const setFollowing = useCallback((next: boolean) => {+ isFollowingRef.current = next;+ setIsFollowing(next);+ if (next) {+ setPendingCount(0);+ }+ }, []);+const markProgrammaticScroll = useCallback(() => {isProgrammaticScrollRef.current = true;requestAnimationFrame(() => {@@ -105,6 +120,17 @@ export function ChatThread({});}, [scrollToBottom]);+ // Count new items that arrive while the user is scrolled up, so the+ // jump-to-latest pill can surface "N new" rather than silently accumulating+ // content off-screen.+ useEffect(() => {+ const previous = previousItemCountRef.current;+ previousItemCountRef.current = items.length;+ if (items.length > previous && !isFollowingRef.current) {+ setPendingCount((count) => count + (items.length - previous));+ }+ }, [items.length]);+// The thread re-renders on every streaming update, so keep locked chats pinned// after both React commit and LegendList's follow-up layout measurements.useEffect(() => {@@ -133,9 +159,9 @@ export function ChatThread({}lastSeenPromptIdRef.current = latestSentPromptId;userWantsFollowRef.current = true;- isFollowingRef.current = true;+ setFollowing(true);scheduleFollowToBottom();- }, [latestSentPromptId, scheduleFollowToBottom]);+ }, [latestSentPromptId, scheduleFollowToBottom, setFollowing]);const handleScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {@@ -153,7 +179,7 @@ export function ChatThread({!isProgrammaticScrollRef.current) {userWantsFollowRef.current = false;- isFollowingRef.current = false;+ setFollowing(false);}if (offset > (previousOffset ?? offset)) {@@ -161,67 +187,87 @@ export function ChatThread({}if (isAtBottom && userWantsFollowRef.current && !isFollowingRef.current) {- isFollowingRef.current = true;+ setFollowing(true);scheduleFollowToBottom();}lastScrollOffsetRef.current = offset;},- [scheduleFollowToBottom],+ [scheduleFollowToBottom, setFollowing],);// Wheel intent gives immediate scroll-lock feedback for mouse and trackpad users.const handleWheel = useCallback((event: WheelEvent) => {if (event.deltaY < 0) {userWantsFollowRef.current = false;- isFollowingRef.current = false;+ setFollowing(false);return;}if (event.deltaY > 0) {userWantsFollowRef.current = true;}- }, []);+ }, [setFollowing]);++ const handleJumpToLatest = useCallback(() => {+ userWantsFollowRef.current = true;+ setFollowing(true);+ scrollToBottom();+ }, [scrollToBottom, setFollowing]);return (- <LegendList- ref={listRef}- data={items}- renderItem={(props) =>- renderChatThreadItem(props, {- requestTimingsById,- workspacePath,- itemCount: items.length,- })- }- keyExtractor={(item) => item.key}- getItemType={(item) =>- item.kind === "message" ? item.message.kind : item.kind- }- onScroll={handleScroll}- onWheel={handleWheel}- initialScrollAtEnd={items.length > 0}- estimatedItemSize={88}- style={{ height: "100%" }}- contentContainerStyle={{- paddingTop: 20,- paddingBottom: 24,- }}- ListEmptyComponent={- <div className="mx-auto flex min-h-full w-full max-w-3xl items-center justify-center px-6 py-12">- <div className="w-full rounded-3xl border border-black/5 bg-black/5 px-8 py-10 text-center dark:border-white/10 dark:bg-white/5">- <p className={`${CHAT_BADGE_TEXT_CLASS} text-muted-foreground`}>- New chat- </p>- <h2 className="mt-3 text-2xl font-semibold tracking-tight text-foreground">- Ask anything about {workspaceLabel}- </h2>- <p className="mt-3 text-sm leading-6 text-muted-foreground">- Start with a question, a task, or a change you want to make in- this workspace.- </p>+ <div className="relative h-full">+ <LegendList+ ref={listRef}+ data={items}+ renderItem={(props) =>+ renderChatThreadItem(props, {+ requestTimingsById,+ workspacePath,+ itemCount: items.length,+ })+ }+ keyExtractor={(item) => item.key}+ getItemType={(item) =>+ item.kind === "message" ? item.message.kind : item.kind+ }+ onScroll={handleScroll}+ onWheel={handleWheel}+ initialScrollAtEnd={items.length > 0}+ estimatedItemSize={88}+ style={{ height: "100%" }}+ contentContainerStyle={{+ paddingTop: 20,+ paddingBottom: 24,+ }}+ ListEmptyComponent={+ <div className="mx-auto flex min-h-full w-full max-w-3xl items-center justify-center px-6 py-12">+ <div className="w-full rounded-3xl border border-black/5 bg-black/5 px-8 py-10 text-center dark:border-white/10 dark:bg-white/5">+ <p className={`${CHAT_BADGE_TEXT_CLASS} text-muted-foreground`}>+ New chat+ </p>+ <h2 className="mt-3 text-2xl font-semibold tracking-tight text-foreground">+ Ask anything about {workspaceLabel}+ </h2>+ <p className="mt-3 text-sm leading-6 text-muted-foreground">+ Start with a question, a task, or a change you want to make in+ this workspace.+ </p>+ </div></div>+ }+ />+ {!isFollowing ? (+ <div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center px-4">+ <button+ type="button"+ onClick={handleJumpToLatest}+ className="pointer-events-auto inline-flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-foreground shadow-[var(--elevation-md)] transition hover:bg-accent hover:text-accent-foreground"+ >+ <ArrowDownIcon className="size-3.5" />+ {pendingCount > 0 ? `${pendingCount} new` : "Scroll to latest"}+ </button></div>- }- />+ ) : null}+ </div>);}diff --git a/gui/src/components/chat/ChatWorkRow.tsx b/gui/src/components/chat/ChatWorkRow.tsxindex c98d5a1d..74d91c30 100644--- a/gui/src/components/chat/ChatWorkRow.tsx+++ b/gui/src/components/chat/ChatWorkRow.tsx@@ -1,4 +1,4 @@-import { useState } from "react";+import { useEffect, useRef, useState } from "react";import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";import { CHAT_MUTED_TEXT_CLASS } from "./constants/chatStyles";@@ -40,6 +40,21 @@ export function ChatWorkRow({workspacePath,}: ChatWorkRowProps) {const [open, setOpen] = useState(item.isRunning || item.hasError);+ const previousRunningRef = useRef(item.isRunning);++ // Drive open state from running→idle transitions WITHOUT remounting. Stable+ // keys (here and in chatThreadList) preserve the user's manual expands across+ // completion. On a clean finish we leave the group open so the results the+ // user was watching don't collapse out from under them; errors force-open.+ // Past (already-idle) turns mount collapsed via the initial state above.+ useEffect(() => {+ const wasRunning = previousRunningRef.current;+ previousRunningRef.current = item.isRunning;+ if (wasRunning && !item.isRunning && item.hasError) {+ setOpen(true);+ }+ }, [item.isRunning, item.hasError]);+const canExpand = item.activities.length > 0;const header = (@@ -78,7 +93,7 @@ export function ChatWorkRow({<div className="grid min-w-0 gap-1">{item.activities.map((activityItem) => (<ChatActivityRow- key={`${activityItem.key}:${activityItem.isRunning ? "running" : activityItem.hasError ? "error" : "idle"}`}+ key={activityItem.key}item={activityItem}workspacePath={workspacePath}/>diff --git a/gui/src/components/chat/utils/chatThreadList.tsx b/gui/src/components/chat/utils/chatThreadList.tsxindex 5c4abe92..5857f5ec 100644--- a/gui/src/components/chat/utils/chatThreadList.tsx+++ b/gui/src/components/chat/utils/chatThreadList.tsx@@ -104,7 +104,7 @@ export function renderChatThreadItem(renderChatMessage(item.message, workspacePath)) : item.kind === "request_work" ? (<ChatWorkRow- key={`${item.key}:${item.isRunning ? "running" : item.hasError ? "error" : "idle"}`}+ key={item.key}item={item}requestTiming={requestTimingsById[item.requestId]}workspacePath={workspacePath}diff --git a/gui/src/components/conversation-panel/ConversationDockviewTab.tsx b/gui/src/components/conversation-panel/ConversationDockviewTab.tsxindex e6124ac4..0cd33cc0 100644--- a/gui/src/components/conversation-panel/ConversationDockviewTab.tsx+++ b/gui/src/components/conversation-panel/ConversationDockviewTab.tsx@@ -5,11 +5,11 @@ import {Breadcrumb,BreadcrumbItem,BreadcrumbList,- BreadcrumbPage,} from "@/components/ui/Breadcrumb";import { cn } from "@/utils/cn";import { BranchSwitcherMenu } from "./BranchSwitcherMenu";+import { ProjectSwitcherMenu } from "./ProjectSwitcherMenu";import { useConversationHeaderState } from "./hooks/useConversationHeaderState";import type { ConversationDockviewTabProps } from "./types/conversationHeader";@@ -23,15 +23,20 @@ export function ConversationDockviewTab({branchSearchInputRef,canCreateBranch,conversationTitle,+ currentProjectLabel,filteredBranches,isBranchMenuOpen,isGitActionPending,isManagedChat,+ isProjectChangePending,+ projects,repoName,+ selectedProjectPath,setBranchQuery,handleBranchCreate,handleBranchMenuOpenChange,handleBranchSelect,+ handleProjectSelect,} = useConversationHeaderState(binding);const isSidebarVisible = useSidebarVisible();// When the sidebar is collapsed the tile sits flush against the window's@@ -58,13 +63,28 @@ export function ConversationDockviewTab({<Breadcrumb className="min-w-0"><BreadcrumbList className="min-w-0 flex-nowrap"><BreadcrumbItem className="min-w-0">- <BreadcrumbPage className="pointer-events-none inline-flex min-w-0 items-center gap-1.5 text-xs font-medium text-foreground">+ <div+ className="flex min-w-0 shrink items-center gap-1.5"+ onPointerDownCapture={(event) => {+ event.stopPropagation();+ }}+ onDragStartCapture={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ ><GitForkstrokeWidth={2}className="size-3 shrink-0 text-muted-foreground"/>- <span className="truncate">{repoName}</span>- </BreadcrumbPage>+ <ProjectSwitcherMenu+ currentProjectLabel={repoName ?? currentProjectLabel}+ isBusy={isProjectChangePending}+ projects={projects}+ selectedProjectPath={selectedProjectPath}+ onSelectProject={handleProjectSelect}+ />+ </div></BreadcrumbItem>{branchName ? (diff --git a/gui/src/components/conversation-panel/ConversationHeaderActions.tsx b/gui/src/components/conversation-panel/ConversationHeaderActions.tsxindex f94159af..7013441d 100644--- a/gui/src/components/conversation-panel/ConversationHeaderActions.tsx+++ b/gui/src/components/conversation-panel/ConversationHeaderActions.tsx@@ -4,7 +4,6 @@ import {FileDiffIcon,FolderIcon,GitBranchPlusIcon,- LayoutPanelTopIcon,SquareTerminalIcon,XIcon,} from "lucide-react";@@ -32,7 +31,6 @@ export function ConversationHeaderActions({onCloseChat,onHandoffToLocal,onHandoffToWorktree,- onOpenPreview,onOpenTerminal,onOpenChanges,isChangesOpen = false,@@ -152,14 +150,6 @@ export function ConversationHeaderActions({</DropdownMenuTrigger><DropdownMenuContent align="end" className="w-48"><DropdownMenuGroup>- <DropdownMenuItem- onClick={() => {- onOpenPreview?.();- }}- >- <LayoutPanelTopIcon />- Open Preview- </DropdownMenuItem><DropdownMenuItemonClick={() => {onOpenTerminal?.();diff --git a/gui/src/components/types/sidebar.ts b/gui/src/components/types/sidebar.tsindex a96c46c8..2b4d8b45 100644--- a/gui/src/components/types/sidebar.ts+++ b/gui/src/components/types/sidebar.ts@@ -61,6 +61,8 @@ export interface SidebarItemActionsMenuProps {removeLabel?: string;renameLabel?: string;allowEmptyName?: boolean;+ removeConfirmTitle?: string;+ removeConfirmDescription?: string;}export interface SidebarSettingsControlProps {diff --git a/gui/src/components/workspace-board/ChatTile.tsx b/gui/src/components/workspace-board/ChatTile.tsxindex e91d1994..a2acfe8f 100644--- a/gui/src/components/workspace-board/ChatTile.tsx+++ b/gui/src/components/workspace-board/ChatTile.tsx@@ -28,6 +28,14 @@ import { ConversationDockviewHeaderActions } from "@/components/conversation-panimport { ConversationDockviewTab } from "@/components/conversation-panel/ConversationDockviewTab";import { Button } from "@/components/ui/Button";import { ButtonGroup } from "@/components/ui/ButtonGroup";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/Dialog";import * as desktopClient from "@/services/desktop/client";import { AuxiliaryPaneShell } from "./AuxiliaryPaneShell";@@ -110,6 +118,10 @@ export function ChatTile({changes: false,terminal: false,});+ // Tracks how many terminal tabs would be destroyed by the toggle-close so the+ // confirmation dialog can warn the user. Closing a single terminal is normal+ // toggle behavior; closing 2+ at once (each with its own PTY) is destructive.+ const [closeTerminalsCount, setCloseTerminalsCount] = useState(0);// Briefly enables a width/position transition on the dock's view containers so// chat glides to its new size when a pane opens/closes (see chat-tile-dockview.css).// Toggled imperatively (not via state) so the class is in the DOM *before* the@@ -271,10 +283,13 @@ export function ChatTile({const terminals = getTerminalPanels(api);if (terminals.length > 0) {- // Re-clicking the toggle closes the whole bottom terminal panel.- for (const panel of terminals) {- dispatchPaneCloseRequest(`${binding.conversationId}:${panel.id}`);+ // A single terminal closes immediately (normal toggle). Two or more tabs+ // each hold a live PTY, so confirm before tearing them all down at once.+ if (terminals.length > 1) {+ setCloseTerminalsCount(terminals.length);+ return;}+ dispatchPaneCloseRequest(`${binding.conversationId}:${terminals[0].id}`);return;}@@ -283,6 +298,18 @@ export function ChatTile({scheduleInnerLayoutSave();}, [binding, runLayoutAnimation, scheduleInnerLayoutSave, withProgrammaticMutation]);+ const handleCloseAllTerminalsConfirm = useCallback(() => {+ const api = innerApiRef.current;+ if (api == null) {+ setCloseTerminalsCount(0);+ return;+ }+ for (const panel of getTerminalPanels(api)) {+ dispatchPaneCloseRequest(`${binding.conversationId}:${panel.id}`);+ }+ setCloseTerminalsCount(0);+ }, [binding.conversationId]);+const handleAddTerminal = useCallback(() => {const api = innerApiRef.current;if (api == null) {@@ -652,6 +679,40 @@ export function ChatTile({tabComponents={tabComponents}theme={theme}/>+ <Dialog+ open={closeTerminalsCount > 0}+ onOpenChange={(open) => {+ if (!open) {+ setCloseTerminalsCount(0);+ }+ }}+ >+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>Close {closeTerminalsCount} terminals?</DialogTitle>+ <DialogDescription>+ This closes every terminal tab and ends its shell session. This+ can't be undone.+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => setCloseTerminalsCount(0)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="destructive"+ onClick={handleCloseAllTerminalsConfirm}+ >+ Close terminals+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog></section>);}diff --git a/scripts/tdev b/scripts/tdevnew file mode 100755index 00000000..a2ed0129--- /dev/null+++ b/scripts/tdev@@ -0,0 +1,75 @@+#!/usr/bin/env bash+# tdev — agentic remote control for the native Tauri app.+#+# Talks to the dev-only debug bridge (debug_bridge.rs) that runs inside the+# Codegraff desktop app on http://127.0.0.1:9233. Lets an agent (or human)+# evaluate JS in the real webview WITH return values, screenshot the window,+# and synthesize clicks/keys — all via curl, against the native app.+#+# tdev health bridge alive?+# tdev eval '<js>' run JS in webview, print JSON result+# tdev shot [file] screenshot the app window → png (default ./tdev_shot.png)+# tdev click '<sel>' click the first element matching a CSS selector+# tdev type '<sel>' '<text>' set input value + dispatch input event+# tdev key '<key>' [meta] dispatch a KeyboardEvent on window+# (meta = "meta" | "ctrl" | "shift" | "" )+#+# Examples:+# tdev eval 'document.querySelector("textarea#prompt")?.disabled'+# tdev eval 'document.title'+# tdev click 'button[aria-label="New chat"]'+# tdev key 'n' meta # fires the Cmd+N shortcut+# tdev shot++set -euo pipefail++HOST="http://127.0.0.1:9233"+SELF="$(readlink -f "$0" 2>/dev/null || echo "$0")"++usage() {+ sed -n '2,24p' "$SELF"+ exit 1+}++[ $# -ge 1 ] || usage+cmd="$1"; shift || true++case "$cmd" in+ health)+ curl -fsS "$HOST/health" && echo+ ;;+ eval)+ [ $# -ge 1 ] || { echo "usage: tdev eval '<js>'" >&2; exit 2; }+ code="$1"+ curl -fsS -X POST "$HOST/eval" \+ -H 'Content-Type: application/json' \+ -d "$(printf '%s' "$code" | python3 -c 'import sys,json; print(json.dumps({"code":sys.stdin.read()}))')" \+ | python3 -m json.tool+ ;;+ shot)+ out="${1:-./tdev_shot.png}"+ curl -fsS "$HOST/screenshot" -o "$out"+ echo "saved $out ($(wc -c < "$out" | tr -d ' ') bytes)"+ ;;+ click)+ [ $# -ge 1 ] || { echo "usage: tdev click '<selector>'" >&2; exit 2; }+ sel="$1"+ "$SELF" eval "(()=>{const e=document.querySelector($(python3 -c "import json,sys; print(json.dumps(sys.argv[1]))" "$sel"));if(!e)return null;e.scrollIntoView({block:'center'});e.click();return 'clicked'})()"+ ;;+ type)+ [ $# -ge 2 ] || { echo "usage: tdev type '<selector>' '<text>'" >&2; exit 2; }+ sel="$1"; text="$2"+ "$SELF" eval "(()=>{const e=document.querySelector($(python3 -c "import json,sys; print(json.dumps(sys.argv[1]))" "$sel"));if(!e)return null;const s=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,'value')?.set||Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value')?.set;s.call(e,$(python3 -c "import json,sys; print(json.dumps(sys.argv[1]))" "$text"));e.dispatchEvent(new Event('input',{bubbles:true}));return 'typed'})()"+ ;;+ key)+ [ $# -ge 1 ] || { echo "usage: tdev key '<key>' [meta]" >&2; exit 2; }+ key="$1"; meta="${2:-}"+ metaflag="false"+ [ "$meta" = "meta" ] && metaflag="true"+ [ "$meta" = "ctrl" ] && metaflag="true"+ "$SELF" eval "(()=>{window.dispatchEvent(new KeyboardEvent('keydown',{key:$(python3 -c "import json,sys; print(json.dumps(sys.argv[1]))" "$key"),metaKey:$metaflag,bubbles:true}));return 'keydown $key'})()"+ ;;+ *)+ usage+ ;;+esac