diff --git a/CLAUDE.md b/CLAUDE.md index 069f12c..9e5051f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,67 +1,50 @@ -# CLAUDE.md — Claudiu +# CLAUDE.md -The code is the source of truth. This file holds only rules. +Claudiu is a native Rust + GPUI desktop app that manages sessions around the user's existing `claude` CLI. -Maintain Claudiu as if you'll own it for years: prefer durable fixes over quick ones, push back when a request would hurt its long-term health, and leave the code simpler and easier to navigate than you found it (one job per module, names that are unambiguous and greppable, no dead or duplicate code, references updated when you move things). +## Settings + +- Tracker: GitHub issues in m4rocks/claudiu +- Tests: when a cheap test seam exists +- Commits: only when the maintainer says +- Pushes and pull requests: only when the maintainer says +- Closing issues: ask first +- Subagents: only when the maintainer asks + +## Working here + +GitHub issues hold intent, one issue per feature with a checklist in its body; the code and the maintainer decide what is true. +Check off items the code already does. Add entries for requests that aren't listed, and for problems you notice outside the task, rather than fixing those in passing, so every diff stays reviewable. Order is a suggestion: if a request seems to depend on unfinished work, say so in one line and continue. + +Care about the project's long-term health, not just the request in front of you. When a request would harm it, say so plainly and early, give your own recommendation, and don't agree just to be agreeable. Hold your position if the pushback brings no new information. Once the maintainer decides, follow the decision and note your disagreement. + +Ask the maintainer about product direction, scope, and anything irreversible or outward-facing, such as pushing, deleting data, adding a dependency or closing issues, unless the settings above allow it. Ask through the harness's structured question tool when it has one, recommended option first; otherwise ask one question per message with numbered options. Decide everything reversible yourself and report it. Ask a question only when you can't continue without a decision. Finishing a change is not such a point: report it in a line or two and stop, and leave committing and pushing to the settings or the maintainer's word. + +The maintainer can override any setting for a single request, for example "go autonomous, commit and push everything" or "ask before each commit"; the override lasts until that request is done. + +When a task finishes, say once what changed, what you skipped or couldn't check, and any risk. After that, follow the maintainer's current topic: raise finished work again only when the current topic affects it or they ask, and keep options about it out of questions on other subjects. + +When the m4 skills are installed, route requests through them even when phrased casually, because they carry the steps that keep work consistent: a bug or error goes through m4:fix, building or changing behavior through m4:do, reviewing a diff through m4:tidy, planning through m4:shape, explaining code through m4:explore, and a repeated correction through m4:harden. One-line edits are made directly. Before writing prose that lands somewhere, such as docs, a README, comments, commit or pull request text, tracker entries, or a message to another person, run m4:unslop on the draft. In chat replies, follow its rules without invoking it. + +Work inline; spawn subagents only as the settings allow, except the plan review in m4:shape, because they spend tokens the maintainer wants to spend deliberately. + +## Code + +People who don't use agents read and maintain this code, so aim for code that is obviously correct to a newcomer. Rank choices by correctness, then how easily the code reads and tests, then size; a one-liner that needs decoding is not simple. + +Build only what was asked: features, options and configuration nobody requested wait until someone needs them. How the requested thing is built is open. For non-trivial logic, weigh more than one shape and pick the one whose correctness is most obvious, even if it is unconventional. Before writing new code, look for it in this repo, then the standard library and platform, then installed dependencies. + +Before editing, find every place the change must reach (callers, tests, fixtures, config, exports) and finish all of them. When a better structure would make the task simpler, use it in this change; when it is bigger than the task, do the task and add the redesign to the tracker with a one-line reason. Keep validation of untrusted input, error handling that prevents data loss, security and accessibility, including in code you move. + +Comments explain why something non-obvious is true, such as a known limit and when it will matter. When code needs a comment to say what it does, rename or restructure it instead. Leave existing comments in code you don't change. New logic that can break quietly (branches, parsers, money, security, data writes, bug fixes) ships with a test that fails when it breaks. + +Leave nothing behind but the change: no summary files, commented-out code, debug logs or session scripts. When a test fails, fix the code, or ask if the test's expectation looks wrong. Update the README in the same commit when user-visible behavior changes. ## Boundaries -- Claudiu is a native Rust + GPUI desktop app that manages sessions around the user's existing `claude` CLI. Claude Code owns the agent experience; Claudiu owns the workspace. -- Never call the Anthropic API. Never implement or embed authentication, API keys or subscription login. Never impersonate Claude Desktop. -- Never type into a PTY on the user's behalf. -- Never run `claude -p` from Claudiu. Background one-shot text goes through the running session's mod. -- Never edit the main account's `~/.claude`. Alt accounts are separate folders passed with `CLAUDE_CONFIG_DIR`. -- Never write into Claude Code's private data or depend on undocumented transcript (JSONL) schemas. Prefer documented CLI interfaces and documented mod hooks. -- Do not edit Claude Code's settings files. A feature may ask Claude Code to change its own settings (such as `/model`) through the mod. -- Claude Code's own TUI is the only conversation view. Do not recreate its UI or protocol. -- Do not intercept Claude Code shortcuts. Reserve only explicit, documented Claudiu-global shortcuts. -- Never delete Claude Code session data as a side effect. Hiding a Claudiu entry must not delete a transcript. -- Nothing leaves the machine by default: no transcripts, project files, source, credentials, environment variables or API keys go to any Claudiu server. -- Do not log terminal contents. Persist environment variables only on explicit user opt-in. -- Use public crates and APIs; do not copy Zed source. Respect licenses. - -## Platforms and architecture - -- Windows and macOS are the primary targets. Isolate platform code behind small abstractions; the core model makes no Windows-only assumptions. -- Use `alacritty_terminal` as the terminal core unless a clearly superior compatible option is demonstrated. -- Each Claude session has exactly one PTY. Switching sessions never terminates, suspends or alters another session's PTY. -- Keep terminal emulation, process management, persistence, Claude discovery and GPUI rendering in separate modules. Persistence stays independent of GPUI. -- Never block the GPUI thread with filesystem scans or process I/O. Use background tasks and send compact state updates. -- Use platform application-data directories through a crate. Never hardcode paths, separators or home directories. Store Claudiu metadata apart from Claude Code data. -- Favor simple, debuggable code over premature abstraction. Do not over-engineer persistence before the session lifecycle is proven. - -## Sessions and projects - -- A session is a persistent record of a Claude Code process. A shell belongs to a Claude session as a panel, never as its own sidebar entry. -- Exited sessions stay in history. -- Startup reconciliation never deletes a record because an external record is unreadable. Mark it stale or unknown instead. -- Projects are Git-first. A plain folder is supported but is not the primary abstraction. -- Do not scan the filesystem for repositories without an explicit user choice. -- Resume through documented Claude Code CLI mechanisms. Do not reconstruct conversations. -- A click on a session must never restart a long-running process. - -## Terminal correctness (critical) - -Claude Code must behave as in a capable terminal, not a line-oriented shell. Test at least: Alt+P, Shift+Tab, Ctrl+C/D/Z, arrow keys, Home/End, modified keys, mouse, selection, paste, multiline input, resize, Unicode and emoji, ANSI colors, hyperlinks, alternate screen, scrollback, title changes, bell and image paste. - -## Process lifecycle - -- Handle spawn errors, PTY initialization, resize, stdin, output, exit, graceful and forced termination, shutdown and orphaned children. -- Closing the window must not silently kill Claude sessions. -- Sessions that were running come back at the next start. Sessions the user closed do not. - -## Usage and limits - -- Never invent a value. Show a neutral unavailable or stale state instead. -- Do not present limits as exact when Claude Code does not expose them. -- Do not build a separate Anthropic subscription API integration to obtain them. -- Account-wide meters must not change when the user switches sessions. - -## UI - -- Dark-first, minimal, dense without feeling cramped, keyboard-friendly, subtle in animation. Native, not a web wrapper. -- Use the Claude Desktop / Clawd icon as the application identity, never a generic terminal icon. -- Do not overuse cards, gradients, large rounded rectangles or decoration. -- Conveniences support the core product. Do not turn Claudiu into a generic IDE. -- Keep the Visual panel's `visual::ui::PROMPT`, `default_css` and `Css::set` in step. -- Every icon used must be listed in `icon_assets!`; a test enforces it. +Claudiu types into a session's terminal in one place. In editor mode, moving the keyboard to the terminal while lines are selected pastes `@path#L12-30: ` into Claude Code's input box, and leaving without typing erases it again (`terminal/view/typing.rs`, `app/selection_reference.rs`). It does this only while the cursor is in that input box. It stays a deliberate exception: messages, settings changes and every other request reach Claude Code through the mod, not the terminal. Any further typing into a PTY needs the maintainer's decision first. + +## Enforced rules + +| Rule | Enforced by | +|---|---| diff --git a/Cargo.lock b/Cargo.lock index 5dd3937..e29d071 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -977,7 +977,7 @@ dependencies = [ [[package]] name = "claudiu" -version = "0.5.5" +version = "0.6.0" dependencies = [ "alacritty_terminal", "anyhow", @@ -990,6 +990,7 @@ dependencies = [ "image", "junction", "libc", + "lsp-types", "objc2 0.6.4", "objc2-app-kit 0.3.2", "raw-window-handle", @@ -997,7 +998,9 @@ dependencies = [ "serde_json", "tempfile", "time", + "tree-sitter-gleam", "ureq", + "url", "uuid", "velopack", "which", @@ -2432,6 +2435,17 @@ dependencies = [ "smallvec", "smol", "tracing", + "tree-sitter", + "tree-sitter-bash", + "tree-sitter-css", + "tree-sitter-html", + "tree-sitter-javascript", + "tree-sitter-json", + "tree-sitter-md", + "tree-sitter-rust", + "tree-sitter-toml-ng", + "tree-sitter-typescript", + "tree-sitter-yaml", "uuid", "windows 0.58.0", ] @@ -6594,6 +6608,12 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d08889ec5408683408db66ad89e0e1f93dff55c73a4ccc71c427d5b277ee47e6" +[[package]] +name = "streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" + [[package]] name = "strict-num" version = "0.1.1" @@ -7307,6 +7327,136 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "tree-sitter" +version = "0.26.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17ebdd3a5a7e28a1890b876fdbd0c3c0fe0a6336cffaa104f11b9f720c9daa29" +dependencies = [ + "cc", + "regex", + "regex-syntax", + "serde_json", + "streaming-iterator", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-bash" +version = "0.23.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "329a4d48623ac337d42b1df84e81a1c9dbb2946907c102ca72db158c1964a52e" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-css" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ad6489794d41350d12a7fbe520e5199f688618f43aace5443980d1ddcf1b29e" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-gleam" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0175c53793bda5d444360dd5add25463d18d66afb7f521d6791e2fc61bf2fb3" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-html" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261b708e5d92061ede329babaaa427b819329a9d427a1d710abb0f67bbef63ee" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-javascript" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf40bf599e0416c16c125c3cec10ee5ddc7d1bb8b0c60fa5c4de249ad34dc1b1" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-json" +version = "0.24.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d727acca406c0020cffc6cf35516764f36c8e3dc4408e5ebe2cb35a947ec471" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-language" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a" + +[[package]] +name = "tree-sitter-md" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed661bfe3c264961425f77cd89ad2998bf5d629e71ce8bab1e5d7e940d6246e" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-rust" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-toml-ng" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9adc2c898ae49730e857d75be403da3f92bb81d8e37a2f918a08dd10de5ebb1" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-typescript" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-yaml" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c223db85f05e34794f065454843b0668ebc15d240ada63e2b5939f43ce7c97" +dependencies = [ + "cc", + "tree-sitter-language", +] + [[package]] name = "triomphe" version = "0.1.16" diff --git a/Cargo.toml b/Cargo.toml index 920704d..d04466a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "claudiu" -version = "0.5.5" +version = "0.6.0" edition = "2024" description = "A native workspace for Claude Code sessions: real PTYs, projects, and session history" repository = "https://github.com/m4rocks/claudiu" @@ -14,13 +14,33 @@ dunce = "1.0.5" futures = "0.3.34" git2 = { version = "0.21.0", default-features = false } gpui = { package = "gpui-pre", version = "=0.3.8" } -gpui-kit = { version = "0.7.1", default-features = false, features = ["component", "assets"] } +gpui-kit = { version = "0.7.1", default-features = false, features = [ + "component", + "assets", + # Editor mode's syntax highlighting; each grammar adds to the binary, so only these. + "tree-sitter-bash", + "tree-sitter-css", + "tree-sitter-html", + "tree-sitter-javascript", + "tree-sitter-markdown", + "tree-sitter-markdown-inline", + "tree-sitter-rust", + "tree-sitter-toml", + "tree-sitter-tsx", + "tree-sitter-typescript", + "tree-sitter-yaml", +] } raw-window-handle = "0.6" serde = { version = "1.0.229", features = ["derive"] } -serde_json = "1.0.151" +serde_json = { version = "1.0.151", features = ["preserve_order"] } +# The same versions gpui-kit's editor uses for its LSP hooks; editor mode's language servers (`lsp`) speak through them. +lsp-types = "0.97.0" +url = "2.5.8" image = { version = "0.25", default-features = false, features = ["png", "bmp", "jpeg", "gif", "webp"] } ureq = "3.4.2" time = { version = "0.3.55", features = ["parsing"] } +# Gleam is not among gpui-kit's grammars; registered in `app::editor_mode::register_languages`. +tree-sitter-gleam = "1.0.0" uuid = { version = "1.27.0", features = ["v4"] } velopack = "1.2.161" which = "8.0.6" @@ -40,7 +60,7 @@ strip = true [target."cfg(windows)".dependencies] junction = "2.1.0" -windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging", "Win32_Foundation", "Win32_Security", "Win32_System_DataExchange", "Win32_System_Memory"] } +windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging", "Win32_Foundation", "Win32_Security", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/README.md b/README.md index fc1e6c3..8e90f0e 100644 --- a/README.md +++ b/README.md @@ -8,19 +8,24 @@ It's a personal project with rough edges; issues and PRs are welcome. ## How it works -- **Your own `claude`, in a real terminal.** Each session is one `claude` process in its own pseudo-terminal (ConPTY on Windows, a Unix PTY on macOS), drawn with `alacritty_terminal`. Claude Code sees a normal terminal, so Alt+P, Shift+Tab, mouse, paste and the rest go straight to it. Claudiu never types for you. +- **Your own `claude`, in a real terminal.** Each session is one `claude` process in its own pseudo-terminal (ConPTY on Windows, a Unix PTY on macOS), drawn with `alacritty_terminal`. Claude Code sees a normal terminal, so Alt+P, Shift+Tab, mouse, paste and the rest go straight to it. Claudiu types into the terminal in one case: in editor mode, the `@file#L` reference of the selected lines, which it takes out again if you leave without typing. - **No API, no login.** Claudiu never calls the Anthropic API and has no API keys or sign-in of its own. Authentication stays with Claude Code. - **Sessions are records.** A session is Claudiu's record of a Claude process. Ended sessions stay in the sidebar and resume through `claude --resume`. Switching sessions never touches another session's process. Sessions that were running come back at the next start. - **Projects are Git-first.** Add a folder with the button, by dropping it on the window, or with `claudiu `. Claudiu never scans your disk for repositories. - **Documented hooks only.** Each session is started with `--session-id` or `--resume`, plus a per-process `--plugin-dir` mod and a `--mcp-config` file (tab titles). They live only as long as the session. -- **Usage meters.** The mod writes a small snapshot after each response: 5-hour and 7-day limits, context, auto-compact and advisor settings. No extra tokens are spent, and your own status line is untouched. Limits show only for sessions started from Claudiu, and stale values are labelled with their age. For sessions resumed elsewhere, context is estimated from the transcript and shown with `~`. -- **Alt accounts.** An extra account is a separate Claude Code config folder (`CLAUDE_CONFIG_DIR`) holding only its own login; the rest links back to your main `~/.claude`. Only sign in to accounts you own. -- **GitHub, Git and editors.** Issues, PRs, Commit & Push and Pull go through the `gh` and `git` you already have. Open a project in VS Code or Zed. +- **Usage meters.** The mod writes a small snapshot after each response: 5-hour and 7-day limits, context, auto-compact and advisor settings. Where Claude Code offers background compaction ("Precompute compaction" in `/config`, still behind a feature flag on many accounts), the inspector shows a switch for it too. No extra tokens are spent, and your own status line is untouched. Limits show only for sessions started from Claudiu, and stale values are labelled with their age. For sessions resumed elsewhere, context is estimated from the transcript and shown with `~`. +- **Claude in Chrome.** Switch it per session in the inspector, which restarts the session with `--chrome`. Settings → Sessions → Claude in Chrome for new sessions sets the default. +- **New-session defaults.** Settings → Sessions sets the model, effort and permission mode that new Claude sessions start with (empty means Claude Code's own default). They are passed as `--model`, `--effort` and `--permission-mode` to every new session, including ones another session or the GitHub pane starts; a flag the caller already passes wins, resumed sessions get none, and Fix Git with Claude never starts in plan mode. `bypassPermissions` is on the list and skips every prompt in every new session, so choose it with care. +- **Claudiu's own tools.** Claudiu gives each Claude session a small MCP server (tab titles, the Visual panel, the GitHub sidebar, tools that reach your other sessions, model switching). Settings → Claudiu tools switches the Visual panel, GitHub sidebar, Other sessions and Model switch off one by one: a feature that is off loses its tools and the instruction text about them, in new and resumed sessions (a resumed one may keep the old instructions until its next compaction). Tab titles always stay. +- **Trimmed Claude Code tools.** Claude Code sends every tool definition with every request. Settings → Claude Code tools switches off whole features (bundled skills, workflows, remote control, claude.ai connectors, artifacts) and single tools (plan mode, AskUserQuestion, scheduled tasks, SendMessage and more) by writing them into Claude Code's own `settings.json`, so every account and Claude Code outside Claudiu get them, and switching one back on removes only what Claudiu added. Nothing is trimmed by default. The list follows [How to kill the bloat in Claude Code's system prompt](https://www.aihero.dev/how-to-kill-the-bloat-in-claude-codes-system-prompt). +- **Alt accounts.** An extra account is a separate Claude Code config folder (`CLAUDE_CONFIG_DIR`) holding only its own login. Folders (agents, skills, plugins, session history) link back to your main `~/.claude`. Settings, `CLAUDE.md`, keybindings, user-level MCP servers and project trust are kept the same in every account, both ways: a change in any account, or in `~/.claude`, is copied to the others within a few seconds, and the newest change wins. A file you delete is not deleted elsewhere. An account's `.claude.json` is only written while no session of that account is running. New sessions start under the active account; a session keeps its account after you close it or restart Claudiu, until you hand it off to the active one from the right sidebar. Only sign in to accounts you own. +- **GitHub, Git and editors.** Issues, PRs, Commit & Push (greyed out when there is nothing to commit or push) and Pull go through the `gh` and `git` you already have; the GitHub pane also calls the GitHub API directly with the token `gh` holds. Open a project in VS Code or Zed. +- **Editor mode.** Ctrl+Shift+E puts the session's files and a light editor beside its terminal: tabs, quick open, find in files, Git change marks (a bar over the line numbers: green for added lines, blue for changed ones, a red tick where lines were removed, as of the last save), and highlighting for common languages. Diagnostics, hover and go-to-definition come from language servers already on your PATH: `rust-analyzer` (Rust), TypeScript 7's `tsc --lsp` (TypeScript and JavaScript) and `gleam` (Gleam). A missing one is named under the editor; Claudiu installs nothing. TypeScript's comes with `npm install --global typescript`, and with rustup, run `rustup component add rust-analyzer`. Select lines in the editor and click into Claude's terminal to put `@file#L12-30: ` into Claude's input, then type your comment after it (start a new line yourself before the next one); leave without typing and it's taken back out. Files with tab-indented lines show every tab as spaces and save untouched lines as they were (a line you edit keeps the tabs of its indent, not any inside it, and only in a file indented mostly with tabs). Right-click in the file tree to create a file or folder, rename one, copy its relative path, reveal it in File Explorer or Finder, or delete it (after a confirmation; it doesn't go to the trash). Right-click in the editor to ask Claude to explain, fix or write tests for the selection (or the clicked line), or to fix the problem a language server reports there: the request is sent to Claude as your next message once it is idle, without touching what you have typed in its prompt. Hold Ctrl over a file path in Claude's terminal, such as `src/main.rs:42`, and it is underlined; Ctrl+click opens it at that line (also while Claude Code is capturing the mouse). Quick open lists the files you showed last first. ## What Claudiu touches -- Claude Code's data is read-only. Claudiu never writes to `~/.claude`, never edits Claude Code's settings, and never deletes a transcript. Hiding a session removes it from Claudiu's index only. -- Nothing is uploaded. Terminal contents are never logged. The only network request is the update check against GitHub Releases (turn it off with `"settings": { "update_url": "" }` in `state.json`). +- Claudiu never deletes a transcript, and hiding a session removes it from Claudiu's index only. It writes to Claude Code's own data in two cases: the sidebar's auto-compact, background-compaction and advisor switches and the Claude Code tools page change Claude Code's settings, the same as /config does, and the sync between accounts copies the shared settings, MCP servers and project trust between the config folders (`~/.claude`, `~/.claude.json` and each alt account's folder). +- Nothing is uploaded. Terminal contents are never logged. Claudiu contacts only GitHub: the update check against GitHub Releases, and the GitHub pane and attached issue titles through your `gh` login. Turn the update check off with `"settings": { "update_url": "" }` in `state.json`. - Claudiu's own state is in `%LOCALAPPDATA%\m4rocks\Claudiu\data` on Windows and `~/Library/Application Support/Claudiu` on macOS. Crashes go to `crash.log` there. - Children start with a clean environment: markers from other terminals and from nested Claude Code sessions are removed, IDE auto-connect is off, and `TERM_PROGRAM=Claudiu`. @@ -34,17 +39,28 @@ Claudiu's own shortcuts use Ctrl+Shift (Cmd+Shift on macOS), plus a few Ctrl cho | Ctrl+` / Ctrl+J | Show or hide the session's shell | | Ctrl+Shift+W | End the focused session | | Ctrl+Tab / Ctrl+Shift+Tab | Next / previous running session | +| Ctrl+1 … Ctrl+9 | Show that running session; hold Ctrl a moment to see the numbers in the sidebar, and the other shortcuts beside their buttons | | Ctrl+Shift+] | Move the keyboard between Claude and its shell | +| Ctrl+Shift+E | Editor mode: the session's files and an editor beside its terminal | +| Ctrl+P | Editor mode, over the files or editor: go to a file by name | +| Ctrl+S | Editor mode: save the shown file | +| F12 / Ctrl+click | Editor mode: go to definition (needs the language's server, see Editor mode above) | +| Ctrl+G | Editor mode: go to line (`42` or `42:7`) | +| Alt+← / Alt+→ | Editor mode: back to where you jumped from, and forward again | +| Ctrl+F / Ctrl+H | Editor mode: find, or find and replace, in the shown file | +| Ctrl+click a path | In Claude's terminal: open that file in editor mode, at its line | | Ctrl+Shift+B / Ctrl+Shift+R | Toggle left / right sidebar | -| Ctrl+Shift+F | Search sessions and projects | +| Ctrl+Shift+F | Search sessions and projects; in editor mode, find in the session's files | | Ctrl+Shift+O | Add a project folder | | Ctrl+Shift+G | Open GitHub | | Ctrl+, | Open settings | -On macOS, `Ctrl+Shift` above is `Cmd+Shift`, and `Ctrl+J` is `Cmd+J`. `Ctrl+`` stays Ctrl. +On macOS, `Ctrl+Shift` above is `Cmd+Shift`, `Ctrl+J` is `Cmd+J`, `Ctrl+1` … `Ctrl+9` are `Cmd+1` … `Cmd+9`, and `Ctrl+F` is `Cmd+F`. Back and forward are `Ctrl+-` and `Ctrl+Shift+-`. `Ctrl+`` and `Ctrl+G` stay Ctrl. Copy with Ctrl+Shift+C (or Ctrl+C while text is selected); paste with Ctrl+V or Ctrl+Shift+V. On macOS use Cmd. +A middle click closes an editor tab, or ends a running session in the sidebar. + ## Known gaps - macOS is lightly tested, and the build isn't notarized, so Gatekeeper complains on first launch. diff --git a/mod/.claude-plugin/plugin.json b/mod/.claude-plugin/plugin.json index 2762008..1133712 100644 --- a/mod/.claude-plugin/plugin.json +++ b/mod/.claude-plugin/plugin.json @@ -1,5 +1,5 @@ { - "name": "claudiu-mod", + "name": "Claudiu", "version": "0.1.0", "description": "Claudiu helper: applies set_model mid-turn, applies tab names, reports usage and status" } diff --git a/mod/hooks/ctl.test.ts b/mod/hooks/ctl.test.ts index 46fe240..2f96c82 100644 --- a/mod/hooks/ctl.test.ts +++ b/mod/hooks/ctl.test.ts @@ -14,7 +14,8 @@ test('applies the settings Claudiu asks for, once each, and not the ones sent be }) on('session.id', () => ({ value: 's1' })) on('session.model', () => ({ value: 'claude-haiku-5-5' })) - on('config.list', () => ({ value: [] })) + const precomputeRow = { key: 'precomputeCompactionEnabled', label: 'Precompute compaction', kind: 'boolean', value: true, provider: { plugin: 'engine', tier: 'core' }, isLocked: false } + on('config.list', () => ({ value: [precomputeRow] }) as any) on('settings.read', () => ({ value: {} })) on('session.start', (_$, e) => ({ cwd: e.cwd })) on('config.set', (_$, e) => { @@ -37,16 +38,54 @@ test('applies the settings Claudiu asks for, once each, and not the ones sent be { seq: 7, key: 'advisor', value: 'opus' }, { seq: 8, key: 'advisor', value: 'rm -rf /' }, // not a model name { seq: 9, key: 'theme', value: 'light' }, // not a setting Claudiu sets + { seq: 10, key: 'precompute_compact', value: false }, ], }) await clock.advance(1000) - expect(sets).toEqual([['autoCompact', false]]) + expect(sets).toEqual([['autoCompact', false], ['precomputeCompactionEnabled', false]]) expect(ran).toEqual(['advisor opus']) const snap = JSON.parse(writes.at(-1)!.text) expect(snap.advisor).toBe('opus') expect(snap.advisor_active).toBe('opus') expect(snap.auto_compact).toBe(false) + expect(snap.precompute_compact).toBe(false) await clock.advance(3000) - expect(sets.length + ran.length).toBe(2) // handled once + expect(sets.length + ran.length).toBe(3) // handled once +}) + +test('sends a message Claudiu asks for as the person’s own words, once', async ($, on) => { + mock.env(on, { CLAUDIU_CTL_FILE: 'ctl/me.json', CLAUDIU_USAGE_DIR: 'usage' }) + const clock = mock.clock(on) + let file = JSON.stringify({ cmds: [{ seq: 1, key: 'prompt', value: 'from an earlier run' }] }) + const sent: unknown[] = [] + on('fs.read', () => ({ value: file })) + on('fs.write', () => ({ value: undefined })) + on('session.id', () => ({ value: 's1' })) + on('session.model', () => ({ value: 'claude-haiku-5-5' })) + on('config.list', () => ({ value: [] }) as any) + on('settings.read', () => ({ value: {} })) + on('session.start', (_$, e) => ({ cwd: e.cwd })) + on('prompt.submit', (_$, e) => { + sent.push([e.text, e.origin]) + return { drop: 'test' } + }) + + await $.session.start({ cwd: '/repo', surface: 'terminal', isInteractive: true }) + await clock.advance(1000) + expect(sent).toEqual([]) + + file = JSON.stringify({ + cmds: [ + { seq: 1, key: 'prompt', value: 'from an earlier run' }, + { seq: 2, key: 'prompt', value: '@src/a.rs#L3-9: Explain this code.' }, + { seq: 3, key: 'prompt', value: ' ' }, // nothing to say + { seq: 4, key: 'prompt', value: 42 }, // not text + ], + }) + await clock.advance(1000) + expect(sent).toEqual([['@src/a.rs#L3-9: Explain this code.', { kind: 'plugin', name: expect.anything(), asUser: true }]]) + + await clock.advance(3000) + expect(sent.length).toBe(1) // handled once }) diff --git a/mod/hooks/handoff.test.ts b/mod/hooks/handoff.test.ts new file mode 100644 index 0000000..87cd13b --- /dev/null +++ b/mod/hooks/handoff.test.ts @@ -0,0 +1,51 @@ +import { expect, mock, test } from 'claude-code/testing' + +type Engine = { idle: boolean } + +// A session whose ctl file gets Claudiu's hand-off request. `idle` false is a turn running. +async function handOff($: any, on: any, engine: Engine) { + mock.env(on, { CLAUDIU_CTL_FILE: 'ctl/me.json', CLAUDIU_USAGE_DIR: 'usage' }) + const clock = mock.clock(on) + let file = '{}' + const ran: string[] = [] + const compactions: string[] = [] + const writes: any[] = [] + on('fs.read', () => ({ value: file })) + on('fs.write', (_$: any, e: any) => { + writes.push(JSON.parse(e.text)) + return { value: undefined } + }) + on('session.id', () => ({ value: 's1' })) + on('session.model', () => ({ value: 'claude-opus-5-5' })) + on('config.list', () => ({ value: [] })) + on('settings.read', () => ({ value: {} })) + on('session.start', (_$: any, e: any) => ({ cwd: e.cwd })) + // What Claude Code does after the person stopped a turn: a plugin's slash command is refused until they type. + on('command.run', (_$: any, e: any) => { + if (engine.idle) throw new Error('refused: the session was stopped and nobody has sent input since') + ran.push(e.command) + return {} + }) + on('session.compact', (_$: any, e: any) => { + if (!engine.idle) throw new Error('a turn is running') + compactions.push(e.trigger) + return { messages: [{ role: 'user', text: 'summary', toolUses: [] }] } + }) + + await $.session.start({ cwd: '/repo', surface: 'terminal', isInteractive: true }) + await clock.advance(1000) + file = JSON.stringify({ cmds: [{ seq: 1, key: 'compact', value: true }] }) + await clock.advance(1000) + return { ran, compactions, compactedAt: writes.at(-1)?.compacted_at ?? null } +} + +test('a hand-off compacts an idle session, even after the person stopped its last turn, and says so', async ($, on) => { + const r = await handOff($, on, { idle: true }) + expect(r.compactions.length).toBe(1) + expect(r.compactedAt).not.toBe(null) +}) + +test('a hand-off during a turn queues /compact for when the turn ends', async ($, on) => { + const r = await handOff($, on, { idle: false }) + expect(r.ran).toEqual(['compact']) +}) diff --git a/mod/hooks/register.js b/mod/hooks/register.js index e9ee220..d1179fe 100644 --- a/mod/hooks/register.js +++ b/mod/hooks/register.js @@ -6,10 +6,13 @@ // switches too. Claude Code saves those as the user's default. // - Session name: applies the name Claudiu writes to `CLAUDIU_NAME_FILE` with /rename, which Claude Code queues // until the session is idle. -// - Sidebar settings: applies auto-compact and advisor changes sent through `CLAUDIU_CTL_FILE`, the same as the user -// choosing them in /config or typing /advisor (which Claude Code saves). -// - Usage and status: reports context, the 5-hour and 7-day limits, auto-compact, advisor and the last command to -// `CLAUDIU_USAGE_DIR/.json`. No tokens are spent. +// - Sidebar settings: applies auto-compact, background compaction and advisor changes sent through +// `CLAUDIU_CTL_FILE`, the same as the user choosing them in /config or typing /advisor (which Claude Code saves). +// - Messages: sends a message Claudiu asks for through the same file (the editor's Ask Claude) as the user's own words, +// when the session is idle, without typing into the terminal. (Claudiu itself pastes the editor's `@file#L` +// reference into Claude's input box; that is not done here.) +// - Usage and status: reports context, the 5-hour and 7-day limits, auto-compact, background compaction, advisor and +// the last command to `CLAUDIU_USAGE_DIR/.json`. No tokens are spent. // - Visual panel: answers `show_visual` in-process and, while the model is still writing the call, streams its // Markdown to `CLAUDIU_VISUAL_FILE` so the panel fills live. // - One-shot completions: runs requests from `CLAUDIU_ASK_FILE` (commit messages, session titles) with @@ -24,9 +27,13 @@ const MODELS = { opus: 'claude-opus-5-5', fable: 'claude-fable-5-1', } +const PROMPT_MAX = 20000 // characters of a message Claudiu asks the session to send (the editor's Ask Claude) const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] const ASK_MODELS = ['haiku', 'sonnet', 'opus'] const VISUAL_TOOL = 'mcp__claudiu__show_visual' +// The /config row for background compaction ("Precompute compaction"). Claude Code lists it only while a server-side +// flag enables the feature; without the row the setting does nothing, so Claudiu offers the switch only with it. +const PRECOMPUTE_ROW = 'precomputeCompactionEnabled' // ---- Per-process state -------------------------------------------------------------------------------------------- @@ -35,6 +42,7 @@ let named = null // `${claude session id}\n${name}` last applied with /rename let namePoll // watches CLAUDIU_NAME_FILE let ctlPoll // watches CLAUDIU_CTL_FILE let ctlSeen = null // highest command number handled; null until the file was first read (older ones are not replayed) +let pendingAdvisor = null // an advisor change Claude Code refused (see setAdvisor), tried again until it goes through let askPoll // watches CLAUDIU_ASK_FILE let askSeen = null // id of the last request looked at let asking = false // a completion is running; a poll that finds another request waits for it @@ -49,12 +57,14 @@ let activeAdvisor = null // the advisor the current conversation declared; a mod let activeSession = null // the Claude session id activeAdvisor belongs to (/clear starts a new one) // The token count auto-compaction runs at (null while it is off). It only changes with settings, the model or the -// environment, and the breakdown it comes from is a local estimate, so it is read again at most once a minute or -// after a setting changed. +// environment, and the breakdown it comes from is a local estimate, so it is read again at most once a minute, after +// a setting changed, or when the model changed: each model has its own compaction window. let compactAt = null let compactRead = 0 +let compactModel = null // the model compactAt belongs to let compactedAt = null // when this session last compacted (seconds), so Claudiu can finish a hand-off + // A session id as a file name. const stem = id => String(id).replace(/[^A-Za-z0-9_-]/g, '_') @@ -65,8 +75,10 @@ function secs(iso) { } async function threshold($, fresh) { - if (!fresh && Date.now() - compactRead < 60_000) return compactAt + const model = await $.session.model().catch(() => null) + if (!fresh && model === compactModel && Date.now() - compactRead < 60_000) return compactAt compactRead = Date.now() + compactModel = model const usage = await $.session.usage({ breakdown: 'summary' }).catch(() => null) const b = usage?.context.breakdown if (b) compactAt = b.isAutoCompactEnabled ? (b.autoCompactThreshold ?? null) : null @@ -113,8 +125,11 @@ async function report($, fresh = false, override = {}) { const fromSettings = await setting($, 'autoCompactEnabled') autoCompact = typeof fromSettings === 'boolean' ? fromSettings : null } + const precompute = rows.find(r => r.key === PRECOMPUTE_ROW)?.value + let precomputeCompact = typeof precompute === 'boolean' ? precompute : null let advisor = advisorAlias(await setting($, 'advisorModel')) if ('auto_compact' in override) autoCompact = override.auto_compact + if ('precompute_compact' in override) precomputeCompact = override.precompute_compact if ('advisor' in override) advisor = override.advisor // A different model only reaches the running conversation on /clear or /compact. Off and on take effect at once, @@ -134,6 +149,7 @@ async function report($, fresh = false, override = {}) { model: (await $.session.model().catch(() => null)) ?? null, account: (await $.env.get('CLAUDIU_ACCOUNT')) ?? null, auto_compact: autoCompact, + precompute_compact: precomputeCompact, compact_at: await threshold($, fresh), advisor, advisor_active: activeAdvisor, @@ -166,6 +182,7 @@ async function applyCtl($) { return } const override = {} + if (pendingAdvisor !== null) await setAdvisor($, pendingAdvisor, override) const pending = cmds.filter(c => c.seq > ctlSeen).sort((a, b) => a.seq - b.seq) for (const c of pending) { ctlSeen = c.seq @@ -181,12 +198,45 @@ async function applyCtlCommand($, c, override) { if (c.key === 'auto_compact' && typeof c.value === 'boolean') { await $.config.set({ key: 'autoCompact', value: c.value }).catch(() => {}) override.auto_compact = c.value + } else if (c.key === 'precompute_compact' && typeof c.value === 'boolean') { + // Fails while Claude Code does not list the row; the report then keeps saying it is not offered. + const set = await $.config.set({ key: PRECOMPUTE_ROW, value: c.value }).then(() => true, () => false) + if (set) override.precompute_compact = c.value + } else if (c.key === 'prompt' && typeof c.value === 'string' && c.value.trim() !== '' && c.value.length <= PROMPT_MAX) { + // A turn of its own once the session is idle, which can be a whole turn away: not awaited, so the commands + // behind it in the file are not held up. + void $.prompt.submit({ text: c.value, asUser: true }).catch(() => {}) } else if (c.key === 'compact' && c.value === true) { - // Queued by Claude Code until idle, like the user typing /compact; the session.compact hook reports it. - await $.command.run({ command: 'compact' }).catch(() => {}) + await compactForHandoff($) } else if (c.key === 'advisor' && typeof c.value === 'string' && /^[A-Za-z0-9._-]{1,60}$/.test(c.value)) { - await $.command.run({ command: 'advisor', args: c.value }).catch(() => {}) - override.advisor = advisorAlias(c.value) + await setAdvisor($, c.value, override) + } +} + +// Claude Code refuses a plugin's slash command after the person stopped a turn, until they type again +// ("refused: the session was stopped and nobody has sent input since"). That change is kept and tried again on the +// next look, and the new advisor is only reported once it went through. Any other failure drops the change. +async function setAdvisor($, value, override) { + pendingAdvisor = null + try { + await $.command.run({ command: 'advisor', args: value }) + } catch (e) { + if (String(e?.message ?? e).includes('refused')) pendingAdvisor = value + return + } + override.advisor = advisorAlias(value) +} + +// Claudiu's hand-off waits for this compaction. Between turns it compacts at once: `/compact` from a plugin would be +// refused there after the person stopped the last turn, until they type again. During a turn the direct call is +// refused, and `/compact` waits for the turn to end; the session.compact hook reports that one. +async function compactForHandoff($) { + const result = await $.session.compact().catch(() => null) + if (result === null) { + await $.command.run({ command: 'compact' }).catch(() => {}) + } else if (!('skip' in result)) { + // This plugin's own hooks don't see its own call. + await noteCompaction($) } } @@ -332,14 +382,20 @@ async function onConfigSet($, e, next) { return r } -// Compaction rebuilds the request, so the saved advisor becomes the one this conversation declares. +// Compaction rebuilds the request, so the saved advisor becomes the one this conversation declares. A precompute +// installs nothing, so it is not a compaction here. async function onSessionCompact($, e, next) { + if (e.trigger === 'precompute') return next(e) const r = await next(e) + await noteCompaction($) + return r +} + +async function noteCompaction($) { activeAdvisor = advisorAlias(await setting($, 'advisorModel')) activeSession = await $.session.id().catch(() => null) compactedAt = Math.floor(Date.now() / 1000) await report($, true) - return r } async function onSetModel($, e) { diff --git a/mod/hooks/usage.test.ts b/mod/hooks/usage.test.ts index 9f488c8..639dbf5 100644 --- a/mod/hooks/usage.test.ts +++ b/mod/hooks/usage.test.ts @@ -10,7 +10,7 @@ test('reports context, limits, auto-compact and advisor; rewrites only on change }) on('session.id', () => ({ value: 'abc/123' })) on('session.model', () => ({ value: 'claude-haiku-5-5' })) - on('config.list', () => ({ value: [{ key: 'autoCompact', label: 'Auto-compact', kind: 'boolean', value: true, provider: { plugin: 'claudiu-mod', tier: 'user' }, isLocked: false }] })) + on('config.list', () => ({ value: [{ key: 'autoCompact', label: 'Auto-compact', kind: 'boolean', value: true, provider: { plugin: 'Claudiu', tier: 'user' }, isLocked: false }] })) on('settings.read', () => ({ value: { advisorModel: advisor } })) let compactAt: number | undefined = 167_000 on('session.usage', () => ({ @@ -24,6 +24,7 @@ test('reports context, limits, auto-compact and advisor; rewrites only on change expect(writes.length).toBe(1) expect(writes[0]!.path).toMatch(/usage[\\/]abc_123\.json$/) // the session id cannot escape the directory expect(writes[0]!.snap).toMatchObject({ session_id: 'abc/123', model: 'claude-haiku-5-5', account: 'work', auto_compact: true, advisor: 'opus', advisor_active: 'opus', compact_at: 167_000, context_fraction: null }) + expect(writes[0]!.snap.precompute_compact).toBe(null) // Claude Code does not offer the switch here const measure = { context: { tokens: 28000, window: 1_000_000, percent: 3 }, @@ -60,3 +61,31 @@ test('reports context, limits, auto-compact and advisor; rewrites only on change expect(writes.at(-1)!.snap).toMatchObject({ advisor: 'sonnet', advisor_active: 'opus' }) expect(JSON.stringify(writes.at(-1)!.snap)).not.toContain('command') // what the user types is not reported }) + +test('reports the auto-compact threshold of the model the session switched to', async ($, on) => { + // Each model has its own compaction window, so a cached threshold must not outlive a model change. + mock.env(on, { CLAUDIU_USAGE_DIR: 'usage' }) + let model = 'claude-sonnet-5-5' + const windows: Record = { 'claude-sonnet-5-5': 367_000, 'claude-haiku-5-5': 67_000 } + const writes: any[] = [] + on('fs.write', (_$, e) => { + writes.push(JSON.parse(e.text)) + return { value: undefined } + }) + on('session.id', () => ({ value: 's1' })) + on('session.model', () => ({ value: model })) + on('config.list', () => ({ value: [] })) + on('settings.read', () => ({ value: {} })) + on('session.usage', () => ({ + value: { startedAt: 0, rateLimits: [], cost: { usd: 0 }, context: { window: 1_000_000, breakdown: { isAutoCompactEnabled: true, autoCompactThreshold: windows[model] } } }, + }) as any) + on('session.start', (_$, e) => ({ cwd: e.cwd })) + on('session.measure', (_$, e) => ({ changed: e.changed })) + + await $.session.start({ cwd: '/repo', surface: 'terminal', isInteractive: true }) + expect(writes.at(-1).compact_at).toBe(367_000) + + model = 'claude-haiku-5-5' + await $.session.measure({ context: { tokens: 1000, window: 1_000_000, percent: 0 }, rateLimits: [], changed: ['context'] } as any) + expect(writes.at(-1).compact_at).toBe(67_000) +}) diff --git a/src/app/ask_claude.rs b/src/app/ask_claude.rs new file mode 100644 index 0000000..4a83625 --- /dev/null +++ b/src/app/ask_claude.rs @@ -0,0 +1,132 @@ +//! The editor's right-click requests to Claude: explain, fix or test the selected lines, or fix the problem a language +//! server reports on the clicked line. Each one sends the reference and the request to Claude as the next message (`send_to_claude`). + +use std::path::Path; + +use super::*; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Ask { + Explain, + Fix, + Tests, + /// The language server's problem on the cursor's line. + Problem, +} + +impl Workspace { + pub fn ask_claude(&mut self, ask: Ask, window: &mut Window, cx: &mut Context) { + let Some(id) = self.active_id().cloned() else { return }; + let text = match ask { + Ask::Problem => self.problem_at_cursor(&id, cx).map(|(reference, message)| request(ask, &reference, Some(&message))), + _ => self.selection_reference(&id, cx).or_else(|| self.cursor_reference(&id, cx)).map(|reference| request(ask, &reference, None)), + }; + let Some(text) = text else { + if ask == Ask::Problem { + self.toast("The language server reports no problem on this line.", false, cx); + } + return; + }; + self.send_to_claude(&id, &text, window, cx); + } + + /// The shown session when it is a running Claude session: where a request from anywhere in the app goes, rather than + /// into a session of its own. + pub(super) fn running_claude(&self, cx: &App) -> Option { + self.active_id().filter(|id| self.is_running(id, cx) && self.store.session(id).is_some_and(|r| r.kind == SessionKind::Claude)).cloned() + } + + /// `running_claude`, when it works in `folder` (or inside it, or around it). A request about another repository, + /// or another worktree of this one, must not land in a session that would act on the wrong files. + pub(super) fn running_claude_in(&self, folder: &Path, cx: &App) -> Option { + self.running_claude(cx).filter(|id| self.store.session(id).is_some_and(|r| works_in(&r.cwd, folder))) + } + + /// Ask the Claude session `id` to take `text` as the user's next message, then move the keyboard to its terminal. + /// It goes through the session's mod, which sends it once the session is idle, so nothing is typed into the + /// terminal and a half-written prompt there is left alone. + pub(super) fn send_to_claude(&mut self, id: &Id, text: &str, window: &mut Window, cx: &mut Context) { + let Some(view) = self.live_view(id).filter(|v| v.read(cx).is_running()) else { + self.toast("This session isn't running. Resume it, then try again.", false, cx); + return; + }; + usage::send_ctl(&usage::ctl_file(id), "prompt", text.into()); + // Only a change of focus raises `on_terminal_focus`; otherwise the flag would outlive this request. + self.skip_selection_reference = !view.read(cx).focus_handle(cx).is_focused(window); + self.focus_active(window, cx); + } + + /// `@path#L` for the cursor's line of the shown tab. + fn cursor_reference(&self, id: &Id, cx: &App) -> Option { + let pane = self.panes.get(id)?; + let tab = pane.shown().filter(|t| t.note.is_none())?; + let line = tab.buffer.read(cx).cursor_position().line as usize; + Some(format!("@{}#L{}", super::picker::relative(&tab.path, &pane.root), line + 1)) + } + + /// The reference and message of the most severe problem on the cursor's line of the shown tab. + fn problem_at_cursor(&self, id: &Id, cx: &App) -> Option<(String, String)> { + use gpui_kit::base::input::DiagnosticSeverity as S; + let pane = self.panes.get(id)?; + let tab = pane.shown().filter(|t| t.note.is_none())?; + let b = tab.buffer.read(cx); + let line = b.cursor_position().line; + let rank = |s: &S| match s { + S::Error => 0, + S::Warning => 1, + S::Info => 2, + S::Hint => 3, + }; + let problem = b.diagnostics()?.iter().filter(|d| (d.diagnostic.range.start.line..=d.diagnostic.range.end.line).contains(&line)).min_by_key(|d| rank(&d.severity))?; + let (first, last) = (problem.diagnostic.range.start.line as usize, problem.diagnostic.range.end.line as usize); + let path = super::picker::relative(&tab.path, &pane.root); + let reference = if first == last { format!("@{path}#L{}", first + 1) } else { format!("@{path}#L{}-{}", first + 1, last + 1) }; + Some((reference, problem.message.to_string())) + } +} + +/// What goes into Claude's input for `ask` about the lines `reference` names; `problem` is the server's message. +fn request(ask: Ask, reference: &str, problem: Option<&str>) -> String { + match ask { + Ask::Explain => format!("{reference}: Explain this code."), + Ask::Fix => format!("{reference}: Fix this code."), + Ask::Tests => format!("{reference}: Write tests for this code."), + Ask::Problem => format!("{reference}: Fix this problem: {}", problem.unwrap_or_default().replace('\n', " ")), + } +} + +#[cfg(test)] +mod tests { + use super::{Ask, request}; + + #[test] + fn requests_name_the_lines_and_the_problem_on_one_line() { + assert_eq!(request(Ask::Explain, "@a.rs#L3-9", None), "@a.rs#L3-9: Explain this code."); + assert_eq!(request(Ask::Tests, "@a.rs#L3", None), "@a.rs#L3: Write tests for this code."); + assert_eq!( + request(Ask::Problem, "@a.rs#L3", Some("mismatched types\nexpected `u8`")), + "@a.rs#L3: Fix this problem: mismatched types expected `u8`", + "the request stays on one line" + ); + } +} + +/// Whether a session started in `session` is working on `folder`. +fn works_in(session: &Path, folder: &Path) -> bool { + crate::platform::is_same_or_under(session, folder) || crate::platform::is_same_or_under(folder, session) +} + +#[cfg(test)] +mod folder_tests { + use super::works_in; + use std::path::Path; + + #[test] + fn a_session_works_in_its_folder_and_those_around_and_inside_it_only() { + assert!(works_in(Path::new("/p/app"), Path::new("/p/app"))); + assert!(works_in(Path::new("/p/app/crates/x"), Path::new("/p/app")), "started in a sub-folder of the repository"); + assert!(works_in(Path::new("/p"), Path::new("/p/app")), "started above the repository"); + assert!(!works_in(Path::new("/p/other"), Path::new("/p/app"))); + assert!(!works_in(Path::new("/p/app-wt"), Path::new("/p/app")), "another worktree is not this one"); + } +} diff --git a/src/app/attached_sync.rs b/src/app/attached_sync.rs new file mode 100644 index 0000000..231fb2a --- /dev/null +++ b/src/app/attached_sync.rs @@ -0,0 +1,115 @@ +//! Titles and states of the issues and pull requests attached to sessions come from GitHub, not from the model: new +//! items are asked about at once, and every item again now and then, so a rename or a close shows up. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use super::*; +use crate::github::cli::{Gh, RepoRef}; +use crate::github::model::State; + +/// Between asking about everything again. +const REFRESH_EVERY: Duration = Duration::from_secs(120); +/// Between tries while some item has no answer yet; doubles with each try that left one unanswered (no `gh`, no +/// network, not a GitHub folder), up to `REFRESH_EVERY`. +const RETRY_EVERY: Duration = Duration::from_secs(15); + +#[derive(Default)] +pub struct Sync { + last_try: Option, + running: bool, + /// Tries in a row that left an item unanswered. + failures: u32, +} + +fn retry_wait(failures: u32) -> Duration { + RETRY_EVERY.saturating_mul(2u32.saturating_pow(failures)).min(REFRESH_EVERY) +} + +/// One answer: the session, which item, and what GitHub said. +type Answer = (Id, bool, u32, String, State); + +impl Sync { + fn due(&self, some_unanswered: bool) -> bool { + let wait = if some_unanswered { retry_wait(self.failures) } else { REFRESH_EVERY }; + !self.running && self.last_try.is_none_or(|t| t.elapsed() >= wait) + } +} + +impl Workspace { + pub(super) fn sync_attached(&mut self, cx: &mut Context) { + let asks: Vec<(Id, PathBuf, Vec<(bool, u32)>)> = self + .store + .data + .sessions + .iter() + // A session whose folder is gone cannot be asked about (and would never be answered). + .filter(|s| s.cwd.is_dir()) + .filter_map(|s| { + let items: Vec<_> = s.claude.as_ref()?.attached.iter().map(|a| (a.pull, a.number)).collect(); + (!items.is_empty()).then(|| (s.id.clone(), s.cwd.clone(), items)) + }) + .collect(); + let some_unanswered = self.unanswered_items(); + if asks.is_empty() || !self.attached_sync.due(some_unanswered) { + return; + } + self.attached_sync.running = true; + self.attached_sync.last_try = Some(Instant::now()); + cx.spawn(async move |this, cx| { + let answers = cx.background_executor().spawn(async move { ask_github(asks) }).await; + let _ = this.update(cx, |ws, cx| { + ws.attached_sync.running = false; + let changed = answers.into_iter().fold(false, |c, (id, pull, number, title, state)| { + ws.edit_attached(&id, |list| links::set_status(list, pull, number, &title, state)) | c + }); + ws.attached_sync.failures = if ws.unanswered_items() { ws.attached_sync.failures + 1 } else { 0 }; + if changed { + ws.store.mark_dirty(); + cx.notify(); + } + }); + }) + .detach(); + } + + /// Whether some attached item of a session with a folder has no answer from GitHub yet. + fn unanswered_items(&self) -> bool { + let sessions = self.store.data.sessions.iter().filter(|s| s.cwd.is_dir()); + sessions.filter_map(|s| s.claude.as_ref()).flat_map(|m| &m.attached).any(|a| a.state.is_none()) + } +} + +/// Runs off the UI thread. An item `gh` cannot answer for keeps what it had. +fn ask_github(asks: Vec<(Id, PathBuf, Vec<(bool, u32)>)>) -> Vec { + let Some(exe) = crate::github::cli::locate() else { return vec![] }; + let mut repos: HashMap> = HashMap::new(); + let mut answers = vec![]; + for (id, cwd, items) in asks { + let found = repos.entry(cwd.clone()).or_insert_with(|| { + let gh = Gh::new(exe.clone(), cwd); + gh.repo().ok().map(|repo| (gh, repo)) + }); + let Some((gh, repo)) = found else { continue }; + for (pull, number) in items { + if let Ok((title, state)) = gh.item_status(repo, number) { + answers.push((id.clone(), pull, number, title, state)); + } + } + } + answers +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retrying_backs_off_to_the_normal_pace() { + assert_eq!(retry_wait(0), Duration::from_secs(15)); + assert_eq!(retry_wait(1), Duration::from_secs(30)); + assert_eq!(retry_wait(2), Duration::from_secs(60)); + assert_eq!(retry_wait(3), REFRESH_EVERY); + assert_eq!(retry_wait(u32::MAX), REFRESH_EVERY, "no overflow"); + } +} diff --git a/src/app/background.rs b/src/app/background.rs index 761989e..15faddb 100644 --- a/src/app/background.rs +++ b/src/app/background.rs @@ -60,6 +60,7 @@ impl Workspace { let update = this.update_in(cx, |ws, window, cx| { ws.serve_requests(requests, window, cx); ws.finish_handoffs(window, cx); + ws.check_open_files(window, cx); ws.update_activity(window, cx, &statuses) }); if update.is_err() { @@ -134,9 +135,31 @@ impl Workspace { self.refresh_live(cx); self.remember_open(cx); self.ingest_usage(cx); + self.sync_attached(cx); + self.sync_configs(cx); + self.refresh_files(cx); + self.refresh_marks(cx); + self.lower_tool_priority(cx); + self.refresh_pending(cx); cx.notify(); } + /// Windows: keep what the running Claude sessions start (builds, tests) from starving the other sessions. + fn lower_tool_priority(&self, cx: &mut Context) { + #[cfg(windows)] + { + let claude_pids: Vec = self + .live + .iter() + .filter(|l| self.store.session(&l.id).is_some_and(|r| r.kind == SessionKind::Claude)) + .filter_map(|l| l.view.read(cx).terminal.process_id()) + .collect(); + cx.background_executor().spawn(async move { crate::priority::lower_tool_priority(&claude_pids) }).detach(); + } + #[cfg(not(windows))] + let _ = cx; + } + /// Terminal sessions live only in CURRENT SESSION: once a shell's process is gone and its pane has been /// closed or replaced, its record is dropped instead of lingering in project history. pub(super) fn purge_dead_shells(&mut self) { diff --git a/src/app/config_sync.rs b/src/app/config_sync.rs new file mode 100644 index 0000000..7817e15 --- /dev/null +++ b/src/app/config_sync.rs @@ -0,0 +1,68 @@ +//! Keeps one configuration across the main account and every alt account (see `claude/config_sync.rs`): in the +//! background every few seconds, and just before a session starts. + +use std::time::{Duration, Instant}; + +use super::*; +use crate::claude::config_sync::{self as sync, Account as Files}; + +const EVERY: Duration = Duration::from_secs(3); + +#[derive(Default)] +pub struct Runner { + last_try: Option, + running: bool, + /// The failure was already shown this run. + told: bool, +} + +impl Workspace { + /// Where each account keeps its files. An account with a running session has its `.claude.json` left alone, + /// because Claude Code rewrites that file from memory. + fn account_files(&self, cx: &App) -> Vec { + let busy = |account: &Account| { + self.live.iter().any(|l| l.view.read(cx).is_running() && self.store.session_account(&l.id).is_some_and(|a| a.id == account.id)) + }; + self.store + .data + .accounts + .iter() + .filter_map(|a| match &a.dir { + Some(dir) => Some(sync::alt_account(dir, busy(a))), + None => sync::main_account(busy(a)), + }) + .collect() + } + + pub(super) fn sync_configs(&mut self, cx: &mut Context) { + let accounts = self.account_files(cx); + if accounts.len() < 2 || self.config_sync.running || self.config_sync.last_try.is_some_and(|t| t.elapsed() < EVERY) { + return; + } + self.config_sync.running = true; + self.config_sync.last_try = Some(Instant::now()); + cx.spawn(async move |this, cx| { + let result = cx.background_executor().spawn(async move { sync::sync(&accounts, &sync::state_path()) }).await; + let _ = this.update(cx, |ws, cx| { + ws.config_sync.running = false; + ws.tell_sync_failure(result, cx); + }); + }) + .detach(); + } + + /// Before a session starts, so it begins with what the other accounts changed a moment ago. + pub(super) fn sync_configs_now(&mut self, cx: &mut Context) { + let accounts = self.account_files(cx); + if accounts.len() >= 2 { + let result = sync::sync(&accounts, &sync::state_path()); + self.tell_sync_failure(result, cx); + } + } + + fn tell_sync_failure(&mut self, result: std::io::Result<()>, cx: &mut Context) { + if result.is_err() && !std::mem::replace(&mut self.config_sync.told, true) { + self.toast("Couldn't keep the Claude Code settings the same in every account. Will keep trying.", true, cx); + } + } +} diff --git a/src/app/cross.rs b/src/app/cross.rs index 672a4ed..f42eb9b 100644 --- a/src/app/cross.rs +++ b/src/app/cross.rs @@ -1,6 +1,7 @@ //! Sessions reaching other sessions: a Claude Code session can list, search and read the others and open a new one. -//! The MCP helper files the request (`claude/bridge.rs`) and Claudiu answers it on its next tick, with no dialog (product -//! owner decision). +//! The MCP helper files the request (`claude/bridge.rs`) and Claudiu answers it on its next tick. Listing, searching and +//! reading answer at once; opening a session with a first message of its own asks the user first, since that is a +//! prompt the user never wrote. use super::*; use crate::claude::bridge::{self, Request}; @@ -10,6 +11,23 @@ use serde_json::Value; /// 32,000 characters. const MAX_PROMPT: usize = 2000; +/// A `start_code_session` request that waits for the user's answer to its dialog. +pub struct PendingStart { + req: Request, + /// The dialog is up (it needs the one modal slot, which another dialog may hold). + shown: bool, +} + +/// Longest part of the first message the dialog quotes. +const SHOWN_PROMPT: usize = 600; + +/// What the dialog says about the session a session wants to open. +fn start_question(asker: &str, folder: &std::path::Path, prompt: &str) -> String { + let quoted: String = prompt.chars().take(SHOWN_PROMPT).collect(); + let more = if prompt.chars().count() > SHOWN_PROMPT { "…" } else { "" }; + format!("“{asker}” wants to open a new Claude Code session in {} with this first message:\n\n{quoted}{more}", folder.to_string_lossy()) +} + /// `2026-10-22 09:10 UTC` for a Unix time (days since 1970 turned into a calendar date, no time crate needed). fn utc(ts: i64) -> String { let (days, secs) = (ts.div_euclid(86_400), ts.rem_euclid(86_400)); @@ -66,10 +84,66 @@ impl Workspace { /// work is refused with the reason. pub(super) fn serve_requests(&mut self, requests: Vec, window: &mut Window, cx: &mut Context) { for mut req in requests.into_iter().filter(|r| r.deadline > crate::store::now()) { - let result = self.prepare(&mut req).and_then(|()| self.run_request(&req, window, cx)); + let prepared = self.prepare(&mut req); + if prepared.is_ok() && wants_confirmation(&req) { + self.pending_starts.push(PendingStart { req, shown: false }); + continue; + } + let result = prepared.and_then(|()| self.run_request(&req, window, cx)); let ok = result.is_ok(); answer(&req, ok, result.unwrap_or_else(|e| e)); } + self.settle_pending_starts(window, cx); + } + + /// Once a second: drop the requests nobody waits for, show the next dialog when the modal slot is free, and tell the + /// session when its dialog was closed without a yes. + fn settle_pending_starts(&mut self, window: &mut Window, cx: &mut Context) { + let now = crate::store::now(); + self.pending_starts.retain(|p| p.req.deadline > now); + let asking = match &self.modal { + Some(Modal::Confirm { act: Act::ConfirmStartSession(id), .. }) => Some(id.clone()), + _ => None, + }; + let mut declined = vec![]; + self.pending_starts.retain(|p| { + let gone = p.shown && asking.as_deref() != Some(p.req.id.as_str()); + if gone { + declined.push(p.req.clone()); + } + !gone + }); + for req in declined { + answer(&req, false, "The user declined."); + } + if self.modal.is_some() { + return; + } + let Some(p) = self.pending_starts.iter_mut().find(|p| !p.shown) else { return }; + p.shown = true; + let requester = p.req.from.split_once(':').map_or(p.req.from.as_str(), |(_, id)| id); + let asker = self.store.session(requester).map_or_else(|| "A session".to_string(), |s| s.display_title().to_string()); + let folder = PathBuf::from(p.req.args["folder"].as_str().unwrap_or_default()); + let prompt = p.req.args["prompt"].as_str().unwrap_or_default().trim().to_string(); + self.modal = Some(Modal::Confirm { + title: "Start a Claude Code session?".into(), + body: start_question(&asker, &folder, &prompt), + confirm: "Start session".into(), + danger: false, + act: Act::ConfirmStartSession(p.req.id.clone()), + }); + window.focus(&self.modal_focus, cx); + cx.notify(); + } + + /// The user said yes to a waiting `start_code_session`. + pub(super) fn confirm_start(&mut self, req_id: &str, window: &mut Window, cx: &mut Context) { + self.modal = None; + let Some(ix) = self.pending_starts.iter().position(|p| p.req.id == req_id) else { return }; + let req = self.pending_starts.remove(ix).req; + let result = self.run_request(&req, window, cx); + let ok = result.is_ok(); + answer(&req, ok, result.unwrap_or_else(|e| e)); } /// Check what starting a session needs and resolve the folder into `req.args["folder"]`. @@ -157,7 +231,7 @@ impl Workspace { let before = self.selected.clone(); // A prompt that looks like a flag must not become one. let leading = prompt.map(|p| if p.starts_with('-') { format!(" {p}") } else { p }).into_iter().collect(); - self.new_claude_with(cwd.clone(), leading, window, cx); + self.new_claude_with(cwd.clone(), leading, Starter::OtherSession, window, cx); match self.selected.clone().filter(|s| Some(s) != before.as_ref()) { Some(id) => { // A session started from another one is linked with it from the start. @@ -183,3 +257,35 @@ mod tests { assert_eq!(utc(951_782_400 + 3600), "2000-02-29 01:00 UTC"); } } + +/// A new session with a first message of its own is a prompt the user did not write. +fn wants_confirmation(req: &Request) -> bool { + req.tool == "start_code_session" && req.args["prompt"].as_str().is_some_and(|p| !p.trim().is_empty()) +} + +#[cfg(test)] +mod start_tests { + use super::*; + use serde_json::json; + + fn request(tool: &str, args: Value) -> Request { + Request { id: "r".into(), from: "code:s".into(), tool: tool.into(), args, deadline: 0 } + } + + #[test] + fn only_a_session_with_a_first_message_needs_the_users_yes() { + assert!(wants_confirmation(&request("start_code_session", json!({"folder": "/p", "prompt": "do it"})))); + assert!(!wants_confirmation(&request("start_code_session", json!({"folder": "/p"}))), "no prompt, nothing to approve"); + assert!(!wants_confirmation(&request("start_code_session", json!({"folder": "/p", "prompt": " "})))); + assert!(!wants_confirmation(&request("read_code_session", json!({"prompt": "x"})))); + } + + #[test] + fn the_dialog_quotes_a_long_message_in_part() { + let long = "x".repeat(SHOWN_PROMPT + 50); + let text = start_question("Fix build", std::path::Path::new("/p"), &long); + assert!(text.starts_with("“Fix build” wants to open a new Claude Code session in /p")); + assert!(text.ends_with(&format!("{}…", "x".repeat(SHOWN_PROMPT)))); + assert!(!start_question("a", std::path::Path::new("/p"), "short").contains('…')); + } +} diff --git a/src/app/editing.rs b/src/app/editing.rs new file mode 100644 index 0000000..d45f4d3 --- /dev/null +++ b/src/app/editing.rs @@ -0,0 +1,189 @@ +//! Editing files in editor mode: saving, following changes Claude makes on disk, and never dropping unsaved work. +//! A clean tab reloads when its file changes; a tab with unsaved edits shows a conflict instead, and the user picks. + +use std::path::Path; + +use gpui_kit::component::input::Position; + +use super::*; +use crate::files::{self, Contents, SaveError, Stamp}; + +/// Why a tab's file and its buffer disagree in a way the user has to settle. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Conflict { + /// Changed on disk while the tab had unsaved edits. + Changed, + Deleted, +} + +impl Workspace { + /// Save the shown tab of the shown session. Refuses, and shows the conflict, when the file changed on disk meanwhile. + pub fn save_shown(&mut self, cx: &mut Context) { + let Some(id) = self.active_id().cloned() else { return }; + let Some(pane) = self.panes.get_mut(&id) else { return }; + let Some(tab) = pane.active.and_then(|ix| pane.tabs.get_mut(ix)).filter(|t| t.note.is_none()) else { return }; + tab.saving = true; + let (path, format, expected) = (tab.path.clone(), tab.format.clone(), tab.stamp); + let text = tab.buffer.read(cx).value().to_string(); + cx.spawn(async move |this, cx| { + let (write, written) = (path.clone(), text.clone()); + let saved = cx.background_executor().spawn(async move { files::save(&write, &written, format, expected) }).await; + let _ = this.update(cx, |ws, cx| { + let mut tab = ws.panes.get_mut(&id).and_then(|p| p.tabs.iter_mut().find(|t| t.path == path)); + if let Some(tab) = tab.as_deref_mut() { + tab.saving = false; + } + match (saved, tab) { + (Ok(stamp), Some(tab)) => { + tab.stamp = Some(stamp); + // Typing while the file was written leaves edits the file doesn't have yet. + tab.dirty = tab.buffer.read(cx).value() != text.as_str(); + tab.conflict = None; + ws.tell_server_saved(&id, &path); + ws.refresh_marks(cx); + } + (Ok(_), None) => {} + (Err(SaveError::Changed), tab) => { + if let Some(tab) = tab { + tab.conflict = Some(Conflict::Changed); + } + ws.toast("Not saved: the file changed on disk. Reload it or keep your version.", true, cx); + } + (Err(SaveError::Io(e)), _) => ws.toast(format!("Could not save {}: {e}", path.display()), true, cx), + } + cx.notify(); + }); + }) + .detach(); + } + + /// Look at the shown session's open files on disk (once a second, off the UI thread): reload the clean ones that + /// changed, and flag a conflict on the ones with unsaved edits. + pub(super) fn check_open_files(&mut self, window: &mut Window, cx: &mut Context) { + let Some(id) = self.active_id().filter(|_| self.editing()).cloned() else { return }; + let Some(pane) = self.panes.get(&id) else { return }; + // A tab without a stamp follows nothing: it was never read, or the user chose to keep their version. + let watched: Vec<(PathBuf, Stamp)> = pane.tabs.iter().filter(|t| !t.saving).filter_map(|t| Some((t.path.clone(), t.stamp?))).collect(); + if watched.is_empty() { + return; + } + cx.spawn_in(window, async move |this, cx| { + let changed: Vec<(PathBuf, Stamp, Option)> = cx + .background_executor() + .spawn(async move { + watched + .into_iter() + .filter_map(|(path, seen)| { + let now = files::stamp(&path); + (now != Some(seen)).then_some((path, seen, now)) + }) + .collect() + }) + .await; + let _ = this.update_in(cx, |ws, window, cx| { + for (path, seen, now) in changed { + let Some(tab) = ws.panes.get_mut(&id).and_then(|p| p.tabs.iter_mut().find(|t| t.path == path)) else { continue }; + // Saved or reloaded since the look began (or being saved now): the new stamp is the tab's own. + if tab.saving || tab.stamp != Some(seen) { + continue; + } + match (now, tab.dirty) { + (Some(_), false) => ws.reload_tab(&id, path, window, cx), + (Some(_), true) => tab.conflict = Some(Conflict::Changed), + (None, _) => tab.conflict = Some(Conflict::Deleted), + } + } + cx.notify(); + }); + }) + .detach(); + } + + /// Read the tab's file again, dropping unsaved edits; the cursor stays on its line. + pub fn reload_tab(&mut self, id: &Id, path: PathBuf, window: &mut Window, cx: &mut Context) { + let id = id.clone(); + cx.spawn_in(window, async move |this, cx| { + let read = path.clone(); + let (contents, now) = cx.background_executor().spawn(async move { (files::read(&read), files::stamp(&read)) }).await; + let _ = this.update_in(cx, |ws, window, cx| { + let Some(tab) = ws.panes.get_mut(&id).and_then(|p| p.tabs.iter_mut().find(|t| t.path == path)) else { return }; + match contents { + Ok(Contents::Text { text, format, stamp }) => { + tab.buffer.update(cx, |b, cx| { + let at = b.cursor_position(); + b.set_tab_size(super::editor_mode::tab_size(&format), cx); + b.set_value(text, window, cx); + b.set_cursor_position(Position::new(at.line, 0), window, cx); + }); + (tab.format, tab.stamp, tab.dirty, tab.conflict) = (format, Some(stamp), false, None); + ws.sync_with_server(&id, &path, true, cx); + } + // Grew too large, stopped being text, or vanished: keep what is shown and let the user decide. The + // stamp moves on so the once-a-second check does not read the same file again until it changes. + _ => { + tab.conflict = Some(if now.is_some() { Conflict::Changed } else { Conflict::Deleted }); + tab.stamp = now.or(tab.stamp); + } + } + cx.notify(); + }); + }) + .detach(); + } + + /// Settle a conflict by keeping the buffer: the next save writes it over whatever is on disk. + pub fn keep_mine(&mut self, id: &Id, path: &Path, cx: &mut Context) { + if let Some(tab) = self.panes.get_mut(id).and_then(|p| p.tabs.iter_mut().find(|t| t.path == path)) { + tab.conflict = None; + tab.stamp = None; + tab.dirty = true; + cx.notify(); + } + } + + /// Close tab `ix`, asking first when it has unsaved edits. + pub fn request_close_tab(&mut self, id: &Id, ix: usize, window: &mut Window, cx: &mut Context) { + let Some(tab) = self.panes.get(id).and_then(|p| p.tabs.get(ix)) else { return }; + if !tab.dirty { + self.close_tab(id, ix, cx); + return; + } + let name = tab.path.file_name().unwrap_or_default().to_string_lossy().to_string(); + self.modal = Some(Modal::Confirm { + title: format!("Discard changes to {name}?"), + body: "Your unsaved edits to this file will be lost.".into(), + confirm: "Discard".into(), + danger: true, + act: Act::DiscardTab(id.clone(), tab.path.clone()), + }); + window.focus(&self.modal_focus, cx); + cx.notify(); + } + + /// Files with unsaved edits, in one session's pane or (with `None`) in all of them. + pub fn unsaved(&self, id: Option<&Id>) -> usize { + self.panes.iter().filter(|(pid, _)| id.is_none_or(|id| id == *pid)).flat_map(|(_, p)| &p.tabs).filter(|t| t.dirty).count() + } + + /// End a session, asking first when its editor has unsaved files. + pub(super) fn request_close_live(&mut self, id: &Id, window: &mut Window, cx: &mut Context) { + let unsaved = self.unsaved(Some(id)); + if unsaved == 0 { + self.close_live(id, window, cx); + return; + } + self.modal = Some(Modal::Confirm { + title: "End session?".into(), + body: format!("{unsaved} file{} in its editor {} unsaved changes that will be lost.", plural(unsaved), if unsaved == 1 { "has" } else { "have" }), + confirm: "End session".into(), + danger: true, + act: Act::ConfirmCloseLive(id.clone()), + }); + window.focus(&self.modal_focus, cx); + cx.notify(); + } +} + +pub(super) fn plural(n: usize) -> &'static str { + if n == 1 { "" } else { "s" } +} diff --git a/src/app/editor_mode.rs b/src/app/editor_mode.rs new file mode 100644 index 0000000..e4eff78 --- /dev/null +++ b/src/app/editor_mode.rs @@ -0,0 +1,520 @@ +//! Editor mode: the shown session's terminal narrows to the left, and its folder's files and an editor fill the rest. +//! Each session keeps its own pane while it runs; listing and reading files happen off the UI thread (see `files`). + +use gpui_kit::component::input::{EditorState, InputEvent, Position, TabSize}; +use gpui_kit::component::tree::{TreeEvent, TreeItem, TreeState}; + +use super::*; +use super::editing::Conflict; +use crate::files::{self, Contents, Node, Stamp}; + +/// Most entries listed in the tree, so a session started in a huge plain folder (or the home folder) stays usable. +const LIST_LIMIT: usize = 20_000; + +/// A session's files and editor. Never persisted; it goes away with the session. +pub struct EditorPane { + /// The pane as a whole (its file tree): the keyboard needs to be inside the pane for its shortcuts, such as Ctrl+P, + /// which otherwise belong to Claude Code. + pub focus: FocusHandle, + pub tree: Entity, + /// Open files, in the order they were opened, and the one shown. + pub tabs: Vec, + pub active: Option, + /// The listing the tree was last given, to skip redrawing it when nothing changed, and the folder it lists. + pub nodes: Vec, + pub root: PathBuf, + /// The listing's files, and each one's path under `root` as quick open shows it; worked out once per listing + /// rather than on every keystroke. + pub files: std::sync::Arc>, + pub relative: std::sync::Arc>, + /// Git's changes by `path_key`, see `files::Listing`. + pub changed: std::sync::Arc>, + pub truncated: bool, + /// Places the editor left (file and cursor line), latest last, for Back; and the ones Back left, for Forward. + pub back: Vec<(PathBuf, u32)>, + pub forward: Vec<(PathBuf, u32)>, + /// Files shown lately, latest first, which quick open lists first. + pub recent: Vec, + /// Folders the user opened, kept open across refreshes. + pub expanded: HashSet, + /// Tree ids of the listed folders with nothing in them, which the tree would otherwise take for files, since it + /// counts an item with no children as one. + pub empty_folders: std::sync::Arc>, + /// A listing is on its way. A refresh asked for meanwhile sets `relist`, because the walk under way may have + /// passed the change already. + pub listing: bool, + pub relist: bool, + /// Quick open or find in files, while it is up. + pub picker: Option, + /// Language servers by program name; dropping the pane (the session ended) stops them. + pub servers: HashMap<&'static str, super::language_servers::ServerState>, + pub _sub: Subscription, +} + +/// An open file. Its buffer keeps the cursor, scroll and undo history while other tabs are shown. +pub struct Tab { + pub path: PathBuf, + pub buffer: Entity, + /// Why the file's text isn't shown (too large, not text, unreadable); the buffer stays empty then. + pub note: Option, + /// How the file differs from the buffer (line ends, tab indents), which saving puts back (see `files::read`). + pub format: files::Format, + /// The file on disk as last read or saved; `None` when the user chose to keep their version over a change. + pub stamp: Option, + /// Edited since it was last read or saved. + pub dirty: bool, + /// The lines that differ from the last commit, as of the last read or save of the file (`git::lines`). + pub marks: std::sync::Arc>, + /// A save is being written; the disk check leaves the tab alone until it lands, so the save isn't taken for a + /// change from outside. + pub saving: bool, + pub conflict: Option, + /// The highlighter's name for the file's language (see `files::language`), which also picks its language server. + pub language: Option<&'static str>, + /// The document version the language server last heard of, and the server, once it has the file. + pub version: i32, + pub server: Option>, + pub _sub: Option, +} + +impl EditorPane { + pub fn shown(&self) -> Option<&Tab> { + self.tabs.get(self.active?) + } +} + +/// Add the grammars gpui-kit doesn't ship to the highlighter (see `files::language` for the names). Once, at startup. +pub fn register_languages() { + use gpui_kit::component::highlighter::{LanguageConfig, LanguageRegistry}; + let gleam = LanguageConfig::new( + "gleam", + tree_sitter_gleam::LANGUAGE.into(), + vec![], + tree_sitter_gleam::HIGHLIGHT_QUERY, + "", + tree_sitter_gleam::LOCALS_QUERY, + ); + let registry = LanguageRegistry::singleton(); + registry.register("gleam", &gleam); + // gpui-kit's TSX takes tree-sitter-typescript's highlights, which only add TypeScript's extras to JavaScript's, so + // alone they leave most of a .tsx file uncoloured; and neither TSX nor JavaScript (which .jsx files use) colours + // JSX. TSX gets TypeScript's full query instead (its grammar is TypeScript's plus JSX), and both get JSX's. + let (Some(typescript), Some(tsx), Some(javascript)) = (registry.language("typescript"), registry.language("tsx"), registry.language("javascript")) else { + return; + }; + let with_jsx = |config: LanguageConfig, highlights: &str| LanguageConfig { highlights: format!("{highlights}\n{JSX_HIGHLIGHTS}").into(), ..config }; + registry.register("tsx", &with_jsx(LanguageConfig { injection_languages: typescript.injection_languages.clone(), injections: typescript.injections.clone(), ..tsx }, &typescript.highlights)); + if !javascript.highlights.contains(JSX_HIGHLIGHTS) { + registry.register("javascript", &with_jsx(javascript.clone(), &javascript.highlights)); + } +} + +/// tree-sitter-javascript's `highlights-jsx.scm`, which gpui-kit leaves out. +const JSX_HIGHLIGHTS: &str = r#" +(jsx_opening_element (identifier) @tag (#match? @tag "^[a-z][^.]*$")) +(jsx_closing_element (identifier) @tag (#match? @tag "^[a-z][^.]*$")) +(jsx_self_closing_element (identifier) @tag (#match? @tag "^[a-z][^.]*$")) + +(jsx_attribute (property_identifier) @attribute) +(jsx_opening_element (["<" ">"]) @punctuation.bracket) +(jsx_closing_element ([""]) @punctuation.bracket) +(jsx_self_closing_element (["<" "/>"]) @punctuation.bracket) +"#; + +impl Workspace { + pub fn toggle_editor(&mut self, window: &mut Window, cx: &mut Context) { + if !self.editor_mode && !self.active_id().is_some_and(|id| self.is_running(id, cx)) { + self.toast("Open a Claude session to use the editor.", false, cx); + return; + } + self.editor_mode = !self.editor_mode; + if self.editor_mode { + self.refresh_files(cx); + } + self.focus_active(window, cx); + cx.notify(); + } + + /// A path the user Ctrl+clicked in the session's terminal: open it in editor mode, at its line (1-based) when one was + /// given. Text that only looks like a path, naming no file, does nothing. + pub fn open_from_terminal(&mut self, id: &Id, path: &str, line: Option, window: &mut Window, cx: &mut Context) { + let Some(cwd) = self.store.session(id).map(|s| s.cwd.clone()) else { return }; + let Some(file) = dunce::canonicalize(cwd.join(path)).ok().filter(|f| f.is_file()) else { return }; + if self.active_id() != Some(id) { + return; + } + if !self.editor_mode { + self.toggle_editor(window, cx); + } + if self.shown_pane(cx).is_none() { + return; + } + self.open_file(id, file, line.map(|l| l.saturating_sub(1)), window, cx); + } + + /// Editor mode is on and has a session to show; the home page keeps its sidebars. + pub fn editing(&self) -> bool { + self.editor_mode && self.active_id().is_some() + } + + /// The pane of the shown session while editor mode is on, created on first use. + pub fn shown_pane(&mut self, cx: &mut Context) -> Option<(Id, &EditorPane)> { + let id = self.active_id().filter(|_| self.editing()).cloned()?; + if !self.panes.contains_key(&id) { + let tree = cx.new(|cx| TreeState::new(cx)); + let owner = id.clone(); + let sub = cx.subscribe(&tree, move |ws: &mut Workspace, _, ev: &TreeEvent, _| { + if let Some(p) = ws.panes.get_mut(&owner) { + match ev { + TreeEvent::Expanded(path) => p.expanded.insert(path.to_string()), + TreeEvent::Collapsed(path) => p.expanded.remove(path.as_ref()), + }; + } + }); + let pane = EditorPane { + focus: cx.focus_handle(), + tree, + tabs: vec![], + active: None, + nodes: vec![], + root: PathBuf::new(), + files: Default::default(), + relative: Default::default(), + changed: Default::default(), + truncated: false, + back: vec![], + forward: vec![], + recent: vec![], + expanded: HashSet::new(), + empty_folders: Default::default(), + listing: false, + relist: false, + picker: None, + servers: HashMap::new(), + _sub: sub, + }; + self.panes.insert(id.clone(), pane); + self.refresh_files(cx); + } + let pane = self.panes.get(&id)?; + Some((id, pane)) + } + + /// List the shown session's folder again (files Claude added, changed marks), off the UI thread. + pub(super) fn refresh_files(&mut self, cx: &mut Context) { + let Some(id) = self.active_id().filter(|_| self.editor_mode).cloned() else { return }; + let Some(root) = self.store.session(&id).map(|s| s.cwd.clone()) else { return }; + let Some(pane) = self.panes.get_mut(&id) else { return }; + if pane.listing { + pane.relist = true; + return; + } + pane.listing = true; + cx.spawn(async move |this, cx| { + let listing = cx.background_executor().spawn(async move { files::list(&root, LIST_LIMIT) }).await; + let _ = this.update(cx, |ws, cx| { + let Some(pane) = ws.panes.get_mut(&id) else { return }; + pane.listing = false; + let relist = std::mem::take(&mut pane.relist); + pane.changed = std::sync::Arc::new(listing.changed); + pane.truncated = listing.truncated; + pane.root = listing.root; + if pane.nodes != listing.nodes { + let items = tree_items(&listing.nodes, &pane.expanded); + let selected = pane.shown().map(|t| t.path.to_string_lossy().to_string()); + pane.tree.update(cx, |t, cx| { + t.set_items(items, cx); + let ix = selected.and_then(|s| t.index_of(&s.into())); + t.set_selected_index(ix, cx); + }); + pane.empty_folders = std::sync::Arc::new(empty_folders(&listing.nodes)); + let all = files::files_of(&listing.nodes); + pane.relative = std::sync::Arc::new(all.iter().map(|f| super::picker::relative(f, &pane.root)).collect()); + pane.files = std::sync::Arc::new(all); + pane.nodes = listing.nodes; + } + if relist { + ws.refresh_files(cx); + } + cx.notify(); + }); + }) + .detach(); + } + + /// Re-read, off the UI thread, which lines of the shown file differ from the last commit. + pub(super) fn refresh_marks(&mut self, cx: &mut Context) { + let Some(id) = self.active_id().filter(|_| self.editor_mode).cloned() else { return }; + let Some(path) = self.panes.get(&id).and_then(|p| p.shown()).filter(|t| t.note.is_none()).map(|t| t.path.clone()) else { return }; + cx.spawn(async move |this, cx| { + let read = path.clone(); + let marks = cx.background_executor().spawn(async move { crate::git::lines::changed_lines(&read) }).await; + let _ = this.update(cx, |ws, cx| { + let Some(tab) = ws.panes.get_mut(&id).and_then(|p| p.tabs.iter_mut().find(|t| t.path == path)) else { return }; + if *tab.marks != marks { + tab.marks = std::sync::Arc::new(marks); + cx.notify(); + } + }); + }) + .detach(); + } + + /// Show `path` in the session's editor at `line` (0-based), as a jump that Back returns from. + pub fn open_file(&mut self, id: &Id, path: PathBuf, line: Option, window: &mut Window, cx: &mut Context) { + self.remember_place(id, &path, line, cx); + self.note_recent(id, &path); + self.show_file(id, path, line, window, cx); + } + + /// Show `path` in the session's editor: its tab when it is open, otherwise a new tab once the file is read off the UI + /// thread. `line` (0-based) puts the cursor there. + pub(super) fn show_file(&mut self, id: &Id, path: PathBuf, line: Option, window: &mut Window, cx: &mut Context) { + let Some(pane) = self.panes.get_mut(id) else { return }; + if let Some(ix) = pane.tabs.iter().position(|t| t.path == path) { + pane.active = Some(ix); + let buffer = pane.tabs[ix].buffer.clone(); + buffer.update(cx, |b, cx| match line { + Some(line) => b.set_cursor_position(Position::new(line as u32, 0), window, cx), + None => b.focus(window, cx), + }); + cx.notify(); + return; + } + let id = id.clone(); + let read = path.clone(); + cx.spawn_in(window, async move |this, cx| { + let contents = cx.background_executor().spawn(async move { files::read(&read) }).await; + let _ = this.update_in(cx, |ws, window, cx| { + let language = files::language(&path); + let buffer = cx.new(|cx| { + let state = EditorState::new(window, cx); + match language { + Some(language) => state.language(language), + None => state, + } + }); + let (mut format, mut stamp, mut sub) = (files::Format::default(), None, None); + let note = match contents { + Ok(Contents::Text { text, format: f, stamp: s }) => { + buffer.update(cx, |b, cx| { + b.set_tab_size(tab_size(&f), cx); + b.set_value(text, window, cx); + b.set_cursor_position(Position::new(line.unwrap_or(0) as u32, 0), window, cx); + }); + // `set_value` (opening, reloading) sends no Change, so only the user's edits mark the tab. + sub = Some(cx.subscribe(&buffer, |ws: &mut Workspace, buffer, ev: &InputEvent, cx| { + if !matches!(ev, InputEvent::Change) { + return; + } + let edited = ws.panes.iter_mut().find_map(|(owner, p)| { + let tab = p.tabs.iter_mut().find(|t| t.buffer == buffer)?; + tab.dirty = true; + Some((owner.clone(), tab.path.clone())) + }); + if let Some((owner, path)) = edited { + ws.sync_with_server(&owner, &path, false, cx); + cx.notify(); + } + })); + (format, stamp) = (f, Some(s)); + None + } + Ok(Contents::TooLarge) => Some(format!( + "This file is too large for the editor (over {} lines or {} MB).", + files::MAX_LINES, + files::MAX_BYTES / (1024 * 1024) + )), + Ok(Contents::NotText) => Some("This file isn't UTF-8 text.".into()), + Err(e) => Some(format!("Could not read this file: {e}")), + }; + let Some(pane) = ws.panes.get_mut(&id) else { return }; + // A second click while the file was being read: keep the tab that is already there. + let opened = pane.tabs.iter().position(|t| t.path == path); + let ix = opened.unwrap_or_else(|| { + let language = language.filter(|_| note.is_none()); + pane.tabs.push(Tab { path: path.clone(), buffer, note, format, stamp, dirty: false, marks: Default::default(), saving: false, conflict: None, language, version: 0, server: None, _sub: sub }); + pane.tabs.len() - 1 + }); + pane.active = Some(ix); + let shown = pane.tabs[ix].buffer.clone(); + shown.update(cx, |b, cx| b.focus(window, cx)); + if opened.is_none() { + ws.attach_server(&id, &path, cx); + ws.refresh_marks(cx); + } + cx.notify(); + }); + }) + .detach(); + } + + /// Close tab `ix`; the tab to its right is shown next, or the last one. + pub fn close_tab(&mut self, id: &Id, ix: usize, cx: &mut Context) { + let Some(pane) = self.panes.get_mut(id).filter(|p| ix < p.tabs.len()) else { return }; + Self::tell_server_closed(&pane.tabs.remove(ix)); + pane.active = active_after_close(pane.active, ix, pane.tabs.len()); + cx.notify(); + } + + pub fn show_tab(&mut self, id: &Id, ix: usize, window: &mut Window, cx: &mut Context) { + if let Some(path) = self.panes.get(id).and_then(|p| p.tabs.get(ix)).map(|t| t.path.clone()) { + self.remember_place(id, &path, None, cx); + self.note_recent(id, &path); + } + if let Some(pane) = self.panes.get_mut(id).filter(|p| ix < p.tabs.len()) { + pane.active = Some(ix); + pane.tabs[ix].buffer.update(cx, |b, cx| b.focus(window, cx)); + cx.notify(); + } + } +} + +/// What an entry of the editor's right-click menu does. +#[derive(Clone, Copy, Debug)] +pub enum EditorCommand { + GoToDefinition, + Cut, + Copy, + Paste, + SelectAll, + Ask(Ask), +} + +impl Workspace { + /// Run a menu entry on the shown file's editor, which has the keyboard again after the menu closes. + pub(super) fn run_editor_command(&mut self, command: EditorCommand, window: &mut Window, cx: &mut Context) { + use gpui_kit::component::input::{Copy, Cut, GoToDefinition, Paste, SelectAll}; + if let EditorCommand::Ask(ask) = command { + return self.ask_claude(ask, window, cx); + } + let Some(buffer) = self.active_id().and_then(|id| self.panes.get(id)).and_then(|p| p.shown()).map(|t| t.buffer.clone()) else { return }; + buffer.update(cx, |b, cx| b.focus(window, cx)); + let action: Box = match command { + EditorCommand::GoToDefinition => Box::new(GoToDefinition), + EditorCommand::Cut => Box::new(Cut), + EditorCommand::Copy => Box::new(Copy), + EditorCommand::Paste => Box::new(Paste), + EditorCommand::SelectAll => Box::new(SelectAll), + EditorCommand::Ask(_) => return, + }; + window.dispatch_action(action, cx); + } +} + +/// A file indented with tabs is shown with `files::TAB_WIDTH` spaces for each tab, so the Tab key indents by as many. +pub(super) fn tab_size(format: &files::Format) -> TabSize { + match &format.tabs { + Some(indents) if indents.hard => TabSize { tab_size: files::TAB_WIDTH, hard_tabs: false }, + _ => TabSize::default(), + } +} + +fn empty_folders(nodes: &[Node]) -> HashSet { + let mut empty = HashSet::new(); + for n in nodes { + match &n.children { + Some(children) if children.is_empty() => { + empty.insert(n.path.to_string_lossy().to_string()); + } + Some(children) => empty.extend(empty_folders(children)), + None => {} + } + } + empty +} + +fn tree_items(nodes: &[Node], expanded: &HashSet) -> Vec { + nodes + .iter() + .map(|n| { + let id = n.path.to_string_lossy().to_string(); + let open = expanded.contains(&id); + let item = TreeItem::new(id, n.name.clone()); + match &n.children { + Some(children) => item.children(tree_items(children, expanded)).expanded(open), + None => item, + } + }) + .collect() +} + +/// The tab shown after tab `closed` goes, given the one shown before and how many are left: the same file when another +/// tab closed, otherwise the tab that took the closed one's place, or the new last one. +fn active_after_close(active: Option, closed: usize, left: usize) -> Option { + let a = active?; + match a.cmp(&closed) { + std::cmp::Ordering::Less => Some(a), + std::cmp::Ordering::Greater => Some(a - 1), + std::cmp::Ordering::Equal => (left > 0).then(|| closed.min(left - 1)), + } +} + +#[cfg(test)] +mod tests { + use super::active_after_close; + + /// The highlighter falls back to plain text when a grammar or its query fails to load, so check that each language + /// `files::language` names really colours code. + #[test] + fn every_named_language_highlights() { + use gpui_kit::component::highlighter::{HighlightTheme, SyntaxHighlighter}; + use gpui_kit::component::input::Rope; + super::register_languages(); + let samples = [ + ("rust", "fn main() { let x = 1; }"), + ("typescript", "const x: number = 1;"), + ("tsx", "const a =
{x}
;"), + ("javascript", "function f() { return 1; }"), + ("json", "{\"a\": 1}"), + ("toml", "[package]\nname = \"x\""), + ("yaml", "a: 1"), + ("markdown", "# Title\n\nSome *text*."), + ("html", "

hi

"), + ("css", "a { color: red; }"), + ("bash", "echo \"$HOME\""), + ("gleam", "pub fn main() { let x = 1 }"), + ]; + let theme = HighlightTheme::default_dark(); + for (lang, code) in samples { + let mut h = SyntaxHighlighter::new(lang); + assert_eq!(h.language().as_ref(), lang, "{lang} fell back to plain text"); + let rope = Rope::from(code); + h.update(None, &rope, None); + assert!(!h.styles(&(0..code.len()), &*theme).is_empty(), "{lang} has no highlights"); + } + } + + /// Whether some highlight colours exactly `part` of `code`. + fn coloured(lang: &str, code: &str, part: &str) -> bool { + use gpui_kit::component::highlighter::{HighlightTheme, SyntaxHighlighter}; + use gpui_kit::component::input::Rope; + super::register_languages(); + let mut h = SyntaxHighlighter::new(lang); + h.update(None, &Rope::from(code), None); + let start = code.find(part).unwrap(); + let theme = HighlightTheme::default_dark(); + h.styles(&(0..code.len()), &*theme).iter().any(|(range, style)| *range == (start..start + part.len()) && style.color.is_some()) + } + + #[test] + fn tsx_and_jsx_colour_code_and_tags() { + let code = "function App() { const s = \"hi\"; return
{s}
; }"; + for lang in ["tsx", "javascript"] { + for part in ["function", "App", "\"hi\"", "div", "className"] { + assert!(coloured(lang, code, part), "{lang}: {part} has no colour"); + } + } + } + + #[test] + fn closing_a_tab_keeps_the_shown_file_or_moves_to_a_neighbour() { + // Tabs a b c, b shown. + assert_eq!(active_after_close(Some(1), 0, 2), Some(0), "closing a: b is still shown"); + assert_eq!(active_after_close(Some(1), 2, 2), Some(1), "closing c: b is still shown"); + assert_eq!(active_after_close(Some(1), 1, 2), Some(1), "closing b: c takes its place"); + assert_eq!(active_after_close(Some(2), 2, 2), Some(1), "closing the last shown tab: the one before it"); + assert_eq!(active_after_close(Some(0), 0, 0), None, "closing the only tab"); + assert_eq!(active_after_close(None, 0, 1), None); + } +} diff --git a/src/app/file_ops.rs b/src/app/file_ops.rs new file mode 100644 index 0000000..b0b0da4 --- /dev/null +++ b/src/app/file_ops.rs @@ -0,0 +1,161 @@ +//! Creating, renaming and deleting files from editor mode's file tree (the disk work is `files::create_file`, +//! `create_folder`, `rename` and `delete`, which keep to the session's folder). Open tabs follow a rename and close with a delete. + +use super::*; +use crate::files; + +/// What a file name the user types is for. +#[derive(Clone, Debug)] +pub enum NameFor { + /// A new file in this folder. + FileIn(PathBuf), + /// A new folder in this folder. + FolderIn(PathBuf), + /// A new name for this file or folder. + Rename(PathBuf), +} + +impl Workspace { + /// The tree's right-click menu: for a file or folder, or for the session folder (`None`). + pub fn file_menu(&self, id: &Id, path: Option<&std::path::Path>, folder: bool) -> Vec { + let Some(pane) = self.panes.get(id) else { return vec![] }; + let Some(path) = path else { + return Self::new_items(id, &pane.root); + }; + let dir = if folder { path.to_path_buf() } else { path.parent().map_or_else(|| pane.root.clone(), |p| p.to_path_buf()) }; + let mut items = Self::new_items(id, &dir); + items.push(MenuItem::new("Rename…", Act::AskFileName(id.clone(), NameFor::Rename(path.to_path_buf())))); + let reveal = if cfg!(target_os = "macos") { "Reveal in Finder" } else { "Reveal in File Explorer" }; + items.push(MenuItem { separator_before: true, ..MenuItem::new("Copy relative path", Act::CopyText(super::picker::relative(path, &pane.root))) }); + items.push(MenuItem::new(reveal, Act::Reveal(path.to_path_buf()))); + items.push(MenuItem { danger: true, separator_before: true, ..MenuItem::new("Delete", Act::AskDelete(id.clone(), path.to_path_buf())) }); + items + } + + fn new_items(id: &Id, dir: &std::path::Path) -> Vec { + vec![ + MenuItem::new("New file…", Act::AskFileName(id.clone(), NameFor::FileIn(dir.to_path_buf()))), + MenuItem::new("New folder…", Act::AskFileName(id.clone(), NameFor::FolderIn(dir.to_path_buf()))), + ] + } + + pub(super) fn ask_file_name(&mut self, id: Id, purpose: NameFor, window: &mut Window, cx: &mut Context) { + let (value, placeholder) = match &purpose { + NameFor::FileIn(_) => (String::new(), "name.ext"), + NameFor::FolderIn(_) => (String::new(), "name"), + NameFor::Rename(path) => (path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), "name"), + }; + let input = self.modal_input(&value, placeholder, window, cx); + self.modal = Some(Modal::FileName { id, purpose, input }); + } + + pub(super) fn ask_delete(&mut self, id: Id, path: PathBuf, window: &mut Window, cx: &mut Context) { + let Some(pane) = self.panes.get(&id) else { return }; + let name = super::picker::relative(&path, &pane.root); + let folder = path.is_dir(); + let unsaved = pane.tabs.iter().any(|t| t.dirty && crate::platform::is_same_or_under(&t.path, &path)); + let mut body = if folder { "Deletes the folder and everything in it from disk." } else { "Deletes the file from disk." }.to_string(); + body.push_str(" This can't be undone."); + if unsaved { + body.push_str(" Unsaved edits in its open tabs are lost."); + } + self.modal = Some(Modal::Confirm { title: format!("Delete {name}?"), body, confirm: "Delete".into(), danger: true, act: Act::ConfirmDelete(id, path) }); + window.focus(&self.modal_focus, cx); + } + + /// Carry out a typed file name; `Err` says why it can't be used, and the dialog stays open. + pub(super) fn apply_file_name(&mut self, id: &Id, purpose: &NameFor, name: &str, window: &mut Window, cx: &mut Context) -> Result<(), String> { + let root = self.panes.get(id).map(|p| p.root.clone()).ok_or("The session's files are gone.")?; + match purpose { + NameFor::FileIn(dir) => { + let path = files::create_file(&root, dir, name).map_err(|e| e.to_string())?; + if let Some(pane) = self.panes.get_mut(id) { + pane.expanded.insert(dir.to_string_lossy().into_owned()); + } + self.refresh_files(cx); + self.open_file(id, path, None, window, cx); + } + NameFor::FolderIn(dir) => { + let path = files::create_folder(&root, dir, name).map_err(|e| e.to_string())?; + if let Some(pane) = self.panes.get_mut(id) { + pane.expanded.insert(dir.to_string_lossy().into_owned()); + pane.expanded.insert(path.to_string_lossy().into_owned()); + } + self.refresh_files(cx); + } + NameFor::Rename(from) => { + let to = files::rename(&root, from, name).map_err(|e| e.to_string())?; + self.follow_rename(id, from, to, window, cx); + self.refresh_files(cx); + } + } + Ok(()) + } + + /// The open tab of a renamed file shows it under its new name. The shown tab, when its language changed and it has + /// no unsaved edits, is opened afresh, since a buffer keeps the highlighting it was made with. For a renamed folder, + /// every tab inside it follows, and its open folders stay open. + fn follow_rename(&mut self, id: &Id, from: &std::path::Path, to: PathBuf, window: &mut Window, cx: &mut Context) { + self.retarget_history(id, from, &to); + if to.is_dir() { + self.follow_folder_rename(id, from, &to, cx); + return; + } + let Some(pane) = self.panes.get(id) else { return }; + let Some(ix) = pane.tabs.iter().position(|t| t.path == from) else { return }; + let language = files::language(&to); + let tab = &pane.tabs[ix]; + if pane.active == Some(ix) && language != tab.language && !tab.dirty && tab.note.is_none() { + self.close_tab(id, ix, cx); + self.open_file(id, to, None, window, cx); + return; + } + let Some(tab) = self.panes.get_mut(id).map(|p| &mut p.tabs[ix]) else { return }; + Self::tell_server_closed(tab); + (tab.path, tab.server, tab.version) = (to.clone(), None, 0); + if tab.note.is_none() { + tab.language = language; + } + self.attach_server(id, &to, cx); + cx.notify(); + } + + fn follow_folder_rename(&mut self, id: &Id, from: &std::path::Path, to: &std::path::Path, cx: &mut Context) { + let Some(pane) = self.panes.get_mut(id) else { return }; + let moved = |path: &std::path::Path| path.strip_prefix(from).ok().map(|rest| to.join(rest)); + pane.expanded = pane.expanded.iter().map(|key| moved(std::path::Path::new(key)).map_or_else(|| key.clone(), |p| p.to_string_lossy().into_owned())).collect(); + let mut retargeted = vec![]; + for tab in pane.tabs.iter_mut() { + let Some(path) = moved(&tab.path) else { continue }; + Self::tell_server_closed(tab); + (tab.path, tab.server, tab.version) = (path.clone(), None, 0); + retargeted.push(path); + } + for path in retargeted { + self.attach_server(id, &path, cx); + } + cx.notify(); + } + + /// Delete off the UI thread (a folder can hold many files); tabs inside it close once it is gone. + pub(super) fn delete_path(&mut self, id: Id, path: PathBuf, cx: &mut Context) { + let Some(root) = self.panes.get(&id).map(|p| p.root.clone()) else { return }; + let target = path.clone(); + cx.spawn(async move |this, cx| { + let done = cx.background_executor().spawn(async move { files::delete(&root, &target) }).await; + let _ = this.update(cx, |ws, cx| { + match done { + Ok(()) => { + ws.forget_history(&id, &path); + while let Some(ix) = ws.panes.get(&id).and_then(|p| p.tabs.iter().position(|t| crate::platform::is_same_or_under(&t.path, &path))) { + ws.close_tab(&id, ix, cx); + } + } + Err(e) => ws.toast(format!("Could not delete it: {e}"), true, cx), + } + ws.refresh_files(cx); + }); + }) + .detach(); + } +} diff --git a/src/app/github_pane.rs b/src/app/github_pane.rs index 92e7f3f..0ad6453 100644 --- a/src/app/github_pane.rs +++ b/src/app/github_pane.rs @@ -75,7 +75,10 @@ impl Workspace { let Some(cwd) = self.gh_pane(pane).map(|p| p.cwd.clone()) else { return }; match ev { GhEvent::Toast { text, error } => self.toast(text.clone(), *error, cx), - GhEvent::AskClaude(prompt) => self.new_claude_with(cwd, vec![prompt.clone()], window, cx), + GhEvent::AskClaude(prompt) => match self.running_claude_in(&cwd, cx) { + Some(id) => self.send_to_claude(&id, prompt, window, cx), + None => self.new_claude_with(cwd, vec![prompt.clone()], Starter::User, window, cx), + }, GhEvent::Checkout(number) => { let Some(exe) = crate::github::cli::locate() else { return }; let number = *number; diff --git a/src/app/handoff.rs b/src/app/handoff.rs index 8d55983..1dbb78d 100644 --- a/src/app/handoff.rs +++ b/src/app/handoff.rs @@ -1,14 +1,14 @@ //! Hand-off: a running Claude session moves to the active account. Claude Code can't change the account of a running //! process, so the session compacts itself (the mod runs `/compact`), then its process is replaced by a new one that //! resumes the same conversation under the active account. The Claudiu session is the same record and keeps its shell -//! and cards; the old process ends. The left sidebar's warning only switches the account; the right sidebar offers -//! the hand-off for a session that runs under another one. +//! and cards; the old process ends. The record remembers its new account, so it starts there from then on. The right sidebar offers the hand-off for a session that +//! runs under another account than the active one. use super::*; use crate::claude::usage::Snapshot; +use crate::terminal::view::Handover; +use std::time::Instant; -/// Used share of a limit at which the left sidebar shows its notice. -pub const HIGH: f32 = 0.95; /// How long a compaction may take before the hand-off is given up. const TIMEOUT_SECS: i64 = 180; @@ -17,32 +17,11 @@ pub struct Handoff { pub asked: i64, /// Set once the mod reports a compaction after `asked`. pub compacted: bool, + /// The skeleton counts from here, across the restart. + pub since: Instant, } -/// The left sidebar notice: the active account is at `HIGH` of a limit. It only reports; the user picks any account. impl Workspace { - /// Derived on every render, so the notice stays until the use drops or the account changes. - pub fn switch_offer(&self) -> Option { - let t = crate::store::now(); - let active = self.store.active_account()?; - let peak = active.usage.peak(t); - if peak < HIGH { - return None; - } - // The reset shown belongs to the limit whose percentage is shown; none if that limit has no known reset. - let reset = [&active.usage.five_hour, &active.usage.seven_day] - .into_iter() - .flatten() - .filter(|l| l.resets_at.is_none_or(|r| r > t)) - .max_by(|a, b| a.utilization.unwrap_or(0.0).total_cmp(&b.utilization.unwrap_or(0.0))) - .and_then(|l| l.resets_at); - let mut text = format!("{} is at {:.0}% of a usage limit.", active.name(), peak * 100.0); - if let Some(r) = reset { - text.push_str(&format!(" It resets in {}.", crate::panels::widgets::countdown(r - t))); - } - Some(text) - } - /// The right sidebar offer: a running session that runs under another account than the active one. /// Returns the account it runs under, and the active account's name. pub fn session_away(&self, id: &str, cx: &App) -> Option<(String, String)> { @@ -79,8 +58,9 @@ impl Workspace { /// Confirmed: the session asks to compact, and its skeleton says it is handing over. pub fn start_handoff(&mut self, id: &str, cx: &mut Context) { let to_name = self.store.active_account().map_or_else(|| "the active account".into(), |a| a.name()); - self.handoffs.insert(id.into(), Handoff { asked: crate::store::now(), compacted: false }); - self.set_handover(id, Some(to_name), cx); + let since = Instant::now(); + self.handoffs.insert(id.into(), Handoff { asked: crate::store::now(), compacted: false, since }); + self.set_handover(id, Some(Handover { to: to_name, since }), cx); usage::send_ctl(&usage::ctl_file(id), "compact", serde_json::json!(true)); } @@ -98,18 +78,19 @@ impl Workspace { /// compacts is given up on. pub fn finish_handoffs(&mut self, window: &mut Window, cx: &mut Context) { let t = crate::store::now(); - let due: Vec<(Id, bool)> = self + let due: Vec<(Id, bool, Instant)> = self .handoffs .iter() - .filter_map(|(id, h)| if h.compacted { Some((id.clone(), true)) } else if t - h.asked > TIMEOUT_SECS { Some((id.clone(), false)) } else { None }) + .filter(|(_, h)| h.compacted || t - h.asked > TIMEOUT_SECS) + .map(|(id, h)| (id.clone(), h.compacted, h.since)) .collect(); - for (id, compacted) in due { + for (id, compacted, since) in due { self.handoffs.remove(&id); if !compacted { self.set_handover(&id, None, cx); self.toast("The hand-off was cancelled: the session did not compact.", true, cx); } else if self.is_running(&id, cx) { - self.restart_handed_off(&id, window, cx); + self.restart_handed_off(&id, since, window, cx); } else { self.set_handover(&id, None, cx); } @@ -118,17 +99,21 @@ impl Workspace { /// The old process ends and a new one resumes the same conversation. The shell and cards belong to the session, /// so they stay. - fn restart_handed_off(&mut self, id: &str, window: &mut Window, cx: &mut Context) { + fn restart_handed_off(&mut self, id: &str, since: Instant, window: &mut Window, cx: &mut Context) { + let to = self.store.active_account().map(|a| a.id.clone()); + if let Some(meta) = self.store.session_mut(id).and_then(|r| r.claude.as_mut()) { + meta.account = to; + } self.restart_session(id, window, cx); let to_name = self.store.active_account().map_or_else(|| "the active account".into(), |a| a.name()); - self.set_handover(id, Some(to_name), cx); + self.set_handover(id, Some(Handover { to: to_name, since }), cx); } /// The skeleton says "Handing over to …" while this is set; the new process clears it once its prompt is ready. - fn set_handover(&self, id: &str, label: Option, cx: &mut App) { + fn set_handover(&self, id: &str, handover: Option, cx: &mut App) { if let Some(view) = self.live_view(id) { view.update(cx, |v, cx| { - v.handover = label; + v.handover = handover; cx.notify(); }); } diff --git a/src/app/headless.rs b/src/app/headless.rs index b979cca..88c5a0a 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -63,7 +63,16 @@ fn run() { serve(&mut cx, take()); assert!(h.join().unwrap().unwrap_err().contains("No project or folder")); + // A first message of its own needs the user's yes: a closed dialog is a refusal, and nothing was started. let live_before = ws.read_with(&cx, |ws, _| ws.live.len()); + let h = ask(from_session.clone(), "start_code_session", json!({"folder": cwd.to_string_lossy(), "prompt": "do the thing"})); + serve(&mut cx, take()); + assert!(ws.read_with(&cx, |ws, _| matches!(ws.modal, Some(Modal::Confirm { act: Act::ConfirmStartSession(_), .. }))), "the user was not asked"); + step(&mut cx, &|ws, w, cx| ws.act(Act::Dismiss, w, cx)); + step(&mut cx, &|ws, w, cx| ws.serve_requests(vec![], w, cx)); + assert_eq!(h.join().unwrap().unwrap_err(), "The user declined."); + assert_eq!(ws.read_with(&cx, |ws, _| ws.live.len()), live_before, "a declined request started a session"); + let h = ask(from_session.clone(), "start_code_session", json!({"folder": cwd.to_string_lossy()})); serve(&mut cx, take()); let text = h.join().unwrap().unwrap(); @@ -137,8 +146,131 @@ fn sessions_and_shell() { assert_eq!(ws.shells[&first].height, SHELL_MIN); ws.shell_drag = None; }); + // Editor mode: the shown session keeps its terminal and process, its folder is listed, and files open beside it. + std::fs::write(cwd.join("notes.md"), "# Notes\n").unwrap(); + std::fs::write(cwd.join("big.txt"), "let x = 1; // a line of ordinary code\n".repeat(crate::files::MAX_LINES)).unwrap(); + let wait = |cx: &mut TestAppContext, what: &str, done: &dyn Fn(&Workspace, &App) -> bool| { + let t = std::time::Instant::now(); + while !ws.read_with(cx, |ws, app| done(ws, app)) { + assert!(t.elapsed() < Duration::from_secs(20), "{what} never happened"); + // Timers (find in files waits for typing to pause) only fire as the test clock moves. + cx.executor().advance_clock(Duration::from_millis(50)); + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + } + }; + let term = ws.read_with(&cx, |ws, _| ws.live_view(&first).unwrap().entity_id()); + let (live, sidebars) = ws.read_with(&cx, |ws, _| (ws.live.len(), (ws.store.data.layout.sidebar_visible, ws.store.data.layout.right_hidden))); + step(&mut cx, &|ws, w, cx| ws.toggle_editor(w, cx)); + wait(&mut cx, "listing the folder", &|ws, _| ws.panes.get(&first).is_some_and(|p| p.nodes.iter().any(|n| n.name == "notes.md"))); + assert!(ws.read_with(&cx, |ws, app| ws.editor_mode + && ws.live.len() == live + && ws.live_view(&first).unwrap().entity_id() == term + && ws.is_running(&first, app)), "the terminal keeps running in editor mode"); + step(&mut cx, &|ws, w, cx| ws.open_file(&first, cwd.join("notes.md"), None, w, cx)); + wait(&mut cx, "opening a file", &|ws, _| ws.panes[&first].shown().is_some()); + // The keyboard moves to the opened file, inside the pane, so the pane's shortcuts (Ctrl+P) reach it. + cx.update_window(window, |_, window, app| { + let pane = &ws.read(app).panes[&first]; + assert!(pane.shown().unwrap().buffer.read(app).focus_handle(app).is_focused(window) && pane.focus.contains_focused(window, app)); + }) + .unwrap(); + assert_eq!(ws.read_with(&cx, |ws, app| ws.panes[&first].shown().unwrap().buffer.read(app).value().to_string()), "# Notes\n"); + let t = std::time::Instant::now(); + step(&mut cx, &|ws, w, cx| ws.open_file(&first, cwd.join("big.txt"), None, w, cx)); + wait(&mut cx, "opening a large file", &|ws, _| ws.panes[&first].shown().is_some_and(|t| t.path.ends_with("big.txt"))); + eprintln!("a {}-line file opened and drew in {:?}", crate::files::MAX_LINES, t.elapsed()); + assert!(ws.read_with(&cx, |ws, _| ws.panes[&first].shown().unwrap().note.is_none()), "a file at the line limit opens"); + // Quick open finds a file by name; find in files finds a line and opens the file there. + let typed = |cx: &mut TestAppContext, kind: crate::app::picker::PickerKind, text: &'static str| { + step(cx, &|ws, w, cx| { + ws.open_picker(kind, w, cx); + let input = ws.panes[&first].picker.as_ref().unwrap().input.clone(); + input.update(cx, |i, cx| i.set_value(text, w, cx)); + ws.update_picker(&first, cx); + }); + }; + typed(&mut cx, crate::app::picker::PickerKind::Files, "notmd"); + wait(&mut cx, "quick open", &|ws, _| ws.panes[&first].picker.as_ref().is_some_and(|p| !p.hits.is_empty())); + assert_eq!(ws.read_with(&cx, |ws, _| ws.panes[&first].picker.as_ref().unwrap().hits[0].text.clone()), "notes.md"); + step(&mut cx, &|ws, w, cx| ws.choose_picked(w, cx)); + wait(&mut cx, "opening the picked file", &|ws, _| ws.panes[&first].shown().is_some_and(|t| t.path.ends_with("notes.md"))); + assert!(ws.read_with(&cx, |ws, _| ws.panes[&first].picker.is_none()), "choosing closes the picker"); + std::fs::write(cwd.join("code.rs"), "fn a() {}\nfn needle() {}\n").unwrap(); + step(&mut cx, &|ws, _w, cx| ws.refresh_files(cx)); + wait(&mut cx, "listing the new file", &|ws, _| ws.panes[&first].nodes.iter().any(|n| n.name == "code.rs")); + typed(&mut cx, crate::app::picker::PickerKind::Text, "NEEDLE"); + wait(&mut cx, "find in files", &|ws, _| ws.panes[&first].picker.as_ref().is_some_and(|p| !p.hits.is_empty())); + assert_eq!(ws.read_with(&cx, |ws, _| ws.panes[&first].picker.as_ref().unwrap().hits[0].line), 1); + step(&mut cx, &|ws, w, cx| ws.choose_picked(w, cx)); + wait(&mut cx, "opening the found file", &|ws, _| ws.panes[&first].shown().is_some_and(|t| t.path.ends_with("code.rs"))); + assert_eq!(ws.read_with(&cx, |ws, app| ws.panes[&first].shown().unwrap().buffer.read(app).cursor_position().line), 1, "the cursor is on the found line"); + // Each file opened has a tab; opening one again shows its tab, and closing a tab shows its neighbour. + let tabs = |ws: &Workspace| ws.panes[&first].tabs.iter().map(|t| t.path.file_name().unwrap().to_string_lossy().to_string()).collect::>(); + assert_eq!(ws.read_with(&cx, |ws, _| tabs(ws)), ["notes.md", "big.txt", "code.rs"]); + step(&mut cx, &|ws, w, cx| ws.open_file(&first, cwd.join("notes.md"), None, w, cx)); + assert!(ws.read_with(&cx, |ws, _| ws.panes[&first].tabs.len() == 3 && ws.panes[&first].active == Some(0)), "reopening shows the open tab"); + step(&mut cx, &|ws, _w, cx| ws.close_tab(&first, 0, cx)); + assert_eq!(ws.read_with(&cx, |ws, _| (tabs(ws), ws.panes[&first].active)), (vec!["big.txt".to_string(), "code.rs".into()], Some(0))); + // Editing: an edit marks the tab, saving writes it; a change on disk reloads a clean tab, and with unsaved edits it + // becomes a conflict that never overwrites either side until the user picks. + let code = cwd.join("code.rs"); + let buffer = |ws: &Workspace| ws.panes[&first].shown().unwrap().buffer.clone(); + let shown_tab = |ws: &Workspace, f: &dyn Fn(&crate::app::Tab) -> bool| ws.panes[&first].shown().is_some_and(f); + step(&mut cx, &|ws, w, cx| ws.open_file(&first, code.clone(), None, w, cx)); + step(&mut cx, &|ws, w, cx| buffer(ws).update(cx, |b, cx| b.replace_all("fn mine() {}\n", w, cx))); + assert!(ws.read_with(&cx, |ws, _| shown_tab(ws, &|t| t.dirty)), "an edit marks the tab"); + step(&mut cx, &|ws, _w, cx| ws.save_shown(cx)); + wait(&mut cx, "saving", &|ws, _| shown_tab(ws, &|t| !t.dirty)); + assert_eq!(std::fs::read_to_string(&code).unwrap(), "fn mine() {}\n"); + std::fs::write(&code, "fn by_claude() {}\n// a longer file than before\n").unwrap(); + wait(&mut cx, "reloading a clean tab", &|ws, app| { + ws.panes[&first].shown().unwrap().buffer.read(app).value().starts_with("fn by_claude") + }); + step(&mut cx, &|ws, w, cx| buffer(ws).update(cx, |b, cx| b.replace_all("fn unsaved() {}\n", w, cx))); + std::fs::write(&code, "fn by_claude_again() {}\n").unwrap(); + wait(&mut cx, "the conflict", &|ws, _| shown_tab(ws, &|t| t.conflict == Some(crate::app::editing::Conflict::Changed))); + assert_eq!(ws.read_with(&cx, |ws, app| buffer(ws).read(app).value().to_string()), "fn unsaved() {}\n", "unsaved edits stay"); + step(&mut cx, &|ws, _w, cx| ws.save_shown(cx)); + wait(&mut cx, "the refused save", &|ws, _| ws.toast.as_ref().is_some_and(|t| t.text.starts_with("Not saved"))); + assert_eq!(std::fs::read_to_string(&code).unwrap(), "fn by_claude_again() {}\n", "Claude's change is not overwritten"); + step(&mut cx, &|ws, _w, cx| ws.keep_mine(&first, &code, cx)); + step(&mut cx, &|ws, _w, cx| ws.save_shown(cx)); + wait(&mut cx, "saving over the change", &|ws, _| shown_tab(ws, &|t| !t.dirty && t.stamp.is_some())); + assert_eq!(std::fs::read_to_string(&code).unwrap(), "fn unsaved() {}\n", "keeping mine and saving writes mine"); + // Unsaved edits are never dropped without asking: closing the tab, or ending its session, asks first. + step(&mut cx, &|ws, w, cx| buffer(ws).update(cx, |b, cx| b.replace_all("fn later() {}\n", w, cx))); + step(&mut cx, &|ws, w, cx| { + let ix = ws.panes[&first].active.unwrap(); + ws.request_close_tab(&first, ix, w, cx); + }); + assert!(ws.read_with(&cx, |ws, _| matches!(ws.modal, Some(Modal::Confirm { act: Act::DiscardTab(..), .. })) && ws.panes[&first].tabs.len() == 2), "closing a dirty tab asks"); + step(&mut cx, &|ws, w, cx| ws.act(Act::Dismiss, w, cx)); + step(&mut cx, &|ws, w, cx| ws.act(Act::CloseLive(first.clone()), w, cx)); + assert!(ws.read_with(&cx, |ws, _| matches!(ws.modal, Some(Modal::Confirm { act: Act::ConfirmCloseLive(_), .. })) && ws.live_view(&first).is_some()), "ending the session asks"); + step(&mut cx, &|ws, w, cx| ws.act(Act::Dismiss, w, cx)); + assert_eq!(std::fs::read_to_string(&code).unwrap(), "fn unsaved() {}\n", "nothing was saved by asking"); + // Claude Code first asks whether to trust this new folder. That is a menu, where a pasted line break could pick an + // answer, so moving there with lines selected puts nothing in (`selection_reference` covers Claude's input box). + cx.update_window(window, |_, window, _| window.activate_window()).unwrap(); + step(&mut cx, &|ws, w, cx| buffer(ws).update(cx, |b, cx| { + b.focus(w, cx); + b.select_all(w, cx); + })); + step(&mut cx, &|ws, w, cx| ws.focus_active(w, cx)); + assert!(ws.read_with(&cx, |ws, app| !ws.live_view(&first).unwrap().read(app).tail_text(40).contains("@code.rs"))); + step(&mut cx, &|ws, w, cx| ws.toggle_editor(w, cx)); + assert!(ws.read_with(&cx, |ws, _| !ws.editor_mode && (ws.store.data.layout.sidebar_visible, ws.store.data.layout.right_hidden) == sidebars), "leaving editor mode brings the sidebars back as they were"); + // Asking for a sidebar in editor mode leaves it and shows that sidebar, even one that was hidden before. + step(&mut cx, &|ws, w, cx| { + ws.store.data.layout.sidebar_visible = false; + ws.toggle_editor(w, cx); + ws.toggle_left(cx); + }); + assert!(ws.read_with(&cx, |ws, _| !ws.editor_mode && ws.store.data.layout.sidebar_visible), "the sidebar shows"); step(&mut cx, &|ws, w, cx| ws.close_live(&first, w, cx)); assert!(ws.read_with(&cx, |ws, _| !ws.shells.contains_key(&first)), "closing the session drops its shell"); + assert!(ws.read_with(&cx, |ws, _| !ws.panes.contains_key(&first)), "closing the session drops its editor pane"); // The GitHub view lives in the right sidebar: one per folder, it widens the sidebar, "Ask Claude" starts a session. assert_eq!(ws.read_with(&cx, |ws, _| ws.right_width(1600.0)), RIGHT_MENU_W, "the menu starts at its default width"); // Both sidebars can be dragged; the menu and the GitHub view each remember their own width. @@ -199,6 +331,11 @@ fn sessions_and_shell() { assert!(ws.read_with(&cx, |ws, _| !ws.store.data.layout.right_hidden), "shown again"); step(&mut cx, &|ws, w, cx| ws.open_github(cwd.clone(), w, cx)); assert!(ws.read_with(&cx, |ws, _| ws.gh.len() == 1), "one github pane per folder"); + // A running Claude session in the folder takes the request itself, so close the leftovers to see a new one start. + let leftovers: Vec = ws.read_with(&cx, |ws, _| ws.live.iter().map(|l| l.id.clone()).collect()); + for id in leftovers { + step(&mut cx, &|ws, w, cx| ws.close_live(&id, w, cx)); + } let before = ws.read_with(&cx, |ws, _| ws.live.len()); step(&mut cx, &|ws, _w, cx| { let view = ws.gh[0].view.clone(); @@ -244,3 +381,390 @@ fn starting_sessions_does_not_hang_or_panic() { } } } + +/// Editor mode with a real rust-analyzer: diagnostics arrive, hover and go-to-definition answer, and a language whose +/// server isn't installed says so. Uses `rust-analyzer` from `CLAUDIU_TEST_RUST_ANALYZER_DIR` (prepended to PATH), +/// else PATH. `cargo test -- --ignored language_servers`. +fn language_servers_with_rust_analyzer() { + use std::cell::RefCell; + use std::rc::Rc; + let data = tempfile::tempdir().unwrap(); + // SAFETY: set before any other thread reads the environment; this test owns the process. + unsafe { + std::env::set_var("CLAUDIU_DATA_DIR", data.path()); + if let Some(dir) = std::env::var_os("CLAUDIU_TEST_RUST_ANALYZER_DIR") { + let mut paths = vec![PathBuf::from(dir)]; + paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())); + std::env::set_var("PATH", std::env::join_paths(paths).unwrap()); + } + } + let work = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(work.path()).unwrap(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write(root.join("Cargo.toml"), "[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2021\"\n").unwrap(); + let code = "fn helper() -> u32 {\n 1\n}\n\nfn main() {\n let n: u32 = helper();\n let s: u32 = \"not a number\";\n}\n"; + std::fs::write(root.join("src/main.rs"), code).unwrap(); + std::fs::write(root.join("probe.gleam"), "pub fn main() { 1 }\n").unwrap(); + + let mut cx = TestAppContext::single(); + cx.update(|app| { + gpui_kit::init(app); + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, app); + }); + let (window, ws) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| Workspace::new(window, vec![], cx)))) + .unwrap(); + let draw = |cx: &mut TestAppContext| { + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + }; + let act = |cx: &mut TestAppContext, f: &dyn Fn(&mut Workspace, &mut Window, &mut Context)| { + cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| f(ws, window, cx))).unwrap(); + draw(cx); + }; + let wait = |cx: &mut TestAppContext, what: &str, secs: u64, done: &dyn Fn(&Workspace, &App) -> bool| { + let t = std::time::Instant::now(); + while !ws.read_with(cx, |ws, app| done(ws, app)) { + assert!(t.elapsed() < Duration::from_secs(secs), "{what} never happened: {:?}", ws.read_with(cx, |ws, _| ws.active.clone().and_then(|id| ws.server_status(&id)))); + std::thread::sleep(Duration::from_millis(100)); + cx.executor().advance_clock(Duration::from_millis(100)); + draw(cx); + } + }; + act(&mut cx, &|ws, w, cx| ws.new_claude(root.clone(), w, cx)); + let id = ws.read_with(&cx, |ws, _| ws.active.clone().unwrap()); + act(&mut cx, &|ws, w, cx| ws.toggle_editor(w, cx)); + wait(&mut cx, "the editor pane", 20, &|ws, _| ws.panes.contains_key(&id)); + + act(&mut cx, &|ws, w, cx| ws.open_file(&id, root.join("probe.gleam"), None, w, cx)); + wait(&mut cx, "gleam's status", 20, &|ws, _| ws.server_status(&id).is_some_and(|s| !s.contains("starting"))); + if crate::platform::find_executable("gleam").is_none() { + assert_eq!(ws.read_with(&cx, |ws, _| ws.server_status(&id)).unwrap(), "gleam isn't installed, so this file has no diagnostics or hover."); + } + + // TypeScript's server comes with the compiler from npm (a `.cmd` on Windows), and is asked for its diagnostics. + std::fs::write(root.join("probe.ts"), "export function f() { + const n: number = \"x\"; + return n; +} +").unwrap(); + act(&mut cx, &|ws, w, cx| ws.open_file(&id, root.join("probe.ts"), None, w, cx)); + wait(&mut cx, "typescript's status", 20, &|ws, _| ws.server_status(&id).is_some_and(|s| !s.contains("starting"))); + if crate::platform::find_executable("tsc").is_none() { + assert_eq!(ws.read_with(&cx, |ws, _| ws.server_status(&id)).unwrap(), "tsc isn't installed, so this file has no diagnostics or hover."); + } else { + assert_eq!(ws.read_with(&cx, |ws, _| ws.server_status(&id)).as_deref(), Some("tsc")); + let ts = ws.read_with(&cx, |ws, _| ws.panes[&id].shown().unwrap().buffer.clone()); + wait(&mut cx, "a TypeScript diagnostic", 60, &|_, app| ts.read(app).diagnostics().is_some_and(|d| d.iter().any(|e| e.message.contains("not assignable")))); + } + + act(&mut cx, &|ws, w, cx| ws.open_file(&id, root.join("src/main.rs"), None, w, cx)); + wait(&mut cx, "rust-analyzer starting", 60, &|ws, _| ws.server_status(&id).is_some_and(|s| s == "rust-analyzer")); + let buffer = ws.read_with(&cx, |ws, _| ws.panes[&id].shown().unwrap().buffer.clone()); + wait(&mut cx, "a diagnostic", 240, &|_, app| { + let messages: Vec = buffer.read(app).diagnostics().map(|d| d.iter().map(|e| e.message.to_string()).collect()).unwrap_or_default(); + messages.iter().any(|m| m.contains("u32")) + }); + + // Ask the editor's own providers, as a hover and an F12 would. + let at = code.find("helper();").unwrap() + 2; + let hover: Rc>> = Default::default(); + let found: Rc>> = Default::default(); + cx.update_window(window, |_, window, app| { + let (lsp_hover, lsp_def, text) = { + let b = buffer.read(app); + (b.lsp().hover_provider.clone().unwrap(), b.lsp().definition_provider.clone().unwrap(), b.text().clone()) + }; + let (h, d) = (lsp_hover.hover(&text, at, window, app), lsp_def.definitions(&text, at, window, app)); + let (hover, found) = (hover.clone(), found.clone()); + app.spawn(async move |_| { + let h = h.await.unwrap().map(|h| format!("{:?}", h.contents)); + *hover.borrow_mut() = Some(h.unwrap_or_default()); + *found.borrow_mut() = d.await.unwrap().first().map(|l| l.target_selection_range.start.line); + }) + .detach(); + }) + .unwrap(); + wait(&mut cx, "hover and definition", 60, &|_, _| found.borrow().is_some()); + assert!(hover.borrow().as_deref().is_some_and(|h| h.contains("fn helper")), "hover: {:?}", hover.borrow()); + assert_eq!(*found.borrow(), Some(0), "helper is defined on the first line"); + + // Ending the session ends its servers with it. + act(&mut cx, &|ws, w, cx| ws.close_live(&id, w, cx)); + assert!(ws.read_with(&cx, |ws, _| !ws.panes.contains_key(&id))); +} + +#[test] +#[ignore] +fn language_servers() { + let t = std::thread::spawn(language_servers_with_rust_analyzer); + let start = std::time::Instant::now(); + while !t.is_finished() { + assert!(start.elapsed() < Duration::from_secs(300), "the workspace froze"); + std::thread::sleep(Duration::from_millis(100)); + } + t.join().unwrap(); +} + +/// Lines selected in the editor go into Claude's input as `@file#L..` when the keyboard moves to Claude, and come back +/// out when it leaves without typing. Runs the real `claude` in this repository, which Claude Code already trusts (a +/// new folder stops at its trust and import questions), on a file under `target`. `cargo test -- --ignored selection_reference`. +fn selection_reference_in_claudes_input() { + let data = tempfile::tempdir().unwrap(); + // SAFETY: set before any other thread reads the environment; this test owns the process. + unsafe { std::env::set_var("CLAUDIU_DATA_DIR", data.path()) }; + let root = dunce::canonicalize(env!("CARGO_MANIFEST_DIR")).unwrap(); + let work = tempfile::tempdir_in(root.join("target")).unwrap(); + let code = work.path().join("code.rs"); + std::fs::write(&code, "fn a() {} +fn b() {} +fn c() {} +").unwrap(); + let mention = format!("@{}#L2", crate::app::picker::relative(&dunce::canonicalize(&code).unwrap(), &root)); + + let mut cx = TestAppContext::single(); + cx.update(|app| { + gpui_kit::init(app); + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, app); + }); + let (window, ws) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| Workspace::new(window, vec![], cx)))) + .unwrap(); + // Focus changes are only reported in an active window. + cx.update_window(window, |_, window, _| window.activate_window()).unwrap(); + let draw = |cx: &mut TestAppContext| { + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + }; + let act = |cx: &mut TestAppContext, f: &dyn Fn(&mut Workspace, &mut Window, &mut Context)| { + cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| f(ws, window, cx))).unwrap(); + draw(cx); + }; + let wait = |cx: &mut TestAppContext, what: &str, done: &dyn Fn(&Workspace, &App) -> bool| { + let t = std::time::Instant::now(); + while !ws.read_with(cx, |ws, app| done(ws, app)) { + assert!(t.elapsed() < Duration::from_secs(60), "{what} never happened"); + std::thread::sleep(Duration::from_millis(100)); + draw(cx); + } + }; + act(&mut cx, &|ws, w, cx| ws.new_claude(root.clone(), w, cx)); + let id = ws.read_with(&cx, |ws, _| ws.active.clone().unwrap()); + let screen = |ws: &Workspace, app: &App| ws.live_view(&id).unwrap().read(app).tail_text(40); + wait(&mut cx, "Claude's input box", &|ws, app| screen(ws, app).contains('❯') && !ws.live_view(&id).unwrap().read(app).loading); + act(&mut cx, &|ws, w, cx| ws.toggle_editor(w, cx)); + wait(&mut cx, "the editor pane", &|ws, _| ws.panes.contains_key(&id)); + act(&mut cx, &|ws, w, cx| ws.open_file(&id, dunce::canonicalize(&code).unwrap(), None, w, cx)); + wait(&mut cx, "opening the file", &|ws, _| ws.panes[&id].shown().is_some()); + let buffer = ws.read_with(&cx, |ws, _| ws.panes[&id].shown().unwrap().buffer.clone()); + act(&mut cx, &|_, w, cx| buffer.update(cx, |b, cx| { + b.focus(w, cx); + b.set_selected_range(10..20, cx); + })); + + act(&mut cx, &|ws, w, cx| ws.focus_active(w, cx)); + wait(&mut cx, "the reference in Claude's input", &|ws, app| screen(ws, app).contains(&mention)); + act(&mut cx, &|_, w, cx| buffer.update(cx, |b, cx| b.focus(w, cx))); + wait(&mut cx, "the untouched reference taken back", &|ws, app| !screen(ws, app).contains(&mention)); + + // Typed after: it stays, and coming back with the same lines selected doesn't add it again. + act(&mut cx, &|ws, w, cx| ws.focus_active(w, cx)); + wait(&mut cx, "the reference again", &|ws, app| screen(ws, app).contains(&mention)); + act(&mut cx, &|ws, _w, cx| ws.live_view(&id).unwrap().update(cx, |v, cx| v.paste_text("explain", cx))); + wait(&mut cx, "the typed request", &|ws, app| screen(ws, app).contains("explain")); + act(&mut cx, &|_, w, cx| buffer.update(cx, |b, cx| b.focus(w, cx))); + act(&mut cx, &|ws, w, cx| ws.focus_active(w, cx)); + std::thread::sleep(Duration::from_secs(1)); + draw(&mut cx); + assert_eq!(ws.read_with(&cx, |ws, app| screen(ws, app).matches(&mention).count()), 1, "kept once: {}", ws.read_with(&cx, |ws, app| screen(ws, app))); + + // After text the user typed first, the reference follows it on the same line. + act(&mut cx, &|_, w, cx| buffer.update(cx, |b, cx| { + b.focus(w, cx); + b.set_selected_range(0..20, cx); + })); + act(&mut cx, &|ws, w, cx| ws.focus_active(w, cx)); + let both = format!("@{}#L1-2", crate::app::picker::relative(&dunce::canonicalize(&code).unwrap(), &root)); + wait(&mut cx, "the second reference", &|ws, app| screen(ws, app).contains(&both)); + let lines = ws.read_with(&cx, |ws, app| screen(ws, app)); + // After the user's text, on the same line with a space: the user starts a new line themselves when they want one. + // Words only: Claude Code wraps a long input line onto the next row, padding the row it leaves. + let words = lines.split_whitespace().collect::>().join(" "); + assert!(words.contains(&format!("explain {both}:")), "after the typed text: {lines}"); + act(&mut cx, &|ws, w, cx| ws.close_live(&id, w, cx)); +} + +#[test] +#[ignore] +fn selection_reference() { + let t = std::thread::spawn(selection_reference_in_claudes_input); + let start = std::time::Instant::now(); + while !t.is_finished() { + assert!(start.elapsed() < Duration::from_secs(180), "the workspace froze"); + std::thread::sleep(Duration::from_millis(100)); + } + t.join().unwrap(); +} + +/// Creating, renaming and deleting from the file tree, with open tabs following along. Runs the real `claude` in a new +/// temporary folder (not under `target`, which Git ignores, so the tree would list nothing); it waits at the folder +/// trust question, which is enough for the editor. +/// `cargo test -- --ignored file_operations`. +fn file_operations_in_the_tree() { + let data = tempfile::tempdir().unwrap(); + // SAFETY: set before any other thread reads the environment; this test owns the process. + unsafe { std::env::set_var("CLAUDIU_DATA_DIR", data.path()) }; + let work = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(work.path()).unwrap(); + std::fs::write(root.join("code.rs"), "fn a() {} +").unwrap(); + std::fs::create_dir(root.join("sub")).unwrap(); + std::fs::write(root.join("sub/inner.rs"), "fn b() {} +").unwrap(); + + let mut cx = TestAppContext::single(); + cx.update(|app| { + gpui_kit::init(app); + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, app); + }); + let (window, ws) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| Workspace::new(window, vec![], cx)))) + .unwrap(); + let draw = |cx: &mut TestAppContext| { + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + }; + let act = |cx: &mut TestAppContext, f: &dyn Fn(&mut Workspace, &mut Window, &mut Context)| { + cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| f(ws, window, cx))).unwrap(); + draw(cx); + }; + let wait = |cx: &mut TestAppContext, what: &str, done: &dyn Fn(&Workspace, &App) -> bool| { + let t = std::time::Instant::now(); + while !ws.read_with(cx, |ws, app| done(ws, app)) { + assert!(t.elapsed() < Duration::from_secs(60), "{what} never happened"); + std::thread::sleep(Duration::from_millis(100)); + draw(cx); + } + }; + let name = |cx: &mut TestAppContext, purpose: NameFor, name: &'static str| -> Result<(), String> { + let id = ws.read_with(cx, |ws, _| ws.active.clone().unwrap()); + let out = std::cell::RefCell::new(Ok(())); + act(cx, &|ws, w, cx| *out.borrow_mut() = ws.apply_file_name(&id, &purpose, name, w, cx)); + out.into_inner() + }; + let shown = |ws: &Workspace, id: &Id| ws.panes[id].shown().map(|t| t.path.clone()); + + act(&mut cx, &|ws, w, cx| ws.new_claude(root.clone(), w, cx)); + let id = ws.read_with(&cx, |ws, _| ws.active.clone().unwrap()); + wait(&mut cx, "the session running", &|ws, app| ws.is_running(&id, app)); + act(&mut cx, &|ws, w, cx| ws.toggle_editor(w, cx)); + wait(&mut cx, "the files listed", &|ws, _| ws.panes.get(&id).is_some_and(|p| !p.nodes.is_empty())); + + // A new file opens in the editor; a bad or taken name is refused and nothing is written. + name(&mut cx, NameFor::FileIn(root.join("sub")), "made.rs").unwrap(); + wait(&mut cx, "the new file open", &|ws, _| shown(ws, &id) == Some(root.join("sub/made.rs"))); + assert!(name(&mut cx, NameFor::FileIn(root.clone()), "a/b.rs").is_err()); + assert!(name(&mut cx, NameFor::FileIn(root.clone()), "code.rs").is_err()); + assert_eq!(std::fs::read_to_string(root.join("code.rs")).unwrap(), "fn a() {} +"); + + // A new folder shows in the tree; a taken name is refused. + name(&mut cx, NameFor::FolderIn(root.join("sub")), "deeper").unwrap(); + assert!(root.join("sub/deeper").is_dir()); + wait(&mut cx, "the new folder listed", &|ws, _| ws.panes[&id].nodes.iter().filter(|n| n.path == root.join("sub")).flat_map(|n| n.children.iter().flatten()).any(|n| n.path == root.join("sub/deeper"))); + assert!(name(&mut cx, NameFor::FolderIn(root.join("sub")), "deeper").is_err()); + + // A rename keeps the tab; one that changes the language reopens it. + act(&mut cx, &|ws, w, cx| ws.open_file(&id, root.join("code.rs"), None, w, cx)); + wait(&mut cx, "code.rs open", &|ws, _| shown(ws, &id) == Some(root.join("code.rs"))); + name(&mut cx, NameFor::Rename(root.join("code.rs")), "renamed.rs").unwrap(); + wait(&mut cx, "the tab following the rename", &|ws, _| shown(ws, &id) == Some(root.join("renamed.rs"))); + name(&mut cx, NameFor::Rename(root.join("renamed.rs")), "renamed.txt").unwrap(); + wait(&mut cx, "the tab reopened as text", &|ws, _| { + ws.panes[&id].shown().is_some_and(|t| t.path == root.join("renamed.txt") && t.language.is_none()) + }); + assert_eq!(ws.read_with(&cx, |ws, _| ws.panes[&id].tabs.iter().filter(|t| t.path.ends_with("renamed.txt")).count()), 1); + + // Renaming a folder takes its open tabs along. + act(&mut cx, &|ws, w, cx| ws.open_file(&id, root.join("sub/inner.rs"), None, w, cx)); + wait(&mut cx, "inner.rs open", &|ws, _| shown(ws, &id) == Some(root.join("sub/inner.rs"))); + name(&mut cx, NameFor::Rename(root.join("sub")), "moved").unwrap(); + wait(&mut cx, "the tab following the folder", &|ws, _| shown(ws, &id) == Some(root.join("moved/inner.rs"))); + + // Deleting a folder closes the tabs inside it. + act(&mut cx, &|ws, _w, cx| ws.delete_path(id.clone(), root.join("moved"), cx)); + wait(&mut cx, "the folder's tabs closed", &|ws, _| ws.panes[&id].tabs.iter().all(|t| !t.path.starts_with(root.join("moved")))); + assert!(!root.join("moved").exists()); + assert!(root.join("renamed.txt").exists(), "only the folder went"); + act(&mut cx, &|ws, w, cx| ws.close_live(&id, w, cx)); +} + +#[test] +#[ignore] +fn file_operations() { + let t = std::thread::spawn(file_operations_in_the_tree); + let start = std::time::Instant::now(); + while !t.is_finished() { + assert!(start.elapsed() < Duration::from_secs(180), "the workspace froze"); + std::thread::sleep(Duration::from_millis(100)); + } + t.join().unwrap(); +} + +/// A changed file in a repository gets marks in the editor's gutter (see `panels::editor_pane::change_marks`). +#[test] +#[ignore] +fn git_change_marks_are_painted() { + let data = tempfile::tempdir().unwrap(); + unsafe { std::env::set_var("CLAUDIU_DATA_DIR", data.path()) }; + let work = tempfile::tempdir().unwrap(); + let cwd = dunce::canonicalize(work.path()).unwrap(); + let repo = git2::Repository::init(&cwd).unwrap(); + std::fs::create_dir_all(cwd.join("src")).unwrap(); + let file = cwd.join("src").join("a.txt"); + std::fs::write(&file, "one\ntwo\nthree\nfour\n").unwrap(); + { + let mut index = repo.index().unwrap(); + index.add_all(["*"], git2::IndexAddOption::DEFAULT, None).unwrap(); + index.write().unwrap(); + let tree = repo.find_tree(index.write_tree().unwrap()).unwrap(); + let sig = git2::Signature::now("t", "t@t").unwrap(); + repo.commit(Some("HEAD"), &sig, &sig, "c", &tree, &[]).unwrap(); + } + std::fs::write(&file, "one\nTWO\nthree\nfour\nfive\n").unwrap(); + let mut cx = TestAppContext::single(); + cx.update(|app| { + gpui_kit::init(app); + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, app); + }); + let (window, ws) = cx.update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| Workspace::new(window, vec![], cx)))).unwrap(); + let draw = |cx: &mut TestAppContext| { + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + }; + let step = |cx: &mut TestAppContext, f: &dyn Fn(&mut Workspace, &mut Window, &mut Context)| { + cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| f(ws, window, cx))).unwrap(); + draw(cx); + draw(cx); + }; + draw(&mut cx); + step(&mut cx, &|ws, w, cx| ws.new_claude(cwd.clone(), w, cx)); + let id = ws.read_with(&cx, |ws, _| ws.active.clone().unwrap()); + step(&mut cx, &|ws, w, cx| ws.toggle_editor(w, cx)); + step(&mut cx, &|ws, w, cx| ws.open_file(&id, file.clone(), None, w, cx)); + for _ in 0..100 { + cx.executor().advance_clock(Duration::from_millis(50)); + draw(&mut cx); + std::thread::sleep(Duration::from_millis(50)); + } + // Each change is painted as a bar at the editor's left edge, above everything the editor drew. + let (marks, bars) = cx + .update_window(window, |_, window, app| { + let marks = ws.read(app).panes[&id].shown().unwrap().marks.clone(); + let bars: Vec<_> = window.painted_quads().into_iter().filter(|q| q.bounds.size.width.0 < 8.0 && q.bounds.size.height.0 > 8.0).collect(); + (marks, bars) + }) + .unwrap(); + assert_eq!(marks.len(), 2, "{marks:?}"); + assert_eq!(bars.len(), 2, "one bar for the changed line and one for the added line"); +} diff --git a/src/app/ingest.rs b/src/app/ingest.rs index 9cae81d..046055c 100644 --- a/src/app/ingest.rs +++ b/src/app/ingest.rs @@ -114,6 +114,11 @@ fn apply_to_meta(meta: &mut ClaudeMeta, snap: &Snapshot) -> bool { meta.auto_compact = snap.auto_compact; changed = true; } + // `None` is real too: Claude Code lists the row only while its feature flag is on. + if meta.precompute_compact != snap.precompute_compact { + meta.precompute_compact = snap.precompute_compact; + changed = true; + } if meta.compact_at != snap.compact_at { meta.compact_at = snap.compact_at; changed = true; @@ -144,4 +149,15 @@ mod tests { assert!(apply_to_meta(&mut meta, &later), "advisor off is a real change"); assert_eq!((meta.context_tokens, meta.auto_compact, meta.advisor.clone()), (Some(500), Some(true), None)); } + + #[test] + fn background_compaction_is_offered_only_while_the_mod_reports_it() { + let mut meta = ClaudeMeta::default(); + let offered = snap(r#"{"session_id":"s","five_hour":null,"seven_day":null,"context_fraction":null,"context_tokens":null,"context_window":null,"model":null,"captured_at":1,"precompute_compact":true}"#); + assert!(apply_to_meta(&mut meta, &offered)); + assert_eq!(meta.precompute_compact, Some(true)); + let withdrawn = snap(r#"{"session_id":"s","five_hour":null,"seven_day":null,"context_fraction":null,"context_tokens":null,"context_window":null,"model":null,"captured_at":2}"#); + assert!(apply_to_meta(&mut meta, &withdrawn), "Claude Code stopped listing the row: the switch goes away"); + assert_eq!(meta.precompute_compact, None); + } } diff --git a/src/app/language_servers.rs b/src/app/language_servers.rs new file mode 100644 index 0000000..5cfb675 --- /dev/null +++ b/src/app/language_servers.rs @@ -0,0 +1,290 @@ +//! Language servers for editor mode: one per kind (see `lsp::KINDS`) per session, started when the first file of its +//! language opens and ended with the session. A missing or stopped server is shown, never installed or restarted. + +use std::path::Path; +use std::rc::Rc; + +use futures::StreamExt; +use gpui_kit::component::input::{DefinitionProvider, HoverProvider, Rope, RopeExt}; +use lsp_types::notification::{DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument}; +use lsp_types::request::{GotoDefinition, HoverRequest}; +use lsp_types::{GotoDefinitionResponse, LocationLink, TextDocumentIdentifier, TextDocumentPositionParams, Uri}; + +use super::*; +use crate::lsp::{self, Event, Server}; +use crate::platform::path_key; + +/// Edits are sent to the server once typing pauses this long. +const SYNC_DELAY: Duration = Duration::from_millis(300); + +pub enum ServerState { + Starting, + Ready(Rc), + /// Not found on PATH. + Missing, + /// Failed to start or stopped on its own, with why. + Stopped(String), +} + +impl Workspace { + /// Hand a newly opened tab to its language's server, starting the server on first use. + pub(super) fn attach_server(&mut self, id: &Id, path: &Path, cx: &mut Context) { + let Some(pane) = self.panes.get_mut(id) else { return }; + let Some(kind) = pane.tabs.iter().find(|t| t.path == path).and_then(|t| t.language).and_then(lsp::kind_for) else { return }; + match pane.servers.get(kind.program) { + Some(ServerState::Ready(server)) => { + let server = server.clone(); + self.open_in_server(id, path, &server, cx); + } + Some(_) => {} + None => { + pane.servers.insert(kind.program, ServerState::Starting); + self.start_server(id, kind, cx); + } + } + } + + fn start_server(&mut self, id: &Id, kind: &'static lsp::Kind, cx: &mut Context) { + let Some(root) = self.store.session(id).map(|s| s.cwd.clone()) else { return }; + let (events, mut incoming) = futures::channel::mpsc::unbounded(); + let id = id.clone(); + cx.spawn(async move |this, cx| { + let started = cx + .background_executor() + .spawn(async move { + let program = crate::platform::find_executable(kind.program).ok_or(None)?; + Server::start(kind, &program, &root, events).map_err(Some) + }) + .await; + let ready = this.update(cx, |ws, cx| { + let Some(pane) = ws.panes.get_mut(&id) else { return false }; + let state = match started { + Ok(server) => ServerState::Ready(Rc::new(server)), + Err(None) => ServerState::Missing, + Err(Some(why)) => ServerState::Stopped(why), + }; + let ready = matches!(state, ServerState::Ready(_)); + pane.servers.insert(kind.program, state); + if let Some(ServerState::Ready(server)) = pane.servers.get(kind.program) { + let server = server.clone(); + let paths: Vec = pane.tabs.iter().filter(|t| t.language.and_then(lsp::kind_for).is_some_and(|k| k.program == kind.program)).map(|t| t.path.clone()).collect(); + for path in paths { + ws.open_in_server(&id, &path, &server, cx); + } + } + cx.notify(); + ready + }); + if !matches!(ready, Ok(true)) { + return; + } + while let Some(event) = incoming.next().await { + if this.update(cx, |ws, cx| ws.on_server_event(&id, kind.program, event, cx)).is_err() { + break; + } + } + }) + .detach(); + } + + fn on_server_event(&mut self, id: &Id, program: &'static str, event: Event, cx: &mut Context) { + let Some(pane) = self.panes.get_mut(id) else { return }; + match event { + Event::Diagnostics(path, diagnostics) => { + let key = path_key(&path); + if let Some(tab) = pane.tabs.iter().find(|t| path_key(&t.path) == key) { + show_diagnostics(tab, diagnostics, cx); + } + } + Event::Exited(why) => { + let why = if why.is_empty() { "it exited".to_string() } else { why }; + pane.servers.insert(program, ServerState::Stopped(why)); + cx.notify(); + } + } + } + + /// Tell the server about an open tab, and let the tab ask it for hover and definitions. + fn open_in_server(&mut self, id: &Id, path: &Path, server: &Rc, cx: &mut Context) { + let ws = cx.entity().downgrade(); + let Some(tab) = self.panes.get_mut(id).and_then(|p| p.tabs.iter_mut().find(|t| t.path == path)) else { return }; + let (Some(uri), Some(language)) = (lsp::uri(path), tab.language) else { return }; + let text = tab.buffer.read(cx).value().to_string(); + server.notify::(lsp_types::DidOpenTextDocumentParams { + text_document: lsp_types::TextDocumentItem::new(uri.clone(), lsp::language_id(language).into(), tab.version, text), + }); + tab.server = Some(server.clone()); + let doc = Rc::new(Document { server: server.clone(), uri }); + let (owner, current) = (id.clone(), path.to_path_buf()); + tab.buffer.update(cx, |b, _| { + let lsp = b.lsp_mut(); + lsp.hover_provider = Some(doc.clone()); + lsp.definition_provider = Some(doc); + // A definition in another file opens that file's tab; one in this file is a plain jump. + lsp.show_document = Some(Rc::new(move |params, window, cx| { + let Some(target) = lsp::path_of(¶ms.uri).filter(|t| path_key(t) != path_key(¤t)) else { return false }; + // In the tree's form (a server may write `c:` for `C:`), so an open tab of the file is found by its path. + let target = dunce::canonicalize(&target).unwrap_or(target); + let line = params.selection.map(|r| r.start.line as usize); + let (ws, owner) = (ws.clone(), owner.clone()); + // Deferred: the editor asking is still being updated, and opening may update it again. + window.defer(cx, move |window, cx| { + let _ = ws.update(cx, |ws, cx| ws.open_file(&owner, target, line, window, cx)); + }); + true + })); + }); + self.pull_diagnostics(id, path, cx); + } + + /// The tab's text changed: send it to the server once typing pauses (`immediately` for reloads). + pub(super) fn sync_with_server(&mut self, id: &Id, path: &Path, immediately: bool, cx: &mut Context) { + let Some(tab) = self.panes.get_mut(id).and_then(|p| p.tabs.iter_mut().find(|t| t.path == path)) else { return }; + if tab.server.is_none() { + return; + } + tab.version += 1; + let version = tab.version; + let (id, path) = (id.clone(), path.to_path_buf()); + cx.spawn(async move |this, cx| { + if !immediately { + cx.background_executor().timer(SYNC_DELAY).await; + } + let _ = this.update(cx, |ws, cx| { + let Some(tab) = ws.panes.get(&id).and_then(|p| p.tabs.iter().find(|t| t.path == path)) else { return }; + // A later edit has its own pending send. + let (Some(server), Some(uri), true) = (&tab.server, lsp::uri(&path), tab.version == version) else { return }; + server.notify::(lsp_types::DidChangeTextDocumentParams { + text_document: lsp_types::VersionedTextDocumentIdentifier::new(uri, version), + content_changes: vec![lsp_types::TextDocumentContentChangeEvent { range: None, range_length: None, text: tab.buffer.read(cx).value().to_string() }], + }); + ws.pull_diagnostics(&id, &path, cx); + }); + }) + .detach(); + } + + /// Ask a server that doesn't send diagnostics for the tab's (see `lsp::Kind::pull_diagnostics`). + fn pull_diagnostics(&self, id: &Id, path: &Path, cx: &mut Context) { + let Some(tab) = self.panes.get(id).and_then(|p| p.tabs.iter().find(|t| t.path == path)) else { return }; + let (Some(server), Some(uri)) = (tab.server.as_ref().filter(|s| s.pulls_diagnostics()), lsp::uri(path)) else { return }; + let (reply, version) = (server.diagnostics(&uri), tab.version); + let (id, path) = (id.clone(), path.to_path_buf()); + cx.spawn(async move |this, cx| { + let Ok(Some(diagnostics)) = reply.await else { return }; + let _ = this.update(cx, |ws, cx| { + // A later edit asks again; this answer is about older text. + let Some(tab) = ws.panes.get(&id).and_then(|p| p.tabs.iter().find(|t| t.path == path)).filter(|t| t.version == version) else { return }; + show_diagnostics(tab, diagnostics, cx); + }); + }) + .detach(); + } + + pub(super) fn tell_server_saved(&self, id: &Id, path: &Path) { + let Some(tab) = self.panes.get(id).and_then(|p| p.tabs.iter().find(|t| t.path == path)) else { return }; + if let (Some(server), Some(uri)) = (&tab.server, lsp::uri(path)) { + server.notify::(lsp_types::DidSaveTextDocumentParams { text_document: TextDocumentIdentifier::new(uri), text: None }); + } + } + + pub(super) fn tell_server_closed(tab: &Tab) { + if let (Some(server), Some(uri)) = (&tab.server, lsp::uri(&tab.path)) { + server.notify::(lsp_types::DidCloseTextDocumentParams { text_document: TextDocumentIdentifier::new(uri) }); + } + } + + /// One line about the shown tab's server, when its language has one. + pub fn server_status(&self, id: &Id) -> Option { + let pane = self.panes.get(id)?; + let kind = pane.shown()?.language.and_then(lsp::kind_for)?; + let name = kind.program; + Some(match pane.servers.get(name)? { + ServerState::Starting => format!("{name} is starting…"), + ServerState::Ready(_) => name.to_string(), + ServerState::Missing => format!("{name} isn't installed, so this file has no diagnostics or hover."), + ServerState::Stopped(why) => format!("{name} stopped: {why}"), + }) + } +} + +fn show_diagnostics(tab: &Tab, mut diagnostics: Vec, cx: &mut App) { + let utf16 = tab.server.as_ref().is_some_and(|s| s.counts_utf16()); + tab.buffer.update(cx, |b, cx| { + let text = b.text().clone(); + if utf16 { + for d in &mut diagnostics { + d.range = range_in_chars(&text, d.range); + } + } + if let Some(set) = b.diagnostics_mut() { + set.reset(&text); + set.extend(diagnostics); + } + cx.notify(); + }); +} + +/// One open file as the editor's hover and definition provider. +struct Document { + server: Rc, + uri: Uri, +} + +impl Document { + fn at(&self, text: &Rope, offset: usize) -> TextDocumentPositionParams { + let mut at = text.offset_to_position(offset); + if self.server.counts_utf16() { + at.character = lsp::chars_to_utf16(&line_of(text, at.line), at.character); + } + TextDocumentPositionParams::new(TextDocumentIdentifier::new(self.uri.clone()), at) + } +} + +fn line_of(text: &Rope, line: u32) -> String { + text.slice_line(line as usize).to_string() +} + +/// A server's UTF-16 range in `text` with its columns in characters, as the editor counts them. +fn range_in_chars(text: &Rope, range: lsp_types::Range) -> lsp_types::Range { + let at = |p: lsp_types::Position| lsp_types::Position::new(p.line, lsp::utf16_to_chars(&line_of(text, p.line), p.character)); + lsp_types::Range::new(at(range.start), at(range.end)) +} + +impl HoverProvider for Document { + fn hover(&self, text: &Rope, offset: usize, _: &mut Window, cx: &mut App) -> gpui::Task>> { + let reply = self.server.request::(lsp_types::HoverParams { text_document_position_params: self.at(text, offset), work_done_progress_params: Default::default() }); + cx.background_spawn(async move { reply.await.map_err(anyhow::Error::msg) }) + } +} + +impl DefinitionProvider for Document { + fn definitions(&self, text: &Rope, offset: usize, _: &mut Window, cx: &mut App) -> gpui::Task>> { + let reply = self.server.request::(lsp_types::GotoDefinitionParams { + text_document_position_params: self.at(text, offset), + work_done_progress_params: Default::default(), + partial_result_params: Default::default(), + }); + // A jump within this file lands by column; one into another file opens it at its line only. + let (utf16, uri, text) = (self.server.counts_utf16(), self.uri.clone(), text.clone()); + cx.background_spawn(async move { + let mut links = links(reply.await.map_err(anyhow::Error::msg)?); + for link in links.iter_mut().filter(|l| utf16 && l.target_uri == uri) { + link.target_range = range_in_chars(&text, link.target_range); + link.target_selection_range = range_in_chars(&text, link.target_selection_range); + } + Ok(links) + }) + } +} + +/// Servers answer with locations or links; the editor takes links. +fn links(reply: Option) -> Vec { + let link = |l: lsp_types::Location| LocationLink { origin_selection_range: None, target_uri: l.uri, target_range: l.range, target_selection_range: l.range }; + match reply { + None => vec![], + Some(GotoDefinitionResponse::Scalar(l)) => vec![link(l)], + Some(GotoDefinitionResponse::Array(ls)) => ls.into_iter().map(link).collect(), + Some(GotoDefinitionResponse::Link(ls)) => ls, + } +} diff --git a/src/app/layout.rs b/src/app/layout.rs index 07efb03..d644c1c 100644 --- a/src/app/layout.rs +++ b/src/app/layout.rs @@ -77,9 +77,21 @@ impl Workspace { self.store.mark_dirty(); } + /// In editor mode the sidebar is hidden whatever the remembered setting, so asking for it leaves editor mode and shows it. + pub fn toggle_left(&mut self, cx: &mut Context) { + let editing = self.editing(); + let layout = &mut self.store.data.layout; + layout.sidebar_visible = editing || !layout.sidebar_visible; + self.editor_mode = false; + self.store.mark_dirty(); + cx.notify(); + } + pub fn toggle_right(&mut self, window: &mut Window, cx: &mut Context) { + let editing = self.editing(); let layout = &mut self.store.data.layout; - layout.right_hidden = !layout.right_hidden; + layout.right_hidden = !editing && !layout.right_hidden; + self.editor_mode = false; self.store.mark_dirty(); self.focus_active(window, cx); cx.notify(); diff --git a/src/app/lifecycle.rs b/src/app/lifecycle.rs index 95336d3..582fa56 100644 --- a/src/app/lifecycle.rs +++ b/src/app/lifecycle.rs @@ -16,6 +16,7 @@ pub fn tidy_leftovers() { datadir::prune(names, 7 * 86_400); datadir::prune(attached, 7 * 86_400); datadir::prune(mcp_configs, 7 * 86_400); + datadir::prune(crate::claude::trim::settings_dir(), 7 * 86_400); // Titles are copied into the store on the next tick, so an old file is only a duplicate. datadir::prune(titles, 7 * 86_400); datadir::prune(usage::snapshot_dir(), 30 * 86_400); @@ -41,17 +42,25 @@ impl Workspace { v.is_running() && v.is_working() && self.store.session(&l.id).is_some_and(|r| r.kind == SessionKind::Claude) }); let working = working.count(); - if working == 0 { + let unsaved = self.unsaved(None); + if working == 0 && unsaved == 0 { self.finalize(cx); return true; } - self.modal = Some(Modal::Confirm { - title: "Quit Claudiu?".into(), - body: format!( + let mut body = Vec::new(); + if working > 0 { + body.push(format!( "{working} Claude session{} still working. Quitting interrupts {} — sessions stay in your history and can be resumed.", if working == 1 { " is" } else { "s are" }, if working == 1 { "it" } else { "them" } - ), + )); + } + if unsaved > 0 { + body.push(format!("{unsaved} file{} in the editor {} unsaved changes that will be lost.", super::editing::plural(unsaved), if unsaved == 1 { "has" } else { "have" })); + } + self.modal = Some(Modal::Confirm { + title: "Quit Claudiu?".into(), + body: body.join(" "), confirm: "Quit anyway".into(), danger: true, act: Act::ConfirmQuit, diff --git a/src/app/links.rs b/src/app/links.rs index 1f8c0bd..2c9ffe2 100644 --- a/src/app/links.rs +++ b/src/app/links.rs @@ -17,7 +17,7 @@ impl Workspace { } /// Run `f` on the attached items of a session; true when it changed anything. - fn edit_attached(&mut self, id: &str, f: impl FnOnce(&mut Vec) -> bool) -> bool { + pub(super) fn edit_attached(&mut self, id: &str, f: impl FnOnce(&mut Vec) -> bool) -> bool { self.store.session_mut(id).and_then(|s| s.claude.as_mut()).is_some_and(|meta| f(&mut meta.attached)) } @@ -86,16 +86,23 @@ fn remove_id(list: &mut Vec, id: &str) -> bool { list.len() != before } +/// What GitHub says about an attached item. True when the title or state differs from what is kept. +pub(super) fn set_status(list: &mut [Attached], pull: bool, number: u32, title: &str, state: crate::github::model::State) -> bool { + let Some(have) = list.iter_mut().find(|a| a.pull == pull && a.number == number) else { return false }; + if have.title.as_deref() == Some(title) && have.state == Some(state) { + return false; + } + have.title = Some(title.to_string()); + have.state = Some(state); + true +} + /// Most items one session keeps; the oldest go first. const MAX_ATTACHED: usize = 20; -/// Add an attached item unless it is there already (a later title fills in a missing one). True when anything changed. +/// Add an attached item unless it is there already. True when anything changed. pub(super) fn attach(list: &mut Vec, item: Attached) -> bool { - if let Some(have) = list.iter_mut().find(|a| a.pull == item.pull && a.number == item.number) { - if have.title.is_none() && item.title.is_some() { - have.title = item.title; - return true; - } + if list.iter().any(|a| a.pull == item.pull && a.number == item.number) { return false; } list.push(item); @@ -117,26 +124,37 @@ mod attach_tests { assert_eq!(l, ["b"]); } - fn item(pull: bool, number: u32, title: Option<&str>) -> Attached { - Attached { pull, number, title: title.map(String::from) } + fn item(pull: bool, number: u32) -> Attached { + Attached { pull, number, title: None, state: None } } #[test] - fn an_item_is_attached_once_and_may_gain_a_title() { + fn an_item_is_attached_once() { let mut list = vec![]; - assert!(attach(&mut list, item(false, 5, None))); - assert!(!attach(&mut list, item(false, 5, None)), "same item again"); - assert!(attach(&mut list, item(true, 5, None)), "a pull request is not the issue with that number"); - assert!(attach(&mut list, item(false, 5, Some("Fix it"))), "title filled in"); - assert!(!attach(&mut list, item(false, 5, Some("Other"))), "an existing title stays"); - assert_eq!(list, [item(false, 5, Some("Fix it")), item(true, 5, None)]); + assert!(attach(&mut list, item(false, 5))); + assert!(!attach(&mut list, item(false, 5)), "same item again"); + assert!(attach(&mut list, item(true, 5)), "a pull request is not the issue with that number"); + assert_eq!(list, [item(false, 5), item(true, 5)]); + } + + #[test] + fn github_status_updates_only_what_changed() { + use crate::github::model::State; + let mut list = vec![item(false, 5)]; + assert!(set_status(&mut list, false, 5, "Fix it", State::Open)); + assert!(!set_status(&mut list, false, 5, "Fix it", State::Open), "same answer again"); + assert!(set_status(&mut list, false, 5, "Fix it properly", State::Open), "renamed on GitHub"); + assert!(set_status(&mut list, false, 5, "Fix it properly", State::Closed), "closed on GitHub"); + assert!(!set_status(&mut list, true, 5, "Other", State::Open), "no such pull request attached"); + assert_eq!(list[0].title.as_deref(), Some("Fix it properly")); + assert_eq!(list[0].state, Some(State::Closed)); } #[test] fn the_oldest_items_drop_off() { let mut list = vec![]; for n in 1..=(MAX_ATTACHED as u32 + 3) { - attach(&mut list, item(false, n, None)); + attach(&mut list, item(false, n)); } assert_eq!(list.len(), MAX_ATTACHED); assert_eq!(list[0].number, 4); diff --git a/src/app/mod.rs b/src/app/mod.rs index dda6e8c..30968dc 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1,6 +1,7 @@ //! Workspace: the app's state, the `Act` table that menus, shortcuts and clicks all go through, and `new`. The methods -//! are split by topic: `sessions` (start, show, close), `background` (timers and polls), `layout` (panels), `modal` (toasts, -//! menus, modals), `repo` (git), `github_pane`, `alt_accounts`. Rendering lives in `panels/`. +//! are split by topic: `sessions` (start, show, close), `background` (timers and polls), `layout` (panels), +//! `editor_mode` (files and editor beside the terminal), `modal` (toasts, menus, modals), `repo` (git), `github_pane`, +//! `alt_accounts`. Rendering lives in `panels/`. use std::collections::{HashMap, HashSet}; use std::path::PathBuf; @@ -16,6 +17,7 @@ use crate::claude::accounts; use crate::claude; use crate::panels::sidebar::{SIDEBAR_MAX, SIDEBAR_MIN, SIDEBAR_W}; use crate::github::view::{GhEvent, GithubView}; +use crate::claude::defaults::{Effort, PermissionMode, Starter}; use crate::claude::mcp; use crate::platform::{self, Editor}; use crate::{claude::usage, datadir}; @@ -27,22 +29,39 @@ use crate::terminal::view::{TerminalEvent, TerminalView}; use crate::updater::UpdateState; mod alt_accounts; +mod attached_sync; +mod config_sync; +mod ask_claude; mod background; mod cross; +pub mod editing; +mod editor_mode; mod github_pane; mod handoff; #[cfg(test)] mod headless; mod ingest; +mod file_ops; mod layout; +mod language_servers; mod lifecycle; mod links; mod modal; +mod navigation; +pub mod picker; mod repo; +mod selection_reference; mod sessions; +mod settings; mod titles; mod visuals; +pub use editor_mode::{EditorPane, Tab, register_languages}; +pub use ask_claude::Ask; +pub use editor_mode::EditorCommand; +pub use file_ops::NameFor; +pub use settings::SettingsPage; + actions!( claudiu, [ @@ -62,9 +81,24 @@ actions!( HideOthers, ShowAllApps, OpenSettings, + ToggleEditor, + QuickOpen, + SaveFile, + AskExplain, + AskFix, + AskTests, + AskFixProblem, + GoToLine, + GoBack, + GoForward, ] ); +/// Ctrl+1 to Ctrl+9 (Cmd on macOS): show the running session with that number, counted down the sidebar's RUNNING list. +#[derive(Clone, Debug, PartialEq, gpui::Action)] +#[action(namespace = claudiu, no_json)] +pub struct ShowSession(pub usize); + /// Every user-triggerable operation, so buttons, menus and shortcuts share one code path. #[derive(Clone, Debug)] pub enum Act { @@ -73,10 +107,16 @@ pub enum Act { }, /// Show or hide the shell under a Claude session's terminal (started on first use, in the session's folder). ToggleShell(Id), + /// Turn editor mode on or off for the shown session (see `editor_mode.rs`). + ToggleEditor, /// Click on a session row: live -> show it, history -> resume it. Select(Id), Resume(Id), CloseLive(Id), + /// End the session although its editor has unsaved files (the user confirmed). + ConfirmCloseLive(Id), + /// Close an editor tab and drop its unsaved edits (the user confirmed). + DiscardTab(Id, PathBuf), Rename(Id), /// Hide (true) or restore (false) a session in the sidebar. Archived sessions still turn up in search. Archive(Id, bool), @@ -85,6 +125,10 @@ pub enum Act { OpenEditor(Editor, PathBuf), ImportProject, OpenSettings, + /// A choice in the Settings dialog's effort or permission-mode picker (None = Claude Code's default); kept in the + /// dialog until Save. + PickEffort(Option), + PickPermission(Option), /// The project's GitHub issues and pull requests. OpenGithub { cwd: PathBuf, @@ -93,6 +137,7 @@ pub enum Act { RegenTitle(Id), /// Change a setting of a running session through its mod (see `usage::send_ctl`). SetAutoCompact(Id, bool), + SetPrecomputeCompact(Id, bool), SetAdvisor(Id, String), /// Turn Claude in Chrome on or off; the session restarts to apply it. SetChrome(Id, bool), @@ -121,6 +166,8 @@ pub enum Act { /// The shown session runs under another account: restart it under the active one (asks first, see `handoff.rs`). Handoff, ConfirmHandoff(Id), + /// A session's request to open another one with a first message, by request id (see `cross.rs`). + ConfirmStartSession(String), /// Shows the sharing warning, then `ConfirmAddAccount`. AddAccount, ConfirmAddAccount, @@ -128,6 +175,12 @@ pub enum Act { SignIn(Id), RemoveAccount(Id), ConfirmRemoveAccount(Id), + /// Editor mode's file tree: ask for a file name (new or renamed), ask before deleting, delete. + AskFileName(Id, NameFor), + AskDelete(Id, PathBuf), + ConfirmDelete(Id, PathBuf), + /// An entry of the editor's right-click menu. + Editor(EditorCommand), } impl MenuItem { @@ -166,6 +219,15 @@ pub enum Modal { id: Id, input: Entity, }, + FileName { + id: Id, + purpose: NameFor, + input: Entity, + }, + GoToLine { + id: Id, + input: Entity, + }, NewBranch { cwd: PathBuf, input: Entity, @@ -178,8 +240,19 @@ pub enum Modal { Settings { shell: Entity, claude: Entity, + /// Model for new sessions (Sessions page); empty = Claude Code's default. + model: Entity, + effort: Option, + permission: Option, updates: bool, + chrome: bool, scale: u32, + /// Claude Code features and tools turned off (Claude Code tools page). + trimmed: Vec, + /// Claudiu tools turned off (Claudiu tools page). + claudiu_off: Vec, + /// Focus of the category list, which has the keyboard when the dialog opens. + list_focus: FocusHandle, }, } @@ -210,6 +283,7 @@ pub struct Live { pub id: Id, pub view: Entity, pub _sub: Subscription, + pub _focus: [Subscription; 2], /// The session name Claude Code was last given (`--name` or `/rename`), so a changed title is sent once. pub claude_name: Option, /// When Claude last called the title tool. A later call (e.g. after `/clear`, which starts a nameless @@ -301,6 +375,10 @@ pub struct Workspace { /// Shells under Claude sessions, by the session they belong to. pub shells: HashMap, pub shell_drag: Option, + /// Editor mode is on: the sidebars give way to the shown session's files and editor. Not remembered across restarts. + pub editor_mode: bool, + /// Each session's files and editor, by the session they belong to. + pub panes: HashMap, /// The shell panel's animated height (0 while hidden). pub shell_h: crate::panels::widgets::Reveal, /// Open sessions in the order they were last shown (most recent last); closing one goes back to the previous. @@ -310,8 +388,14 @@ pub struct Workspace { pub search: String, pub search_input: Entity, pub root_focus: FocusHandle, + /// Set when an Ask Claude request moves the keyboard to the terminal, so that arrival doesn't also put the editor's + /// selection into Claude's input (`selection_reference`). + pub(crate) skip_selection_reference: bool, pub modal: Option, pub modal_focus: FocusHandle, + /// The Settings category last shown. Kept here because opening Settings builds the modal anew; not saved to disk. + pub settings_page: SettingsPage, + /// Whether this run already said it couldn't write a session's tool settings file (said at most once). pub menu: Option, pub toast: Option, pub toast_serial: u64, @@ -330,10 +414,20 @@ pub struct Workspace { /// Pointer position at the last drag-over check, see `pointer_moved`. /// Sidebar reorder animation: last drawn order of the running rows, and the slides in flight. pub prev_current: Vec, + /// Ctrl (Cmd on macOS) has been held a moment, so the running rows show their Ctrl+number shortcut. + pub shortcuts_shown: bool, + /// Bumped whenever the modifier keys change, so a pending reveal of the shortcuts is dropped. + pub shortcuts_wait: u64, pub slides: HashMap, pub slide_gen: u64, /// When a drag last reordered the sidebar, see `pointer_moved`. pub last_swap: std::time::Instant, + /// Attached issues and pull requests are asked about on GitHub from time to time, see `attached_sync.rs`. + pub attached_sync: attached_sync::Sync, + /// The shared Claude Code settings are kept equal across accounts, see `config_sync.rs`. + pub config_sync: config_sync::Runner, + /// Sessions asked to open another with a first message; each waits for the user's yes (`cross.rs`). + pub pending_starts: Vec, pub drag_pos: Option>, pub update: UpdateState, pub scanning: bool, @@ -347,6 +441,8 @@ pub struct Workspace { /// Sessions that are working or waiting for the user; absent = idle and already seen. pub activity: HashMap, pub git_busy: Option, + /// What Commit & Push would do in the shown session's folder, as last read; `None` until it has been. + pub pending: Option<(PathBuf, crate::git::commit::Pending)>, } impl Workspace { @@ -390,6 +486,8 @@ impl Workspace { active: None, shells: HashMap::new(), shell_drag: None, + editor_mode: false, + panes: HashMap::new(), shell_h: crate::panels::widgets::Reveal::at_value(0.0), recent: vec![], main: Main::Home, @@ -397,8 +495,10 @@ impl Workspace { search: String::new(), search_input, root_focus: cx.focus_handle(), + skip_selection_reference: false, modal: None, modal_focus: cx.focus_handle(), + settings_page: SettingsPage::default(), menu: None, toast: None, toast_serial: 0, @@ -414,9 +514,14 @@ impl Workspace { dragging: None, drag_pos: None, prev_current: Vec::new(), + shortcuts_shown: false, + shortcuts_wait: 0, slides: HashMap::new(), slide_gen: 0, last_swap: std::time::Instant::now(), + attached_sync: Default::default(), + config_sync: Default::default(), + pending_starts: vec![], update: UpdateState::default(), scanning: false, quitting: false, @@ -426,6 +531,7 @@ impl Workspace { restored: false, activity: HashMap::new(), git_busy: None, + pending: None, store, }; // Everything from a previous run is history until clicked. Keep the highlight only if it still exists. @@ -471,9 +577,21 @@ impl Workspace { match act { Act::NewClaude { cwd } => self.new_claude(cwd, window, cx), Act::ToggleShell(id) => self.toggle_shell(&id, window, cx), + Act::ToggleEditor => self.toggle_editor(window, cx), + Act::Editor(command) => self.run_editor_command(command, window, cx), Act::Select(id) => self.show_session(&id, window, cx), Act::Resume(id) => self.resume(&id, window, cx), - Act::CloseLive(id) => self.close_live(&id, window, cx), + Act::CloseLive(id) => self.request_close_live(&id, window, cx), + Act::ConfirmCloseLive(id) => { + self.modal = None; + self.close_live(&id, window, cx) + } + Act::DiscardTab(id, path) => { + self.modal = None; + if let Some(ix) = self.panes.get(&id).and_then(|p| p.tabs.iter().position(|t| t.path == path)) { + self.close_tab(&id, ix, cx); + } + } Act::Rename(id) => { let text = self .store @@ -510,7 +628,11 @@ impl Workspace { } } Act::ImportProject => self.import_project(window, cx), - Act::OpenGithub { cwd } => self.open_github(cwd, window, cx), + Act::OpenGithub { cwd } => { + // GitHub opens in the right sidebar, which editor mode hides. + self.editor_mode = false; + self.open_github(cwd, window, cx) + } Act::RegenTitle(id) => self.regen_title(&id, cx), Act::CommitPush(id, cwd) => { if self.is_running(&id, cx) { @@ -533,14 +655,20 @@ impl Workspace { } Act::FixGitWithClaude(cwd) => { let prompt = "Claudiu's Pull or Commit & Push just failed in this repository because of a merge conflict, a diverged branch or a rejected push. Run git status, fix it (resolve conflicts keeping the intent of both sides, finish the merge or rebase, then push if the push was rejected). Ask me whenever a conflict is ambiguous or you are unsure which side to keep."; - let args = ["--model", "claude-sonnet-5-5", "--effort", "medium"]; - let leading = std::iter::once(prompt).chain(args).map(String::from).collect(); - let before = self.selected.clone(); - self.new_claude_with(cwd, leading, window, cx); - if self.selected != before - && let Some(id) = self.selected.clone() { - self.ephemeral.insert(id); + match self.running_claude_in(&cwd, cx) { + Some(id) => self.send_to_claude(&id, prompt, window, cx), + None => { + // No session to ask: a short-lived one on a mid-sized model. + let args = ["--model", "claude-sonnet-5-5", "--effort", "medium"]; + let leading = std::iter::once(prompt).chain(args).map(String::from).collect(); + let before = self.selected.clone(); + self.new_claude_with(cwd, leading, Starter::FixGit, window, cx); + if self.selected != before + && let Some(id) = self.selected.clone() { + self.ephemeral.insert(id); + } } + } } Act::OpenSettings => { let s = &self.store.data.settings; @@ -549,10 +677,25 @@ impl Workspace { s.claude_path.as_ref().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default(), ); let updates = s.update_url.as_deref() != Some(""); + let chrome = s.chrome_default; let claude_hint = self.claude_exe.as_ref().map_or("not found".to_string(), |p| p.to_string_lossy().into_owned()); + let defaults = s.new_session.clone(); let claude = self.modal_input(&claude_t, &claude_hint, window, cx); + let model = self.modal_input(defaults.model.as_deref().unwrap_or_default(), "Claude Code default", window, cx); let shell = self.modal_input(&shell_t, &platform::default_shell(None).0, window, cx); - self.modal = Some(Modal::Settings { shell, claude, updates, scale: crate::panels::scale::percent() }); + let list_focus = cx.focus_handle(); + window.focus(&list_focus, cx); + self.modal = Some(Modal::Settings { shell, claude, model, effort: defaults.effort, permission: defaults.permission_mode, updates, chrome, scale: crate::panels::scale::percent(), trimmed: self.store.data.settings.trimmed_tools.clone(), claudiu_off: self.store.data.settings.claudiu_tools_off.clone(), list_focus }); + } + Act::PickEffort(choice) => { + if let Some(Modal::Settings { effort, .. }) = self.modal.as_mut() { + *effort = choice; + } + } + Act::PickPermission(choice) => { + if let Some(Modal::Settings { permission, .. }) = self.modal.as_mut() { + *permission = choice; + } } Act::NewBranch(cwd) => { let input = self.modal_input("", "", window, cx); @@ -583,6 +726,15 @@ impl Workspace { usage::send_ctl(&usage::ctl_file(&id), "auto_compact", on.into()); self.toast(format!("Turning auto-compact {}…", if on { "on" } else { "off" }), false, cx); } + Act::SetPrecomputeCompact(id, on) => { + if let Some(meta) = self.store.session_mut(&id).and_then(|s| s.claude.as_mut()) { + meta.precompute_compact = Some(on); + } + self.store.mark_dirty(); + cx.notify(); + usage::send_ctl(&usage::ctl_file(&id), "precompute_compact", on.into()); + self.toast(format!("Turning background compaction {}…", if on { "on" } else { "off" }), false, cx); + } Act::SetChrome(id, on) => { if let Some(meta) = self.store.session_mut(&id).and_then(|s| s.claude.as_mut()) { meta.chrome = on; @@ -678,6 +830,7 @@ impl Workspace { self.toast("Switched. New and resumed sessions use this account; running sessions keep theirs.", false, cx); } Act::Handoff => self.ask_handoff(window, cx), + Act::ConfirmStartSession(req_id) => self.confirm_start(&req_id, window, cx), Act::ConfirmHandoff(id) => { self.modal = None; self.start_handoff(&id, cx); @@ -687,9 +840,10 @@ impl Workspace { title: "Add an account?".into(), body: "Only sign in to accounts you own. Sharing or pooling logins, or using several accounts to get around \ usage limits, can break Anthropic's terms.\n\n\ - The new account shares your main Claude Code setup: settings, CLAUDE.md, agents, skills, plugins and \ - session history. Changes made while using it (like /model) change your main setup too. \ - Only the login is kept separate. Claudiu creates this account's folder; your main ~/.claude is not modified." + The new account uses your main Claude Code setup. Settings, CLAUDE.md, keybindings, MCP servers and project trust \\ + are kept the same in every account, both ways: a change made here (like /model) also changes ~/.claude and \\ + your other accounts, and the other way round. Agents, skills, plugins and session history are shared with \\ + ~/.claude. Only the login is separate. Claudiu creates this account's folder." .into(), confirm: "Add and sign in".into(), danger: false, @@ -724,6 +878,9 @@ impl Workspace { }); window.focus(&self.modal_focus, cx); } + Act::AskFileName(id, purpose) => self.ask_file_name(id, purpose, window, cx), + Act::AskDelete(id, path) => self.ask_delete(id, path, window, cx), + Act::ConfirmDelete(id, path) => self.delete_path(id, path, cx), Act::ConfirmRemoveAccount(id) => { self.modal = None; if let Some(dir) = self.store.account(&id).and_then(|a| a.dir.clone()) { diff --git a/src/app/modal.rs b/src/app/modal.rs index d3940f2..21db4d1 100644 --- a/src/app/modal.rs +++ b/src/app/modal.rs @@ -55,6 +55,24 @@ impl Workspace { } Act::Dismiss } + Some(Modal::FileName { id, purpose, input }) => { + let name = input.read(cx).value().trim().to_string(); + if let Err(why) = self.apply_file_name(&id, &purpose, &name, window, cx) { + self.modal = Some(Modal::FileName { id, purpose, input }); + self.toast(why, true, cx); + return; + } + Act::Dismiss + } + Some(Modal::GoToLine { id, input }) => { + let text = input.read(cx).value().to_string(); + if let Err(why) = self.go_to_line(&id, &text, window, cx) { + self.modal = Some(Modal::GoToLine { id, input }); + self.toast(why, true, cx); + return; + } + Act::Dismiss + } Some(Modal::Advisor { id, input }) => { let name = input.read(cx).value().trim().to_lowercase(); if name.is_empty() { @@ -73,15 +91,20 @@ impl Workspace { let name = input.read(cx).value().split_whitespace().collect::>().join("-"); if name.is_empty() { Act::Dismiss } else { Act::CreateBranch(cwd, name) } } - Some(Modal::Settings { shell, claude, updates, scale }) => { + Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, list_focus }) => { let clean = |s: &str| s.trim().trim_matches('"').to_string(); let (shell_t, claude_t) = (clean(shell.read(cx).value().as_ref()), clean(claude.read(cx).value().as_ref())); - let bad = [("Shell", &shell_t), ("Claude path", &claude_t)] + let model_name = claude::defaults::parse_model(model.read(cx).value().as_ref()); + // In category order, then top to bottom: the first bad field decides which page the dialog shows. + let paths = [("Shell", &shell, &shell_t), ("Claude path", &claude, &claude_t)] .into_iter() - .find(|(_, t)| !t.is_empty() && platform::resolve_program(t).is_none()); - if let Some((what, t)) = bad { - let msg = format!("{what}: “{t}” is not a file or a program on PATH"); - self.modal = Some(Modal::Settings { shell, claude, updates, scale }); + .find(|(_, _, t)| !t.is_empty() && platform::resolve_program(t).is_none()) + .map(|(what, field, t)| (SettingsPage::General, field.clone(), format!("{what}: “{t}” is not a file or a program on PATH"))); + let bad_model = model_name.is_err().then(|| (SettingsPage::Sessions, model.clone(), "Use a model alias or id (letters, digits, . _ -).".to_string())); + if let Some((page, field, msg)) = paths.or(bad_model) { + self.settings_page = page; + field.update(cx, |s, cx| s.focus(window, cx)); + self.modal = Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, list_focus }); self.toast(msg, true, cx); return; } @@ -93,11 +116,40 @@ impl Workspace { s.update_url = (!updates).then(String::new); } s.scale = (scale != 100).then_some(scale); + s.chrome_default = chrome; + s.new_session = claude::defaults::NewSessionDefaults { model: model_name.unwrap_or_default(), effort, permission_mode: permission }; + let trimmed = claude::trim::normalized(&trimmed); + let claudiu_off = mcp::normalized_features(&claudiu_off); + // The trims go into Claude Code's own settings.json (every account gets the file through config_sync). + // When that fails the old trims stay, so what the page shows is what Claude Code has. + let mut trim_error = None; + let mut trimmed = trimmed; + if s.trimmed_tools != trimmed { + let written = claude::claude_home() + .ok_or_else(|| std::io::Error::other("Claude Code's folder was not found")) + .and_then(|home| claude::trim::write_global(&home.join("settings.json"), &trimmed, &s.applied_trims)); + match written { + Ok(owned) => s.applied_trims = owned, + Err(e) => { + trim_error = Some(e); + trimmed = s.trimmed_tools.clone(); + } + } + } + let tools_changed = s.trimmed_tools != trimmed || s.claudiu_tools_off != claudiu_off; + s.trimmed_tools = trimmed; + s.claudiu_tools_off = claudiu_off; crate::panels::scale::set(scale); self.shell = platform::default_shell(s.shell.as_deref()); self.claude_exe = claude::discover(s.claude_path.as_deref()); self.store.mark_dirty(); - self.toast("Settings saved. Open sessions keep their current shell.", false, cx); + if let Some(e) = trim_error { + self.toast(format!("Settings saved, but Claude Code's settings.json could not be changed ({e}), so the tool trims stay as they were."), true, cx); + } else if tools_changed { + self.toast("Settings saved. Tool changes apply to new sessions; resumed sessions keep the old instructions until their next compaction.", false, cx); + } else { + self.toast("Settings saved. Open sessions keep their current shell.", false, cx); + } Act::Dismiss } None => return, diff --git a/src/app/navigation.rs b/src/app/navigation.rs new file mode 100644 index 0000000..f48047d --- /dev/null +++ b/src/app/navigation.rs @@ -0,0 +1,182 @@ +//! Moving around in editor mode: back and forward through the places the editor left, go to line, and the recently +//! shown files that quick open lists first. + +use std::path::Path; + +use gpui_kit::component::input::Position; + +use super::*; + +/// Most places kept for back and forward, and most recent files. +const KEPT: usize = 50; + +impl Workspace { + /// Leave a note of where the shown tab is before showing `to` (at `line`), for `go_back`. A new jump forgets the + /// way forward. Showing the tab that is already shown, without a line, goes nowhere. + pub(super) fn remember_place(&mut self, id: &Id, to: &Path, line: Option, cx: &App) { + let Some(pane) = self.panes.get_mut(id) else { return }; + let Some(here) = current_place(pane, cx) else { return }; + if here.0 == to && line.is_none() { + return; + } + push_kept(&mut pane.back, here); + pane.forward.clear(); + } + + /// Put `path` first among the recently shown files. + pub(super) fn note_recent(&mut self, id: &Id, path: &Path) { + if let Some(pane) = self.panes.get_mut(id) { + pane.recent.retain(|p| p != path); + pane.recent.insert(0, path.to_path_buf()); + pane.recent.truncate(KEPT); + } + } + + /// A file or folder was renamed: the places and recent files under it follow, so Back does not open a name that is gone. + pub(super) fn retarget_history(&mut self, id: &Id, from: &Path, to: &Path) { + let Some(pane) = self.panes.get_mut(id) else { return }; + for path in pane.back.iter_mut().chain(pane.forward.iter_mut()).map(|(p, _)| p).chain(pane.recent.iter_mut()) { + moved_path(path, from, to); + } + } + + /// A file or folder was deleted: nothing under it stays among the places and recent files. + pub(super) fn forget_history(&mut self, id: &Id, gone: &Path) { + let Some(pane) = self.panes.get_mut(id) else { return }; + forget(&mut pane.back, gone, |(p, _)| p); + forget(&mut pane.forward, gone, |(p, _)| p); + forget(&mut pane.recent, gone, |p| p); + } + + pub fn go_back(&mut self, window: &mut Window, cx: &mut Context) { + self.step_through_places(true, window, cx); + } + + pub fn go_forward(&mut self, window: &mut Window, cx: &mut Context) { + self.step_through_places(false, window, cx); + } + + fn step_through_places(&mut self, back: bool, window: &mut Window, cx: &mut Context) { + let Some(id) = self.active_id().filter(|_| self.editing()).cloned() else { return }; + let Some(pane) = self.panes.get_mut(&id) else { return }; + let here = current_place(pane, cx); + let (from, to) = if back { (&mut pane.back, &mut pane.forward) } else { (&mut pane.forward, &mut pane.back) }; + let Some((path, line)) = from.pop() else { return }; + if let Some(here) = here { + push_kept(to, here); + } + self.note_recent(&id, &path); + self.show_file(&id, path, Some(line as usize), window, cx); + } + + /// Ask for a line to put the cursor on in the shown tab. + pub fn ask_go_to_line(&mut self, window: &mut Window, cx: &mut Context) { + let Some(id) = self.active_id().filter(|_| self.editing()).cloned() else { return }; + if self.panes.get(&id).and_then(|p| p.shown()).is_none_or(|t| t.note.is_some()) { + return; + } + let input = self.modal_input("", "Line, or line:column", window, cx); + self.modal = Some(Modal::GoToLine { id, input }); + } + + /// Put the shown tab's cursor where `text` says; `Err` says why it can't, and the dialog stays open. + pub(super) fn go_to_line(&mut self, id: &Id, text: &str, window: &mut Window, cx: &mut Context) -> Result<(), String> { + let (line, column) = parse_line(text).ok_or("Type a line number, such as 42 or 42:7.")?; + let path = self.panes.get(id).and_then(|p| p.shown()).map(|t| t.path.clone()).ok_or("No file is shown.")?; + self.remember_place(id, &path, Some(line as usize), cx); + let Some(tab) = self.panes.get(id).and_then(|p| p.shown()) else { return Ok(()) }; + tab.buffer.update(cx, |b, cx| { + b.set_cursor_position(Position::new(line, column), window, cx); + b.focus(window, cx); + }); + Ok(()) + } +} + +/// The shown tab's file and cursor line. +fn current_place(pane: &EditorPane, cx: &App) -> Option<(PathBuf, u32)> { + let tab = pane.shown()?; + Some((tab.path.clone(), tab.buffer.read(cx).cursor_position().line)) +} + +/// `path` after `from` (itself or a folder above it) became `to`. +fn moved_path(path: &mut PathBuf, from: &Path, to: &Path) { + if path == from { + *path = to.to_path_buf(); + } else if let Ok(rest) = path.strip_prefix(from) { + *path = to.join(rest); + } +} + +fn forget(list: &mut Vec, gone: &Path, path_of: impl Fn(&T) -> &PathBuf) { + list.retain(|item| !crate::platform::is_same_or_under(path_of(item), gone)); +} + +fn push_kept(places: &mut Vec<(PathBuf, u32)>, place: (PathBuf, u32)) { + if places.last() != Some(&place) { + places.push(place); + } + if places.len() > KEPT { + places.remove(0); + } +} + +/// `42` or `42:7` (1-based, as people count) as a 0-based line and column. Past the end is fine: the editor clamps it. +fn parse_line(text: &str) -> Option<(u32, u32)> { + let (line, column) = text.trim().split_once(':').unwrap_or((text.trim(), "1")); + let (line, column): (u32, u32) = (line.trim().parse().ok()?, column.trim().parse().ok()?); + Some((line.checked_sub(1)?, column.saturating_sub(1))) +} + +#[cfg(test)] +mod tests { + use super::{forget, moved_path, parse_line, push_kept}; + use std::path::{Path, PathBuf}; + + #[test] + fn a_renamed_folder_takes_the_places_under_it_along() { + let (from, to) = (Path::new("/p/old"), Path::new("/p/new")); + let mut path = PathBuf::from("/p/old/src/a.rs"); + moved_path(&mut path, from, to); + assert_eq!(path, Path::new("/p/new/src/a.rs")); + let mut itself = PathBuf::from("/p/old"); + moved_path(&mut itself, from, to); + assert_eq!(itself, to, "the folder itself, without a trailing separator"); + let mut other = PathBuf::from("/p/older/a.rs"); + moved_path(&mut other, from, to); + assert_eq!(other, Path::new("/p/older/a.rs"), "a name that merely starts the same stays"); + } + + #[test] + fn a_deleted_file_or_folder_leaves_no_place_behind() { + let mut places = vec![(PathBuf::from("/p/a.rs"), 3), (PathBuf::from("/p/dir/b.rs"), 1), (PathBuf::from("/p/dir2/c.rs"), 2)]; + forget(&mut places, Path::new("/p/dir"), |(p, _)| p); + assert_eq!(places.iter().map(|(p, _)| p.to_str().unwrap()).collect::>(), ["/p/a.rs", "/p/dir2/c.rs"]); + let mut recent = vec![PathBuf::from("/p/a.rs")]; + forget(&mut recent, Path::new("/p/a.rs"), |p| p); + assert!(recent.is_empty()); + } + + #[test] + fn a_line_and_column_count_from_one() { + assert_eq!(parse_line("42"), Some((41, 0))); + assert_eq!(parse_line(" 42:7 "), Some((41, 6))); + assert_eq!(parse_line("1:0"), Some((0, 0)), "column 0 is taken as the first"); + assert_eq!(parse_line("0"), None, "there is no line 0"); + assert_eq!(parse_line("abc"), None); + assert_eq!(parse_line(""), None); + } + + #[test] + fn places_skip_repeats_and_keep_the_latest() { + let mut places = vec![]; + push_kept(&mut places, (PathBuf::from("a"), 1)); + push_kept(&mut places, (PathBuf::from("a"), 1)); + assert_eq!(places.len(), 1, "the same place twice in a row is one step"); + for line in 0..60 { + push_kept(&mut places, (PathBuf::from("b"), line)); + } + assert_eq!(places.len(), super::KEPT); + assert_eq!(places.last(), Some(&(PathBuf::from("b"), 59))); + } +} diff --git a/src/app/picker.rs b/src/app/picker.rs new file mode 100644 index 0000000..ad51a9d --- /dev/null +++ b/src/app/picker.rs @@ -0,0 +1,179 @@ +//! Quick open and find in files: a box over the editor that lists files (by name) or lines (by text) as the user types, +//! and opens the chosen one. Ranking and searching live in `files`; text search runs off the UI thread. + +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use gpui_kit::component::input::{InputEvent, InputState}; + +use super::*; +use crate::files::{self, Hit}; + +/// Most rows a picker lists. +const SHOWN: usize = 200; +/// Find in files waits this long after the last keystroke, so typing a word searches once. +const SEARCH_DELAY: Duration = Duration::from_millis(150); + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum PickerKind { + Files, + Text, +} + +pub struct Picker { + pub kind: PickerKind, + pub input: Entity, + pub hits: Vec, + pub selected: usize, + /// Bumped on every keystroke and when the picker goes, so an older search stops early and can't replace a newer + /// one's results. Shared with the search running off the UI thread. + generation: Arc, + _sub: Subscription, +} + +impl Drop for Picker { + fn drop(&mut self) { + self.generation.fetch_add(1, Ordering::Relaxed); + } +} + +impl Workspace { + /// Open quick open or find in files over the shown session's editor; asking for the one already up closes it. + pub fn open_picker(&mut self, kind: PickerKind, window: &mut Window, cx: &mut Context) { + let Some(id) = self.active_id().filter(|_| self.editing()).cloned() else { return }; + let Some(pane) = self.panes.get_mut(&id) else { return }; + if pane.picker.as_ref().is_some_and(|p| p.kind == kind) { + self.close_picker(window, cx); + return; + } + let placeholder = match kind { + PickerKind::Files => "Go to file", + PickerKind::Text => "Find in files", + }; + let input = cx.new(|cx| InputState::new(window, cx).placeholder(placeholder)); + let owner = id.clone(); + let sub = cx.subscribe_in(&input, window, move |ws: &mut Workspace, _, ev: &InputEvent, window, cx| match ev { + InputEvent::Change => ws.update_picker(&owner, cx), + InputEvent::PressEnter { .. } => ws.choose_picked(window, cx), + _ => {} + }); + input.update(cx, |i, cx| i.focus(window, cx)); + pane.picker = Some(Picker { kind, input, hits: vec![], selected: 0, generation: Default::default(), _sub: sub }); + self.update_picker(&id, cx); + cx.notify(); + } + + pub fn close_picker(&mut self, window: &mut Window, cx: &mut Context) { + let id = self.active_id().cloned(); + if let Some(pane) = id.and_then(|id| self.panes.get_mut(&id)) { + pane.picker = None; + if let Some(buffer) = pane.shown().map(|t| t.buffer.clone()) { + buffer.update(cx, |b, cx| b.focus(window, cx)); + } + } + cx.notify(); + } + + fn shown_picker(&mut self) -> Option<&mut Picker> { + let id = self.active_id().cloned()?; + self.panes.get_mut(&id)?.picker.as_mut() + } + + /// Move the highlighted row by `by`, staying within the list. + pub fn move_picked(&mut self, by: isize, cx: &mut Context) { + let Some(p) = self.shown_picker() else { return }; + p.selected = p.selected.saturating_add_signed(by).min(p.hits.len().saturating_sub(1)); + cx.notify(); + } + + /// Highlight row `ix`. + pub fn pick(&mut self, ix: usize, cx: &mut Context) { + if let Some(p) = self.shown_picker() { + p.selected = ix.min(p.hits.len().saturating_sub(1)); + cx.notify(); + } + } + + pub fn choose_picked(&mut self, window: &mut Window, cx: &mut Context) { + let Some(id) = self.active_id().cloned() else { return }; + let Some(p) = self.panes.get(&id).and_then(|p| p.picker.as_ref()) else { return }; + let Some(hit) = p.hits.get(p.selected).cloned() else { return }; + let line = (p.kind == PickerKind::Text).then_some(hit.line); + self.close_picker(window, cx); + self.open_file(&id, hit.path, line, window, cx); + } + + pub(super) fn update_picker(&mut self, id: &Id, cx: &mut Context) { + let Some(pane) = self.panes.get_mut(id) else { return }; + let (all, rel, recent) = (pane.files.clone(), pane.relative.clone(), pane.recent.clone()); + let Some(p) = pane.picker.as_mut() else { return }; + let query = p.input.read(cx).value().to_string(); + let generation = p.generation.fetch_add(1, Ordering::Relaxed) + 1; + p.selected = 0; + match p.kind { + PickerKind::Files => { + p.hits = recent_first(&query, &all, &rel, &recent) + .into_iter() + .map(|i| Hit { path: all[i].clone(), line: 0, text: rel[i].clone() }) + .collect(); + cx.notify(); + } + PickerKind::Text => { + let latest = p.generation.clone(); + let id = id.clone(); + cx.spawn(async move |this, cx| { + cx.background_executor().timer(SEARCH_DELAY).await; + let stale = move || latest.load(Ordering::Relaxed) != generation; + if stale() { + return; + } + let searching = stale.clone(); + let hits = cx.background_executor().spawn(async move { files::search(&all, &query, SHOWN, &searching) }).await; + let _ = this.update(cx, |ws, cx| { + if !stale() + && let Some(p) = ws.panes.get_mut(&id).and_then(|p| p.picker.as_mut()) + { + p.hits = hits; + cx.notify(); + } + }); + }) + .detach(); + } + } + } +} + +/// Quick open's order: by how well each path matches `query`, except that with nothing typed the recently shown +/// files come first, latest first. +fn recent_first(query: &str, all: &[PathBuf], rel: &[String], recent: &[PathBuf]) -> Vec { + if !query.trim().is_empty() { + return files::rank_paths(query, rel, SHOWN); + } + let mut order = files::rank_paths(query, rel, all.len()); + // Stable, so the rest keep their order. + order.sort_by_key(|&i| recent.iter().position(|r| *r == all[i]).unwrap_or(usize::MAX)); + order.truncate(SHOWN); + order +} + +/// `path` under the listed folder, with `/` separators, for showing and for matching. +pub fn relative(path: &Path, root: &Path) -> String { + path.strip_prefix(root).unwrap_or(path).to_string_lossy().replace('\\', "/") +} + +#[cfg(test)] +mod tests { + use super::recent_first; + use std::path::PathBuf; + + #[test] + fn recent_files_come_first_until_something_is_typed() { + let rel: Vec = ["a.rs", "b.rs", "c.rs"].map(String::from).to_vec(); + let all: Vec = rel.iter().map(PathBuf::from).collect(); + let recent = [PathBuf::from("c.rs"), PathBuf::from("b.rs")]; + assert_eq!(recent_first("", &all, &rel, &recent), [2, 1, 0]); + assert_eq!(recent_first("a", &all, &rel, &recent), [0], "typing ranks by the match alone"); + } +} diff --git a/src/app/repo.rs b/src/app/repo.rs index 1c16a10..cdbdf6c 100644 --- a/src/app/repo.rs +++ b/src/app/repo.rs @@ -22,6 +22,7 @@ impl Workspace { // The branch shown in the top bar follows a pull, switch or new branch. ws.store.refresh_git(); ws.store.save_if_dirty(); + ws.refresh_pending(cx); match result { Ok(summary) => ws.toast(summary, false, cx), Err(fail) => match fail.conflict_in { @@ -42,6 +43,24 @@ impl Workspace { .detach(); } + /// Re-read, off the UI thread, whether Commit & Push has anything to do in the shown session's folder. + pub(super) fn refresh_pending(&mut self, cx: &mut Context) { + let cwd = self.active_cwd(); + cx.spawn(async move |this, cx| { + let dir = cwd.clone(); + let pending = cx.background_executor().spawn(async move { crate::git::commit::pending(&dir) }).await; + let _ = this.update(cx, |ws, cx| { + // The shown session may have changed meanwhile; its own read replaces this one. + let now = pending.ok().map(|p| (cwd, p)); + if ws.pending != now { + ws.pending = now; + cx.notify(); + } + }); + }) + .detach(); + } + /// Fetch origin for the folder in view once a minute so the branch menu opens instantly and the /// remote branches it lists are current. Skipped while another git operation runs. pub(super) fn start_fetch_loop(&mut self, cx: &mut Context) { diff --git a/src/app/selection_reference.rs b/src/app/selection_reference.rs new file mode 100644 index 0000000..2d6e265 --- /dev/null +++ b/src/app/selection_reference.rs @@ -0,0 +1,81 @@ +//! Point Claude at the editor's selection: moving the keyboard to the session's terminal while lines are selected puts +//! `@path#L12-30: ` into Claude's input, so the user types their comment after it on the same line. Leaving the +//! terminal without typing takes it back out; once the user typed after it, it stays. + +use gpui_kit::component::input::RopeExt; + +use super::*; + +impl Workspace { + /// Have the session's terminal watch its keyboard focus, for `on_terminal_focus` and `on_terminal_blur`. + pub(super) fn watch_terminal_focus(&self, id: &Id, view: &Entity, window: &mut Window, cx: &mut Context) -> [Subscription; 2] { + let focus = view.read(cx).focus_handle(cx); + let (focused, blurred) = (id.clone(), id.clone()); + [ + cx.on_focus(&focus, window, move |ws, _w, cx| ws.on_terminal_focus(&focused, cx)), + cx.on_blur(&focus, window, move |ws, _w, cx| ws.on_terminal_blur(&blurred, cx)), + ] + } + + fn on_terminal_focus(&mut self, id: &Id, cx: &mut Context) { + if std::mem::take(&mut self.skip_selection_reference) { + return; + } + if !self.editing() || self.active_id() != Some(id) || self.store.session(id).is_none_or(|r| r.kind != SessionKind::Claude) { + return; + } + let Some(reference) = self.selection_reference(id, cx) else { return }; + let Some(view) = self.live_view(id) else { return }; + // Still in Claude's input from an earlier visit, where the user kept it by typing after it. Once sent, it can + // be put in again. + if view.read(cx).input_holds(&reference) { + return; + } + view.update(cx, |v, cx| v.insert_reference(&reference, cx)); + } + + fn on_terminal_blur(&mut self, id: &Id, cx: &mut Context) { + self.skip_selection_reference = false; + let Some(view) = self.live_view(id) else { return }; + view.update(cx, |v, cx| v.withdraw_reference(cx)); + } + + /// `@path#L..` for the shown tab's selection; `None` when nothing is selected. + pub(super) fn selection_reference(&self, id: &Id, cx: &App) -> Option { + let pane = self.panes.get(id)?; + let tab = pane.shown().filter(|t| t.note.is_none())?; + let b = tab.buffer.read(cx); + let range = b.selected_range(); + if range.is_empty() { + return None; + } + let start = b.text().offset_to_point(range.start); + let end = b.text().offset_to_point(range.end); + // Relative to the listed folder, which is the session's own: the path Claude Code resolves `@` against. + let path = super::picker::relative(&tab.path, &pane.root); + Some(reference(&path, start.row, end.row, end.column)) + } +} + +/// `@path#L-` (1-based, or `#L` for one line) for a selection from row `start` to the point `end_row`, +/// `end_col` (0-based). A selection that ends at the very start of a line doesn't take that line. +fn reference(path: &str, start: usize, end_row: usize, end_col: usize) -> String { + let last = if end_row > start && end_col == 0 { end_row - 1 } else { end_row }; + match last == start { + true => format!("@{path}#L{}", start + 1), + false => format!("@{path}#L{}-{}", start + 1, last + 1), + } +} + +#[cfg(test)] +mod tests { + use super::reference; + + #[test] + fn references_name_the_selected_lines() { + assert_eq!(reference("src/main.rs", 11, 29, 4), "@src/main.rs#L12-30"); + assert_eq!(reference("a.rs", 4, 4, 9), "@a.rs#L5", "within one line"); + assert_eq!(reference("a.rs", 4, 7, 0), "@a.rs#L5-7", "whole lines, ending at the start of the next"); + assert_eq!(reference("a.rs", 4, 5, 0), "@a.rs#L5"); + } +} diff --git a/src/app/sessions.rs b/src/app/sessions.rs index 7aa176f..035cf1b 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -2,22 +2,35 @@ use super::*; +/// Item `n` (from 1) of `items`. +fn numbered(items: &[T], n: usize) -> Option<&T> { + items.get(n.checked_sub(1)?) +} + +/// How long Ctrl (Cmd) is held alone before the sidebar shows the session shortcuts. +const SHORTCUT_HOLD: Duration = Duration::from_millis(400); + impl Workspace { /// Per-process additions to a Claude launch; nothing in the user's Claude Code config changes: /// the mod (`--plugin-dir`, which reports usage and status), the tab-title MCP server (`--mcp-config`, its - /// tools pre-allowed), and IDE integration switched off through environment variables. + /// tools pre-allowed), and IDE integration switched off through environment variables. `chrome` adds Claude in + /// Chrome (`--chrome`). fn with_helpers( - &self, + &mut self, mut spec: SpawnSpec, claude_session_id: &str, record_id: &str, + chrome: bool, + cx: &mut Context, ) -> SpawnSpec { let started = std::time::Instant::now(); // Diagnostics for the start-up trace (`terminal/trace.rs`): start without Claudiu's MCP server or mod to see what they cost. let without = |name: &str| crate::terminal::trace::on() && std::env::var_os(name).is_some(); - if let Ok(config) = mcp::prepare(claude_session_id, record_id).and_then(|c| if without("CLAUDIU_NO_MCP") { Err(std::io::Error::other("off")) } else { Ok(c) }) { + let settings = &self.store.data.settings; + let off = mcp::tools_off(&settings.claudiu_tools_off, &settings.trimmed_tools); + if let Ok(config) = mcp::prepare(claude_session_id, record_id, &off).and_then(|c| if without("CLAUDIU_NO_MCP") { Err(std::io::Error::other("off")) } else { Ok(c) }) { spec.args.push("--allowedTools".into()); - spec.args.extend(mcp::allowed_tools()); + spec.args.extend(mcp::allowed_tools(&off)); spec.args.extend(["--mcp-config".into(), config.to_string_lossy().into_owned()]); } if let Ok(dir) = claude::plugin::install().and_then(|d| if without("CLAUDIU_NO_MOD") { Err(std::io::Error::other("off")) } else { Ok(d) }) { @@ -28,13 +41,14 @@ impl Workspace { spec.env.push((crate::visual::VISUAL_ENV.into(), crate::visual::file(record_id).to_string_lossy().into_owned())); spec.env.push((crate::claude::ask::ASK_ENV.into(), crate::claude::ask::request_file(record_id).to_string_lossy().into_owned())); } - if self.store.session(record_id).and_then(|r| r.claude.as_ref()).is_some_and(|m| m.chrome) { + if chrome { spec.args.push("--chrome".into()); } spec.env.push(("CLAUDE_CODE_NO_FLICKER".into(), "1".into())); // fullscreen renderer, per process spec.env.push(("CLAUDE_CODE_AUTO_CONNECT_IDE".into(), "false".into())); spec.env.push(("CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL".into(), "1".into())); - if let Some(acct) = self.store.active_account() { + self.sync_configs_now(cx); + if let Some(acct) = self.store.session_account(record_id) { spec.env.push((usage::ACCOUNT_ENV.into(), acct.id.clone())); spec.env.extend(Self::account_env(acct)); } @@ -87,12 +101,12 @@ impl Workspace { } pub fn new_claude(&mut self, cwd: PathBuf, window: &mut Window, cx: &mut Context) { - self.new_claude_with(cwd, vec![], window, cx); + self.new_claude_with(cwd, vec![], Starter::User, window, cx); } /// `leading` goes before every other argument: the initial prompt must come ahead of the variadic /// `--allowedTools` / `--mcp-config` flags, or they would swallow it. - pub(super) fn new_claude_with(&mut self, cwd: PathBuf, leading: Vec, window: &mut Window, cx: &mut Context) { + pub(super) fn new_claude_with(&mut self, cwd: PathBuf, mut leading: Vec, by: Starter, window: &mut Window, cx: &mut Context) { let Some(exe) = self.claude_exe.clone() else { self.toast("Could not find the `claude` CLI. Install Claude Code, or set its path in Settings.", true, cx); return; @@ -100,8 +114,12 @@ impl Workspace { let session_id = new_id(); let record_id = new_id(); let mut spec = claude::new_session_spec(&exe, &cwd, &session_id); + let settings = &self.store.data.settings; + let defaults = claude::defaults::flags(&settings.new_session, settings.trimmed_tools.contains(&claude::trim::Trim::PlanMode), &leading, by); + leading.extend(defaults); spec.args.splice(0..0, leading); - let spec = self.with_helpers(spec, &session_id, &record_id); + let chrome = self.store.data.settings.chrome_default; + let spec = self.with_helpers(spec, &session_id, &record_id, chrome, cx); let record = SessionRecord { id: record_id, kind: SessionKind::Claude, @@ -116,6 +134,7 @@ impl Workspace { hidden: false, claude: Some(ClaudeMeta { session_id, + chrome, ..Default::default() }), }; @@ -143,7 +162,7 @@ impl Workspace { if let Some(name) = rec.chosen_title() { spec.args.extend(["--name".into(), name.into()]); } - let spec = self.with_helpers(spec, &meta.session_id, &rec.id); + let spec = self.with_helpers(spec, &meta.session_id, &rec.id, meta.chrome, cx); self.start(rec, spec, false, window, cx); } @@ -196,6 +215,7 @@ impl Workspace { move |ws: &mut Workspace, _view, ev: &TerminalEvent, window, cx| match ev { TerminalEvent::Exited(code) => ws.on_exit(&sub_id, *code, window, cx), TerminalEvent::Bell => {} + TerminalEvent::OpenPath(path, line) => ws.open_from_terminal(&sub_id, path, *line, window, cx), }, ); let claude_name = spec.args.iter().position(|a| a == "--name").and_then(|i| spec.args.get(i + 1)).cloned(); @@ -203,11 +223,17 @@ impl Workspace { if let Some(cid) = self.store.session(&id).and_then(|r| r.claude_id()) { mcp::write_name(cid, claude_name.as_deref()); } - let account = self.store.active_account().map_or_else(|| MAIN_ACCOUNT.into(), |a| a.id.clone()); + // The account `with_helpers` chose: kept, so the session starts there again after closing or a restart. + let account = self.store.session_account(&id).map_or_else(|| MAIN_ACCOUNT.into(), |a| a.id.clone()); + if let Some(meta) = self.store.session_mut(&id).and_then(|r| r.claude.as_mut()) { + meta.account = Some(account.clone()); + } + let _focus = self.watch_terminal_focus(&id, &view, window, cx); self.live.push(Live { id: id.clone(), view, _sub: sub, + _focus, claude_name, title_stamp: None, account, @@ -324,6 +350,7 @@ impl Workspace { let was_active = self.active_id().is_some_and(|a| a == id); self.live.retain(|l| l.id != id); // dropping the view drops the Terminal, which closes the PTY self.shells.remove(id); + self.panes.remove(id); self.visuals.remove(id); self.recent.retain(|r| r != id); // Closing the shown session goes back to the one shown before it; otherwise stay where we are. @@ -348,13 +375,45 @@ impl Workspace { cx.notify(); } + /// The running sessions, in the sidebar's order. + pub fn running_ids(&self, cx: &App) -> Vec { + self.live.iter().filter(|l| l.view.read(cx).is_running()).map(|l| l.id.clone()).collect() + } + + /// Show running session number `n` (from 1), as the sidebar numbers them while Ctrl is held. + pub fn show_numbered(&mut self, n: usize, window: &mut Window, cx: &mut Context) { + if let Some(id) = numbered(&self.running_ids(cx), n).cloned() { + self.show_session(&id, window, cx); + } + } + + /// Ctrl (Cmd) alone, held for a moment, shows the sessions' numbers; anything else hides them. Quick chords such as + /// Ctrl+C never show them, since the key is let go before the wait ends. + pub fn modifiers_changed(&mut self, modifiers: &gpui::Modifiers, cx: &mut Context) { + self.shortcuts_wait += 1; + if self.shortcuts_shown { + self.shortcuts_shown = false; + cx.notify(); + } + let alone = modifiers.secondary() && !modifiers.shift && !modifiers.alt && !(modifiers.control && modifiers.platform); + if !alone { + return; + } + let wait = self.shortcuts_wait; + cx.spawn(async move |this, cx| { + cx.background_executor().timer(SHORTCUT_HOLD).await; + let _ = this.update(cx, |ws, cx| { + if ws.shortcuts_wait == wait { + ws.shortcuts_shown = true; + cx.notify(); + } + }); + }) + .detach(); + } + pub fn cycle(&mut self, delta: isize, window: &mut Window, cx: &mut Context) { - let running: Vec = self - .live - .iter() - .filter(|l| l.view.read(cx).is_running()) - .map(|l| l.id.clone()) - .collect(); + let running = self.running_ids(cx); if running.is_empty() { return; } @@ -395,3 +454,17 @@ impl Workspace { Some((claude::context_fraction(tokens), tokens, false, None)) } } + +#[cfg(test)] +mod tests { + use super::numbered; + + #[test] + fn numbers_count_from_one() { + let running = ["a", "b", "c"]; + assert_eq!(numbered(&running, 1), Some(&"a")); + assert_eq!(numbered(&running, 3), Some(&"c")); + assert_eq!(numbered(&running, 4), None, "no fourth session"); + assert_eq!(numbered(&running, 0), None); + } +} diff --git a/src/app/settings.rs b/src/app/settings.rs new file mode 100644 index 0000000..aa8d9b5 --- /dev/null +++ b/src/app/settings.rs @@ -0,0 +1,98 @@ +//! The pages of the Settings dialog and its keyboard handling. + +use super::*; +use gpui::KeyDownEvent; + +/// A category in the Settings dialog's list, in display order. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SettingsPage { + #[default] + General, + Sessions, + ClaudeTools, + ClaudiuTools, + About, +} + +impl SettingsPage { + pub const ALL: [SettingsPage; 5] = [Self::General, Self::Sessions, Self::ClaudeTools, Self::ClaudiuTools, Self::About]; + + pub fn label(self) -> &'static str { + match self { + Self::General => "General", + Self::Sessions => "Sessions", + Self::ClaudeTools => "Claude Code tools", + Self::ClaudiuTools => "Claudiu tools", + Self::About => "About", + } + } + + /// The page below this one; the last page stays put. + pub fn next(self) -> Self { + let i = Self::ALL.iter().position(|p| *p == self).unwrap_or(0); + Self::ALL[(i + 1).min(Self::ALL.len() - 1)] + } + + /// The page above this one; the first page stays put. + pub fn prev(self) -> Self { + let i = Self::ALL.iter().position(|p| *p == self).unwrap_or(0); + Self::ALL[i.saturating_sub(1)] + } +} + +impl Workspace { + /// Keys for the open Settings dialog, seen before the focused control. Up and Down change the page and Enter saves + /// only while the category list has focus; Tab and Shift+Tab cycle the list and the current page's text fields. + pub(crate) fn settings_key(&mut self, ev: &KeyDownEvent, window: &mut Window, cx: &mut Context) { + let Some(Modal::Settings { shell, claude, model, list_focus, .. }) = &self.modal else { return }; + let list_focus = list_focus.clone(); + let fields = match self.settings_page { + SettingsPage::General => vec![shell.clone(), claude.clone()], + SettingsPage::Sessions => vec![model.clone()], + _ => Vec::new(), + }; + let on_list = list_focus.is_focused(window); + match ev.keystroke.key.as_str() { + "up" if on_list => self.settings_page = self.settings_page.prev(), + "down" if on_list => self.settings_page = self.settings_page.next(), + "enter" if on_list => self.submit_modal(window, cx), + "tab" => { + let here = if on_list { + Some(0) + } else { + fields.iter().position(|f| f.read(cx).focus_handle(cx).is_focused(window)).map(|i| i + 1) + }; + let Some(here) = here else { return }; + let stops = fields.len() + 1; + let there = if ev.keystroke.modifiers.shift { (here + stops - 1) % stops } else { (here + 1) % stops }; + match there.checked_sub(1) { + None => window.focus(&list_focus, cx), + Some(i) => fields[i].update(cx, |s, cx| s.focus(window, cx)), + } + } + _ => return, + } + cx.stop_propagation(); + cx.notify(); + } +} + +#[cfg(test)] +mod tests { + use super::SettingsPage::{self, *}; + + #[test] + fn next_and_prev_walk_the_list_and_stop_at_the_ends() { + assert_eq!(General.next(), Sessions); + assert_eq!(ClaudiuTools.next(), About); + assert_eq!(About.next(), About); + assert_eq!(About.prev(), ClaudiuTools); + assert_eq!(Sessions.prev(), General); + assert_eq!(General.prev(), General); + } + + #[test] + fn opens_on_general() { + assert_eq!(SettingsPage::default(), General); + } +} diff --git a/src/claude/accounts.rs b/src/claude/accounts.rs index 5e2b626..e0a95d9 100644 --- a/src/claude/accounts.rs +++ b/src/claude/accounts.rs @@ -1,7 +1,8 @@ //! Alt accounts. Each is a Claude Code config folder (`CLAUDE_CONFIG_DIR`) inside Claudiu's data dir that holds -//! only its own login (`.credentials.json`, `.claude.json`); every other entry links back to the main -//! `~/.claude`, so settings, instructions, agents, skills, plugins and session history are shared. -//! The main account is the user's normal Claude Code: launched without `CLAUDE_CONFIG_DIR`, never written to. +//! only its own login (`.credentials.json`, `.claude.json`). Folders (agents, skills, plugins, session history) link +//! back to the main `~/.claude`; settings, `CLAUDE.md`, keybindings, MCP servers and project trust are kept equal in +//! every account by `config_sync`. The main account is the user's normal Claude Code: launched without +//! `CLAUDE_CONFIG_DIR`. use std::ffi::OsStr; use std::fs; @@ -27,7 +28,7 @@ fn is_own(name: &OsStr) -> bool { OWN.contains(&n.as_ref()) || n.starts_with(".claude.json") } -/// A new, empty alt folder with the shared entries already linked. +/// A new alt folder with the shared entries already in place. pub fn create(main: &Path) -> io::Result { let dir = root().join(crate::store::new_id()); fs::create_dir_all(&dir)?; @@ -35,80 +36,41 @@ pub fn create(main: &Path) -> io::Result { Ok(dir) } -/// Link every shared entry of `main` that `alt` doesn't have yet. Runs before each launch, so entries Claude -/// Code adds to the main folder later are picked up too. Returns the last error but links what it can. +/// Link every folder of `main` that `alt` doesn't have yet, so skills, agents, plugins and session history are the +/// same for every account. Runs before each launch, so folders Claude Code adds to the main one later are picked up +/// too. Files are not linked: `config_sync` copies the shared ones, and the rest belong to each account. Returns the +/// last error but links what it can. pub fn link_shared(main: &Path, alt: &Path) -> io::Result<()> { let mut result = Ok(()); for e in fs::read_dir(main)?.flatten() { let name = e.file_name(); - let dst = alt.join(&name); let src = e.path(); - if is_own(&name) { + if is_own(&name) || !src.is_dir() { continue; } - if let Ok(meta) = fs::symlink_metadata(&dst) { - // A hard-linked file that a program saved by replacing it is now a separate copy: rejoin it. - if meta.is_file() && !meta.file_type().is_symlink() && src.is_file() { - let r = rejoin(&src, &dst); - if r.is_err() { - result = r; - } - } - // shortcut: any other entry the alt already has (e.g. a folder Claude Code made first) is left alone. + let dst = alt.join(&name); + // shortcut: a folder the alt already has (e.g. one Claude Code made first) is left alone. + if fs::symlink_metadata(&dst).is_ok() { continue; } - let r = if src.is_dir() { link_dir(&src, &dst) } else { link_file(&src, &dst) }; - if r.is_err() { - result = r; + if let Err(e) = link_dir(&src, &dst) { + result = Err(e); } } result } -/// The newer of the two copies wins: an alt's change is written into the main file (in place, so other -/// hard links to it see it), then the alt's copy is replaced by a link to main again. -/// The losing copy is kept in the alt's own `backups` folder first. -fn rejoin(main: &Path, alt: &Path) -> io::Result<()> { - let mtime = |p: &Path| fs::metadata(p).and_then(|m| m.modified()); - let (m, a) = (mtime(main)?, mtime(alt)?); - if m == a { - return Ok(()); // still one file (or identical): nothing to do - } - let (loser, side) = if a > m { (main, "main") } else { (alt, "alt") }; - let name = main.file_name().unwrap_or_default().to_string_lossy(); - let backups = alt.parent().unwrap_or(alt).join("backups"); - fs::create_dir_all(&backups)?; - fs::copy(loser, backups.join(format!("{name}.{side}.{}.bak", crate::store::now())))?; - if a > m { - fs::copy(alt, main)?; - } - fs::remove_file(alt)?; - link_file(main, alt) -} - #[cfg(windows)] fn link_dir(src: &Path, dst: &Path) -> io::Result<()> { // Junctions need no admin rights or Developer Mode, unlike directory symlinks. junction::create(src, dst) } -#[cfg(windows)] -fn link_file(src: &Path, dst: &Path) -> io::Result<()> { - // shortcut: without Developer Mode file symlinks fail and a hard link is used; a program that saves the main - // file by replacing it leaves the alt on the old copy until the alt is re-created. - std::os::windows::fs::symlink_file(src, dst).or_else(|_| fs::hard_link(src, dst)) -} - #[cfg(unix)] fn link_dir(src: &Path, dst: &Path) -> io::Result<()> { std::os::unix::fs::symlink(src, dst) } -#[cfg(unix)] -fn link_file(src: &Path, dst: &Path) -> io::Result<()> { - std::os::unix::fs::symlink(src, dst) -} - /// Delete an alt folder: its login plus the links, never what they point at. Refuses anything outside `root()`. pub fn remove(alt: &Path) -> io::Result<()> { if !alt.starts_with(root()) || alt == root() { @@ -162,25 +124,26 @@ mod tests { use super::*; #[test] - fn alt_shares_everything_but_the_login_and_removal_keeps_main_intact() { + fn alt_links_folders_keeps_its_own_files_and_removal_keeps_main_intact() { let tmp = tempfile::tempdir().unwrap(); let (main, alt) = (tmp.path().join("main"), tmp.path().join("alt")); fs::create_dir_all(main.join("projects/p")).unwrap(); fs::create_dir_all(&alt).unwrap(); - for f in ["settings.json", ".credentials.json", ".claude.json", ".claude.json.backup"] { + for f in ["settings.json", "history.jsonl", ".credentials.json", ".claude.json"] { fs::write(main.join(f), f).unwrap(); } link_shared(&main, &alt).unwrap(); - assert_eq!(fs::read_to_string(alt.join("settings.json")).unwrap(), "settings.json"); - assert!(!alt.join(".credentials.json").exists() && !alt.join(".claude.json").exists() && !alt.join(".claude.json.backup").exists()); + assert!(!alt.join("settings.json").exists() && !alt.join("history.jsonl").exists(), "files are not linked"); + assert!(!alt.join(".credentials.json").exists() && !alt.join(".claude.json").exists()); - // Writes through the alt land in main. + // Folders are shared: writes through the alt land in main. fs::write(alt.join("projects/p/s.jsonl"), "x").unwrap(); assert!(main.join("projects/p/s.jsonl").is_file()); - // The alt's own login stays its own; re-linking is idempotent. + // The alt's own login stays its own; linking again is harmless. fs::write(alt.join(".credentials.json"), "alt").unwrap(); link_shared(&main, &alt).unwrap(); + assert_eq!(fs::read_to_string(alt.join(".credentials.json")).unwrap(), "alt"); delete(&alt).unwrap(); assert!(!alt.exists()); @@ -189,37 +152,6 @@ mod tests { assert_eq!(fs::read_to_string(main.join(".credentials.json")).unwrap(), ".credentials.json"); } - #[test] - fn a_replaced_file_link_is_rejoined_with_the_newer_content_winning() { - let tmp = tempfile::tempdir().unwrap(); - let (main, alt) = (tmp.path().join("main"), tmp.path().join("alt")); - fs::create_dir_all(&main).unwrap(); - fs::create_dir_all(&alt).unwrap(); - fs::write(main.join("settings.json"), "old").unwrap(); - // The alt's copy was saved by replacing it, later than main. - fs::write(alt.join("settings.json"), "alt edit").unwrap(); - let later = std::time::SystemTime::now() + std::time::Duration::from_secs(60); - fs::File::options().write(true).open(alt.join("settings.json")).unwrap().set_modified(later).unwrap(); - - link_shared(&main, &alt).unwrap(); - assert_eq!(fs::read_to_string(main.join("settings.json")).unwrap(), "alt edit"); - assert!(fs::read_dir(alt.join("backups")).unwrap().next().is_some(), "main's old copy is backed up"); - - // Rejoined: a later write to main shows in the alt. - fs::write(main.join("settings.json"), "main edit").unwrap(); - assert_eq!(fs::read_to_string(alt.join("settings.json")).unwrap(), "main edit"); - - // Main newer: the alt's own copy is backed up before it is replaced. - fs::remove_file(alt.join("settings.json")).unwrap(); - fs::write(alt.join("settings.json"), "alt only").unwrap(); - let earlier = std::time::SystemTime::now() - std::time::Duration::from_secs(600); - fs::File::options().write(true).open(alt.join("settings.json")).unwrap().set_modified(earlier).unwrap(); - link_shared(&main, &alt).unwrap(); - assert_eq!(fs::read_to_string(alt.join("settings.json")).unwrap(), "main edit"); - let saved = fs::read_dir(alt.join("backups")).unwrap().flatten().any(|e| fs::read_to_string(e.path()).unwrap() == "alt only"); - assert!(saved, "the alt's copy is backed up"); - } - #[test] fn remove_refuses_folders_outside_the_accounts_root() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/claude/config_sync.rs b/src/claude/config_sync.rs new file mode 100644 index 0000000..c9f50f5 --- /dev/null +++ b/src/claude/config_sync.rs @@ -0,0 +1,401 @@ +//! One Claude Code configuration across the main account and every alt account, kept equal in both directions. +//! +//! Each account has its own config folder, so the same setting exists once per account. A setting changed in any +//! account (or outside Claudiu) is copied to the others. Nothing is linked: Claude Code saves these files by replacing +//! them, which breaks a link and lets the copies drift. +//! +//! "Changed" means different from the value every account agreed on last time (`State`), not newer: Claude Code +//! rewrites its files all the time, so the newest file is not necessarily the one somebody edited. When several +//! accounts changed, the newest change wins. A removed file is not copied as a removal. + +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::SystemTime; + +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +/// Files inside each account's config folder that every account shares. +const FILES: &[&str] = &["settings.json", "CLAUDE.md", "keybindings.json"]; +/// Top-level keys of an account's `.claude.json` that every account shares: the user's MCP servers. +const SHARED_KEYS: &[&str] = &["mcpServers"]; +/// One project's trust in `.claude.json`: once any account trusts a folder, every account does. +const TRUST_KEY: &str = "hasTrustDialogAccepted"; + +/// Runs one at a time: a sync at launch and the background one must not interleave. +static RUNNING: Mutex<()> = Mutex::new(()); + +/// Where one account keeps its configuration. +#[derive(Clone, Debug)] +pub struct Account { + /// Its config folder (`~/.claude` for the main account). + pub dir: PathBuf, + /// Its `.claude.json`: login, MCP servers and project trust. Claude Code rewrites it whole and often, so it is + /// only written while no session uses it (`busy`). + pub claude_json: PathBuf, + pub busy: bool, +} + +/// What every account held the last time they agreed, as fingerprints, keyed by what was compared. +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct State { + agreed: BTreeMap, + /// `key|account` for every account that held that key when everyone last agreed. + #[serde(default)] + had: BTreeSet, +} + +impl State { + pub fn load(path: &Path) -> Self { + fs::read_to_string(path).ok().and_then(|text| serde_json::from_str(&text).ok()).unwrap_or_default() + } + + fn save(&self, path: &Path) -> io::Result<()> { + crate::datadir::write_atomic(path, &serde_json::to_string(self).map_err(io::Error::other)?) + } +} + +pub fn state_path() -> PathBuf { + crate::datadir::data_dir().join("config-sync.json") +} + +/// The main account, and the alt folders given: where each keeps its files. The main `.claude.json` is `~/.claude.json` +/// unless `CLAUDE_CONFIG_DIR` moves it into the folder. +pub fn main_account(busy: bool) -> Option { + let dir = super::claude_home()?; + let claude_json = match std::env::var_os("CLAUDE_CONFIG_DIR") { + Some(_) => dir.join(".claude.json"), + None => super::home_dir()?.join(".claude.json"), + }; + Some(Account { dir, claude_json, busy }) +} + +pub fn alt_account(dir: &Path, busy: bool) -> Account { + Account { dir: dir.to_path_buf(), claude_json: dir.join(".claude.json"), busy } +} + +/// Bring every account to the same configuration. Does what it can and returns the first error. +pub fn sync(accounts: &[Account], state_file: &Path) -> io::Result<()> { + let _one_at_a_time = RUNNING.lock().unwrap_or_else(|e| e.into_inner()); + let mut state = State::load(state_file); + let mut result = Ok(()); + for name in FILES { + let paths: Vec = accounts.iter().map(|a| a.dir.join(name)).collect(); + keep(&mut result, sync_files(&paths, &format!("file:{name}"), &mut state)); + } + keep(&mut result, sync_claude_json(accounts, &mut state)); + keep(&mut result, state.save(state_file)); + result +} + +fn keep(result: &mut io::Result<()>, next: io::Result<()>) { + if result.is_ok() { + *result = next; + } +} + +/// FNV-1a: stable between Rust versions, unlike a std hasher, since fingerprints are saved. +fn fingerprint(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)) +} + +/// What one account holds for a thing being compared. +struct Held { + value: T, + print: u64, + modified: SystemTime, +} + +/// The account whose value the others should take, or `None` when nobody holds one. Changed since `agreed` wins over +/// unchanged, then the newest, then the earliest account (the main one). +fn pick(held: &[Option>], agreed: Option) -> Option { + let present = || held.iter().enumerate().filter_map(|(i, h)| h.as_ref().map(|h| (i, h))); + let changed: Vec<_> = present().filter(|(_, h)| Some(h.print) != agreed).collect(); + let candidates = if changed.is_empty() { present().collect() } else { changed }; + candidates.into_iter().min_by(|(ia, a), (ib, b)| b.modified.cmp(&a.modified).then(ia.cmp(ib))).map(|(i, _)| i) +} + +/// Copy the winning file over the others. A file is written beside its target and renamed over it, which replaces the +/// directory entry and never writes through a link left by an earlier Claudiu. +fn sync_files(paths: &[PathBuf], key: &str, state: &mut State) -> io::Result<()> { + let held: Vec>>> = paths + .iter() + .map(|p| { + let value = fs::read(p).ok()?; + let modified = fs::metadata(p).and_then(|m| m.modified()).ok()?; + Some(Held { print: fingerprint(&value), value, modified }) + }) + .collect(); + let Some(winner) = pick(&held, state.agreed.get(key).copied()) else { return Ok(()) }; + let source = held[winner].as_ref().expect("the winner holds a value"); + let mut result = Ok(()); + for (path, have) in paths.iter().zip(&held) { + if have.as_ref().is_some_and(|h| h.print == source.print) { + continue; + } + let tmp = path.with_extension("claudiu-tmp"); + let written = fs::write(&tmp, &source.value).and_then(|()| fs::rename(&tmp, path)); + if written.is_err() { + let _ = fs::remove_file(&tmp); + } + keep(&mut result, written); + } + // Only when everyone took it: an account that could not would otherwise look "changed" next time and push back. + if result.is_ok() { + state.agreed.insert(key.into(), source.print); + } + result +} + +/// A JSON value written the same way whatever the order of its keys, so equal settings have equal fingerprints. +fn canonical(value: &Value) -> String { + match value { + Value::Object(map) => { + let sorted: BTreeMap<_, _> = map.iter().collect(); + let items: Vec = sorted.into_iter().map(|(k, v)| format!("{}:{}", Value::String(k.clone()), canonical(v))).collect(); + format!("{{{}}}", items.join(",")) + } + Value::Array(items) => format!("[{}]", items.iter().map(canonical).collect::>().join(",")), + other => other.to_string(), + } +} + +/// Shared keys and project trust across the accounts' `.claude.json` files. A file that cannot be read or parsed is +/// left out, and one that is `busy` is read but not written. Nothing is recorded as agreed until every account took it. +fn sync_claude_json(accounts: &[Account], state: &mut State) -> io::Result<()> { + let mut files: Vec, SystemTime)>> = accounts + .iter() + .map(|a| { + let Value::Object(map) = serde_json::from_str(&fs::read_to_string(&a.claude_json).ok()?).ok()? else { return None }; + Some((map, fs::metadata(&a.claude_json).and_then(|m| m.modified()).ok()?)) + }) + .collect(); + let mut dirty = vec![false; accounts.len()]; + let mut incomplete = false; + let mut agreed_now: Vec<(String, u64, Vec)> = vec![]; + + for key in SHARED_KEYS { + let state_key = format!("json:{key}"); + let held: Vec>>> = files + .iter() + .enumerate() + .map(|(i, f)| { + let (map, modified) = f.as_ref()?; + let value = map.get(*key).cloned(); + // A missing key is a removal only where the key was seen at the last agreement; elsewhere (a new + // account) it is a gap to fill, so a fresh account cannot wipe the others' servers. + if value.is_none() && !state.had.contains(&had_key(&state_key, &accounts[i])) { + return None; + } + let print = fingerprint(value.as_ref().map(canonical).unwrap_or_default().as_bytes()); + Some(Held { value, print, modified: *modified }) + }) + .collect(); + let Some(winner) = pick(&held, state.agreed.get(&state_key).copied()) else { continue }; + let source = held[winner].as_ref().expect("the winner holds a value"); + let (print, value) = (source.print, source.value.clone()); + for (i, file) in files.iter_mut().enumerate() { + let Some((map, _)) = file else { continue }; + if map.get(*key) == value.as_ref() { + continue; + } + if accounts[i].busy { + incomplete = true; + continue; + } + match &value { + Some(value) => map.insert((*key).into(), value.clone()), + None => map.remove(*key), + }; + dirty[i] = true; + } + let holders = if value.is_some() { (0..files.len()).filter(|i| files[*i].is_some()).collect() } else { vec![] }; + agreed_now.push((state_key, print, holders)); + } + + // Trust only grows: a folder any account trusts is trusted everywhere. + let trusted: HashSet = files + .iter() + .flatten() + .filter_map(|(map, _)| map.get("projects")?.as_object()) + .flat_map(|projects| projects.iter().filter(|(_, p)| p.get(TRUST_KEY) == Some(&Value::Bool(true))).map(|(path, _)| path.clone())) + .collect(); + for (i, file) in files.iter_mut().enumerate() { + let Some((map, _)) = file else { continue }; + let untrusting: Vec<&String> = trusted + .iter() + .filter(|path| map.get("projects").and_then(|p| p.get(path.as_str())).and_then(|p| p.get(TRUST_KEY)) != Some(&Value::Bool(true))) + .collect(); + if untrusting.is_empty() { + continue; + } + if accounts[i].busy { + incomplete = true; + continue; + } + let Some(projects) = map.entry("projects").or_insert_with(|| Value::Object(Map::new())).as_object_mut() else { continue }; + for path in untrusting { + if let Some(project) = projects.entry(path.clone()).or_insert_with(|| Value::Object(Map::new())).as_object_mut() { + project.insert(TRUST_KEY.into(), Value::Bool(true)); + dirty[i] = true; + } + } + } + + let mut result = Ok(()); + for (i, file) in files.iter().enumerate() { + let (true, Some((map, _))) = (dirty[i], file) else { continue }; + let text = serde_json::to_string_pretty(map).map_err(io::Error::other); + let written = text.and_then(|text| crate::datadir::write_atomic(&accounts[i].claude_json, &text)); + incomplete |= written.is_err(); + keep(&mut result, written); + } + if !incomplete { + for (state_key, print, holders) in agreed_now { + state.agreed.insert(state_key.clone(), print); + state.had.retain(|h| !h.starts_with(&format!("{state_key}|"))); + state.had.extend(holders.into_iter().map(|i| had_key(&state_key, &accounts[i]))); + } + } + result +} + +fn had_key(state_key: &str, account: &Account) -> String { + format!("{state_key}|{}", account.dir.display()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + fn at(secs: u64) -> SystemTime { + SystemTime::UNIX_EPOCH + Duration::from_secs(secs) + } + + fn holding(text: &str, secs: u64) -> Option>> { + Some(Held { value: text.as_bytes().to_vec(), print: fingerprint(text.as_bytes()), modified: at(secs) }) + } + + #[test] + fn the_account_that_changed_wins_even_when_another_file_is_newer() { + let agreed = fingerprint(b"v1"); + // main was only touched later (Claude Code rewrote it); the alt holds the edit. + let held = [holding("v1", 500), holding("edited in alt", 100), holding("v1", 300)]; + assert_eq!(pick(&held, Some(agreed)), Some(1)); + } + + #[test] + fn of_several_changes_the_newest_wins_and_a_tie_goes_to_the_earlier_account() { + let agreed = fingerprint(b"v1"); + assert_eq!(pick(&[holding("a", 100), holding("b", 200)], Some(agreed)), Some(1)); + assert_eq!(pick(&[holding("a", 100), holding("b", 100)], Some(agreed)), Some(0)); + } + + #[test] + fn without_a_record_the_newest_file_wins_and_a_missing_one_is_filled() { + assert_eq!(pick(&[holding("old", 100), holding("new", 200)], None), Some(1)); + assert_eq!(pick(&[None, holding("only", 100)], None), Some(1)); + assert_eq!(pick::>(&[None, None], None), None); + } + + struct Setup { + _tmp: tempfile::TempDir, + accounts: Vec, + state: PathBuf, + } + + fn setup(count: usize) -> Setup { + let tmp = tempfile::tempdir().unwrap(); + let accounts = (0..count) + .map(|i| { + let dir = tmp.path().join(format!("acct{i}")); + fs::create_dir_all(&dir).unwrap(); + Account { claude_json: dir.join(".claude.json"), dir, busy: false } + }) + .collect(); + Setup { state: tmp.path().join("state.json"), accounts, _tmp: tmp } + } + + fn write_at(path: &Path, text: &str, secs: u64) { + fs::write(path, text).unwrap(); + fs::File::options().write(true).open(path).unwrap().set_modified(at(secs)).unwrap(); + } + + fn read(account: &Account, name: &str) -> String { + fs::read_to_string(account.dir.join(name)).unwrap() + } + + #[test] + fn an_edit_in_any_account_reaches_all_the_others_and_nothing_bounces_back() { + let s = setup(3); + for a in &s.accounts { + write_at(&a.dir.join("settings.json"), "{\"model\":\"opus\"}", 1000); + } + sync(&s.accounts, &s.state).unwrap(); + + // The second alt edits its copy; main is touched later without a change. + write_at(&s.accounts[2].dir.join("settings.json"), "{\"model\":\"sonnet\"}", 2000); + sync(&s.accounts, &s.state).unwrap(); + assert!(s.accounts.iter().all(|a| read(a, "settings.json") == "{\"model\":\"sonnet\"}")); + + // Then main edits: it spreads the other way. + write_at(&s.accounts[0].dir.join("settings.json"), "{\"model\":\"haiku\"}", 3000); + sync(&s.accounts, &s.state).unwrap(); + assert!(s.accounts.iter().all(|a| read(a, "settings.json") == "{\"model\":\"haiku\"}")); + } + + + #[test] + fn a_missing_file_is_filled_but_a_removed_one_is_not_copied_as_a_removal() { + let s = setup(2); + write_at(&s.accounts[0].dir.join("CLAUDE.md"), "rules", 1000); + sync(&s.accounts, &s.state).unwrap(); + assert_eq!(read(&s.accounts[1], "CLAUDE.md"), "rules"); + fs::remove_file(s.accounts[0].dir.join("CLAUDE.md")).unwrap(); + sync(&s.accounts, &s.state).unwrap(); + assert_eq!(read(&s.accounts[1], "CLAUDE.md"), "rules"); + assert_eq!(read(&s.accounts[0], "CLAUDE.md"), "rules", "it comes back from the account that still has it"); + } + + #[test] + fn mcp_servers_and_trust_are_shared_and_the_rest_of_claude_json_is_left_alone() { + let s = setup(2); + write_at(&s.accounts[0].claude_json, r#"{"oauthAccount":{"email":"main"},"mcpServers":{"a":{"command":"x"}},"projects":{"C:/p":{"hasTrustDialogAccepted":true,"allowedTools":["t"]}}}"#, 1000); + write_at(&s.accounts[1].claude_json, r#"{"oauthAccount":{"email":"alt"},"projects":{"C:/q":{"hasTrustDialogAccepted":true}}}"#, 1000); + sync(&s.accounts, &s.state).unwrap(); + let alt: Value = serde_json::from_str(&fs::read_to_string(&s.accounts[1].claude_json).unwrap()).unwrap(); + let main: Value = serde_json::from_str(&fs::read_to_string(&s.accounts[0].claude_json).unwrap()).unwrap(); + assert_eq!(alt["mcpServers"]["a"]["command"], "x"); + assert_eq!(alt["oauthAccount"]["email"], "alt", "the login is the account's own"); + assert_eq!(alt["projects"]["C:/p"][TRUST_KEY], true); + assert_eq!(main["projects"]["C:/q"][TRUST_KEY], true); + assert!(alt["projects"]["C:/p"].get("allowedTools").is_none(), "only trust is shared, not the project's other state"); + + // Removing the servers in the alt removes them everywhere. + let mut alt: Value = serde_json::from_str(&fs::read_to_string(&s.accounts[1].claude_json).unwrap()).unwrap(); + alt.as_object_mut().unwrap().remove("mcpServers"); + write_at(&s.accounts[1].claude_json, &alt.to_string(), 2000); + sync(&s.accounts, &s.state).unwrap(); + let main: Value = serde_json::from_str(&fs::read_to_string(&s.accounts[0].claude_json).unwrap()).unwrap(); + assert!(main.get("mcpServers").is_none(), "the removal reached main"); + } + + #[test] + fn a_busy_accounts_claude_json_is_not_written_and_catches_up_when_idle() { + let mut s = setup(2); + write_at(&s.accounts[0].claude_json, r#"{"mcpServers":{"a":{}}}"#, 1000); + write_at(&s.accounts[1].claude_json, r#"{"login":1}"#, 1000); + s.accounts[1].busy = true; + let before = fs::read_to_string(&s.accounts[1].claude_json).unwrap(); + sync(&s.accounts, &s.state).unwrap(); + assert_eq!(fs::read_to_string(&s.accounts[1].claude_json).unwrap(), before); + s.accounts[1].busy = false; + sync(&s.accounts, &s.state).unwrap(); + let alt: Value = serde_json::from_str(&fs::read_to_string(&s.accounts[1].claude_json).unwrap()).unwrap(); + assert!(alt["mcpServers"].get("a").is_some()); + } +} diff --git a/src/claude/defaults.rs b/src/claude/defaults.rs new file mode 100644 index 0000000..256b02d --- /dev/null +++ b/src/claude/defaults.rs @@ -0,0 +1,187 @@ +//! What new Claude sessions start with (Settings → Sessions): model, effort and permission mode, passed as +//! `claude` flags. Empty means Claude Code's own default. Resumed sessions get none of this; their conversation +//! already has its own. + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Effort { + Low, + Medium, + High, + Xhigh, + Max, +} + +impl Effort { + pub const ALL: [Effort; 5] = [Self::Low, Self::Medium, Self::High, Self::Xhigh, Self::Max]; + + /// The value `--effort` takes. + pub fn name(self) -> &'static str { + match self { + Self::Low => "low", + Self::Medium => "medium", + Self::High => "high", + Self::Xhigh => "xhigh", + Self::Max => "max", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PermissionMode { + AcceptEdits, + Auto, + BypassPermissions, + Manual, + DontAsk, + Plan, +} + +impl PermissionMode { + pub const ALL: [PermissionMode; 6] = [Self::AcceptEdits, Self::Auto, Self::BypassPermissions, Self::Manual, Self::DontAsk, Self::Plan]; + + /// The value `--permission-mode` takes. + pub fn name(self) -> &'static str { + match self { + Self::AcceptEdits => "acceptEdits", + Self::Auto => "auto", + Self::BypassPermissions => "bypassPermissions", + Self::Manual => "manual", + Self::DontAsk => "dontAsk", + Self::Plan => "plan", + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct NewSessionDefaults { + /// A model alias or id, already checked with `usage::valid_model_name`. + #[serde(default)] + pub model: Option, + #[serde(default)] + pub effort: Option, + #[serde(default)] + pub permission_mode: Option, +} + +/// Who is starting the session; some defaults are not for every caller. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Starter { + /// The user: the New session button, or the GitHub pane's Ask Claude. + User, + /// Fix Git with Claude, which has to edit files and run git, so plan mode would stop it. + FixGit, + /// Another session, through `start_code_session`: it can't start a session that skips every prompt unless the + /// user chose that there. + OtherSession, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct InvalidModel; + +/// A model name as `--model` takes it: trimmed and lowercased, as in the Advisor dialog. `None` for an empty field; +/// `Err` for anything that isn't an alias or id. "off" is refused because it means nothing here. +pub fn parse_model(text: &str) -> Result, InvalidModel> { + let name = text.trim().to_lowercase(); + if name.is_empty() { + return Ok(None); + } + if name == "off" || !super::usage::valid_model_name(&name) { + return Err(InvalidModel); + } + Ok(Some(name)) +} + +/// The flags to add to a new session: each default that is set, unless `leading` already carries that flag or the +/// starter doesn't get it. `plan_trimmed` is whether Plan mode is trimmed (`trim.rs`): the model couldn't propose +/// leaving plan mode then, so a `plan` default is not passed. +pub fn flags(defaults: &NewSessionDefaults, plan_trimmed: bool, leading: &[String], by: Starter) -> Vec { + let given = |flag: &str| leading.iter().any(|a| a == flag || a.strip_prefix(flag).is_some_and(|rest| rest.starts_with('='))); + let mut out = Vec::new(); + if let Some(model) = defaults.model.as_deref().filter(|_| !given("--model")) { + out.extend(["--model".to_string(), model.to_string()]); + } + if let Some(effort) = defaults.effort.filter(|_| !given("--effort")) { + out.extend(["--effort".to_string(), effort.name().to_string()]); + } + let mode = defaults.permission_mode.filter(|mode| match mode { + PermissionMode::Plan => !plan_trimmed && by != Starter::FixGit, + PermissionMode::BypassPermissions => by != Starter::OtherSession, + _ => true, + }); + if let Some(mode) = mode.filter(|_| !given("--permission-mode")) { + out.extend(["--permission-mode".to_string(), mode.name().to_string()]); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() + } + + fn all_set(mode: PermissionMode) -> NewSessionDefaults { + NewSessionDefaults { model: Some("opus".into()), effort: Some(Effort::High), permission_mode: Some(mode) } + } + + #[test] + fn nothing_set_adds_nothing() { + assert!(flags(&NewSessionDefaults::default(), false, &[], Starter::User).is_empty()); + } + + #[test] + fn all_three_are_passed() { + assert_eq!( + flags(&all_set(PermissionMode::Plan), false, &[], Starter::User), + strings(&["--model", "opus", "--effort", "high", "--permission-mode", "plan"]) + ); + } + + #[test] + fn a_flag_the_caller_passes_wins() { + let leading = strings(&["a prompt", "--model", "claude-sonnet-5-5", "--effort=medium"]); + assert!(flags(&all_set(PermissionMode::Plan), false, &leading, Starter::FixGit).is_empty()); + assert_eq!(flags(&all_set(PermissionMode::Auto), false, &leading, Starter::User), strings(&["--permission-mode", "auto"])); + } + + #[test] + fn plan_is_not_passed_while_plan_mode_is_trimmed() { + assert!(flags(&all_set(PermissionMode::Plan), true, &[], Starter::User).iter().all(|a| a != "--permission-mode")); + assert!(flags(&all_set(PermissionMode::Auto), true, &[], Starter::User).contains(&"auto".to_string())); + } + + #[test] + fn fix_git_gets_no_plan_and_other_sessions_get_no_bypass() { + assert!(!flags(&all_set(PermissionMode::Plan), false, &[], Starter::FixGit).contains(&"--permission-mode".to_string())); + assert!(flags(&all_set(PermissionMode::Plan), false, &[], Starter::OtherSession).contains(&"plan".to_string())); + assert!(!flags(&all_set(PermissionMode::BypassPermissions), false, &[], Starter::OtherSession).contains(&"--permission-mode".to_string())); + assert!(flags(&all_set(PermissionMode::BypassPermissions), false, &[], Starter::User).contains(&"bypassPermissions".to_string())); + assert!(flags(&all_set(PermissionMode::BypassPermissions), false, &[], Starter::FixGit).contains(&"bypassPermissions".to_string())); + } + + #[test] + fn model_names_are_cleaned_and_off_is_refused() { + assert_eq!(parse_model(" Opus "), Ok(Some("opus".into()))); + assert_eq!(parse_model(" "), Ok(None)); + assert_eq!(parse_model("off"), Err(InvalidModel)); + assert_eq!(parse_model("op us!"), Err(InvalidModel)); + } + + #[test] + fn names_match_what_the_cli_takes_and_what_is_saved() { + for mode in PermissionMode::ALL { + assert_eq!(serde_json::to_string(&mode).unwrap(), format!("\"{}\"", mode.name())); + } + for effort in Effort::ALL { + assert_eq!(serde_json::to_string(&effort).unwrap(), format!("\"{}\"", effort.name())); + } + let old_state: NewSessionDefaults = serde_json::from_str("{}").unwrap(); + assert_eq!(old_state, NewSessionDefaults::default()); + } +} diff --git a/src/claude/mcp.rs b/src/claude/mcp.rs index 677d25b..0e2f092 100644 --- a/src/claude/mcp.rs +++ b/src/claude/mcp.rs @@ -13,12 +13,81 @@ use std::path::{Path, PathBuf}; use serde_json::{Value, json}; +use serde::{Deserialize, Serialize}; + +use crate::claude::trim::Trim; use crate::store::Attached; pub const FLAG: &str = "--mcp-title"; pub const SESSION_ENV: &str = "CLAUDIU_SESSION"; /// Claudiu's own id of the session. Unlike Claude's session id it survives `/clear`. pub const RECORD_ENV: &str = "CLAUDIU_RECORD"; +/// Comma-separated names of what the server leaves out of this session (see `tools_off`). Missing means nothing is off. +pub const TOOLS_OFF_ENV: &str = "CLAUDIU_TOOLS_OFF"; + +/// A group of Claudiu's tools the user can switch off (Settings → Claudiu tools). `set_tab_title` has no switch. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Feature { + Visual, + Github, + Sessions, + Model, +} + +impl Feature { + /// In the order the page lists them. + pub const ALL: [Feature; 4] = [Self::Visual, Self::Github, Self::Sessions, Self::Model]; + + pub fn label(self) -> &'static str { + match self { + Self::Visual => "Visual panel", + Self::Github => "GitHub sidebar", + Self::Sessions => "Other sessions", + Self::Model => "Model switch", + } + } + + /// The name in `CLAUDIU_TOOLS_OFF`. + fn name(self) -> &'static str { + match self { + Self::Visual => "visual", + Self::Github => "github", + Self::Sessions => "sessions", + Self::Model => "model", + } + } +} + +/// `features` in the page's order, without repeats: how they are stored, so equal sets compare equal. +pub fn normalized_features(features: &[Feature]) -> Vec { + Feature::ALL.into_iter().filter(|f| features.contains(f)).collect() +} + +/// What the server leaves out of a session: the features switched off, plus `ask_user_question` and `artifacts` when +/// those Claude Code tools are trimmed, so Claudiu's own text stops naming them. +pub fn tools_off(features: &[Feature], trimmed: &[Trim]) -> Vec<&'static str> { + let mut off: Vec<&'static str> = normalized_features(features).into_iter().map(Feature::name).collect(); + off.extend(trimmed.contains(&Trim::AskUserQuestion).then_some("ask_user_question")); + off.extend(trimmed.contains(&Trim::Artifacts).then_some("artifacts")); + off +} + +/// The feature a tool belongs to; `set_tab_title` belongs to none. +fn feature_of(tool: &str) -> Option<&'static str> { + match tool { + "show_visual" => Some("visual"), + "attach_github" | "detach_github" => Some("github"), + "link_session" | "unlink_session" => Some("sessions"), + "set_model" => Some("model"), + _ if BRIDGE_TOOLS.contains(&tool) => Some("sessions"), + _ => None, + } +} + +fn is_off(off: &[&str], tool: &str) -> bool { + feature_of(tool).is_some_and(|f| off.contains(&f)) +} /// Tools the model uses to tell Claudiu something about itself; none of them reads or starts another session. const OWN_TOOLS: [&str; 6] = ["set_tab_title", "attach_github", "detach_github", "link_session", "unlink_session", "show_visual"]; @@ -28,36 +97,69 @@ const BRIDGE_TOOLS: [&str; 5] = ["list_code_sessions", "read_code_session", "sea /// `mcp____` names allowed per process so Claude Code adds no prompt of its own: renaming the tab is /// harmless, and the cross-session tools are limited to what the user asks of the model. -pub fn allowed_tools() -> Vec { - OWN_TOOLS.iter().copied().chain(BRIDGE_TOOLS).map(|t| format!("mcp__claudiu__{t}")).collect() +pub fn allowed_tools(off: &[&str]) -> Vec { + OWN_TOOLS.iter().copied().chain(BRIDGE_TOOLS).filter(|t| !is_off(off, t)).map(|t| format!("mcp__claudiu__{t}")).collect() } const BRIDGE_INSTRUCTIONS: &str = " Claudiu also has tools that reach your other sessions: list_code_sessions, read_code_session, \ -search_sessions, search_projects (the user's projects) and start_code_session (opens a new Claude Code session). They act at once. \ -Use them only when the user asks you to look at, hand work to or continue in another session, or to work in a project."; +search_sessions, search_projects and start_code_session. They act at once. Use them only when the user asks you to look at, hand \ +work to or continue in another session, or to work in a project; search_sessions may also be used unasked to find a session to link."; -const LINK_INSTRUCTIONS: &str = " Claudiu shows related sessions together. When this work continues, builds on or was \ -prompted by another Claude Code session (the user says so, or you recognise it), find it with search_sessions \ -and call link_session with its id, once per pair. When a link no longer fits (the work went elsewhere, or it was linked by mistake), \ -call unlink_session with the id. Both are silent and change nothing else."; +const LINK_INSTRUCTIONS: &str = " Claudiu shows related sessions together. When this work continues or builds on another \ +Claude Code session (the user says so, or you recognise it), find it with search_sessions and call link_session once per pair; \ +call unlink_session when a link no longer fits. Both are silent."; /// What makes the model call `show_visual` (the tool's own description teaches the dialect, and stays deferred). -const VISUAL_INSTRUCTIONS: &str = " Visual: Claudiu draws a Visual panel beside this terminal. When something is easier to see than to \ -read (a diagram, a comparison, a table, a chart, a dashboard, a mock-up, a structured walkthrough), call show_visual with Markdown and \ -the panel fills as you write it. If its schema is not loaded yet, load it first with ToolSearch (select:mcp__claudiu__show_visual)."; +const VISUAL_INSTRUCTIONS: &str = " Visual: Claudiu has a Visual panel beside this terminal. When a reply would hold a table, \ +a comparison, a flow of 3+ steps, an architecture, a before/after, several statuses or a chart, draw that part with show_visual \ +unasked (private, no approval) and reply in a few lines. Not for short answers or code."; + +const ARTIFACT_INSTRUCTIONS: &str = " Artifacts are for pages to share."; + +const VISUAL_LOADING: &str = " Load it first with ToolSearch (select:mcp__claudiu__show_visual) if needed."; /// What makes the model call `attach_github`. -const GITHUB_INSTRUCTIONS: &str = " GitHub: attach_github is silent and costs nothing, and its description says when to call it; detach_github takes an item off again when it no longer belongs. If its schema is not loaded yet, load it first with ToolSearch (select:mcp__claudiu__attach_github)."; - -const INSTRUCTIONS: &str = "You are running inside Claudiu, which shows a tab title for this session. Call the \ -set_tab_title tool with a short title (2-5 words, no quotes) once you understand the user's first request. After \ -that, call it again only when the current task or scope changes and the title no longer fits. Also call it \ -whenever the user asks you to rename or retitle this session or tab (use the name they gave). Don't call it again \ -with the same or a near-identical title, and never twice in a row for the same reason (if the user ran /rename \ -themselves, the title is already set; leave it). Don't mention the tool unless the user asked for a rename.\ - Never switch models on your own. Before calling set_model, ask the user with the AskUserQuestion tool which \ -model and effort they want, unless they just named them explicitly. The switch applies from your next request; \ -after calling set_model, end your turn and ask the user to confirm before continuing, so the session itself switches."; +const GITHUB_INSTRUCTIONS: &str = " GitHub: call attach_github (silent, free) for each issue or pull request you work on, \ +as its description says; detach_github takes one off again."; + +const TITLE_INSTRUCTIONS: &str = "You are running inside Claudiu, which shows a tab title for this session. Call \ +set_tab_title (2-5 words, no quotes) once you understand the user's first request, again only when the task changes \ +and the title no longer fits, and whenever the user asks for a rename (use their name). Never repeat a near-identical \ +title; if the user ran /rename, leave it. Don't mention the tool unless asked."; + +/// What makes the model ask before it calls `set_model`; `ask` is how it asks. +fn model_instructions(ask: &str) -> String { + format!( + " Never switch models on your own: before set_model, ask {ask} which model and effort, unless the user \ +just named them. After set_model, end your turn and ask the user to confirm before continuing, so the switch applies." + ) +} + +/// The `initialize` reply's instructions: the tab-title text, then the text of each feature that is not off. +fn instructions(off: &[&str]) -> String { + let on = |name: &str| !off.contains(&name); + let mut text = TITLE_INSTRUCTIONS.to_string(); + if on("model") { + text += &model_instructions(if on("ask_user_question") { "with AskUserQuestion" } else { "the user" }); + } + if on("github") { + text += GITHUB_INSTRUCTIONS; + } + if on("sessions") { + text += LINK_INSTRUCTIONS; + } + if on("visual") { + text += VISUAL_INSTRUCTIONS; + if on("artifacts") { + text += ARTIFACT_INSTRUCTIONS; + } + text += VISUAL_LOADING; + } + if on("sessions") { + text += BRIDGE_INSTRUCTIONS; + } + text +} fn titles_dir() -> PathBuf { crate::datadir::data_dir().join("titles") @@ -99,12 +201,15 @@ pub fn run() -> i32 { let session = std::env::var(SESSION_ENV).unwrap_or_default(); let record = std::env::var(RECORD_ENV).unwrap_or_else(|_| session.clone()); let from = format!("code:{record}"); - serve(std::io::stdin().lock(), std::io::stdout().lock(), &session, &record, &crate::datadir::data_dir(), |tool, args| crate::claude::bridge::ask(&from, tool, args)); + let off_env = std::env::var(TOOLS_OFF_ENV).unwrap_or_default(); + let off: Vec<&str> = off_env.split(',').map(str::trim).filter(|n| !n.is_empty()).collect(); + serve(std::io::stdin().lock(), std::io::stdout().lock(), &session, &record, &crate::datadir::data_dir(), &off, |tool, args| crate::claude::bridge::ask(&from, tool, args)); 0 } -/// `ask` carries a cross-session request to Claudiu and waits for the user's answer. -fn serve(input: impl BufRead, mut out: impl Write, session: &str, record: &str, data: &Path, ask: impl Fn(&str, &Value) -> Result) { +/// `off` names what this session leaves out (see `tools_off`): those tools are neither listed nor callable and their +/// instruction text is dropped. `ask` carries a cross-session request to Claudiu and waits for the user's answer. +fn serve(input: impl BufRead, mut out: impl Write, session: &str, record: &str, data: &Path, off: &[&str], ask: impl Fn(&str, &Value) -> Result) { for line in input.lines().map_while(Result::ok) { let Ok(msg) = serde_json::from_str::(&line) else { continue }; // Notifications (no id) and responses (no method) need no answer. @@ -114,11 +219,11 @@ fn serve(input: impl BufRead, mut out: impl Write, session: &str, record: &str, "protocolVersion": msg["params"]["protocolVersion"].as_str().unwrap_or("2025-06-18"), "capabilities": { "tools": {} }, "serverInfo": { "name": "claudiu", "version": env!("CARGO_PKG_VERSION") }, - "instructions": format!("{INSTRUCTIONS}{GITHUB_INSTRUCTIONS}{LINK_INSTRUCTIONS}{VISUAL_INSTRUCTIONS}{BRIDGE_INSTRUCTIONS}"), + "instructions": instructions(off), })), "ping" => Ok(json!({})), - "tools/list" => Ok(json!({ "tools": own_tools().into_iter().chain(bridge_tools()).collect::>() })), - "tools/call" => Ok(match msg["params"]["name"].as_str() { + "tools/list" => Ok(json!({ "tools": own_tools(off).into_iter().chain(bridge_tools()).filter(|t| !is_off(off, t["name"].as_str().unwrap_or_default())).collect::>() })), + "tools/call" => Ok(match msg["params"]["name"].as_str().filter(|tool| !is_off(off, tool)) { Some("set_tab_title") => set_title(&msg["params"], session, &data.join("titles")), Some("attach_github") => attach_github(&msg["params"], record, &attach_dir(data)), Some("detach_github") => detach_github(&msg["params"], record, &attach_dir(data)), @@ -144,7 +249,7 @@ fn serve(input: impl BufRead, mut out: impl Write, session: &str, record: &str, } /// The tools that tell Claudiu something about the session. -fn own_tools() -> Vec { +fn own_tools(off: &[&str]) -> Vec { let link = json!({ "name": "link_session", "description": "Link this session to another one, so Claudiu shows them together in the sidebar. Use it when this work continues, builds on or was prompted by another Claude Code session. Find the id with search_sessions. Silent; once per pair.", @@ -156,13 +261,12 @@ fn own_tools() -> Vec { }); let attach = json!({ "name": "attach_github", - "description": "Show a GitHub issue or pull request of this session's project in Claudiu's sidebar. Call this every time you read, view, search, open, comment on or push anything about a GitHub issue or pull request, including when the user only asks to see it. Also call it when the user names one by number or link. Call it once per item, before running the next command. It changes nothing on GitHub.", + "description": "Show a GitHub issue or pull request of this session's project in Claudiu's sidebar. Call it once per item, before your next command, whenever you read, open, comment on, create or push to one, or the user names or asks to see one. Not for every result of a list or search. It changes nothing on GitHub.", "inputSchema": { "type": "object", "properties": { "kind": { "type": "string", "enum": ["issue", "pull"], "description": "issue or pull (a pull request)" }, "number": { "type": "integer", "description": "The issue or pull request number" }, - "title": { "type": "string", "description": "Its title, if you know it (optional)" }, }, "required": ["kind", "number"], }, @@ -218,7 +322,10 @@ fn own_tools() -> Vec { }, })), attach, detach, json!({ "name": "set_model", - "description": "Switch this session's model and/or effort from your next request on, even mid-turn. Always ask the user first with the AskUserQuestion tool (which model, which effort) unless they just named them explicitly; never switch on your own. Claude Code also keeps the choice as the user's default model/effort.", + "description": format!( + "Switch this session's model and/or effort from your next request on, even mid-turn. Always ask the user first{} (which model, which effort) unless they just named them explicitly; never switch on your own. Claude Code also keeps the choice as the user's default model/effort.", + if off.contains(&"ask_user_question") { "" } else { " with the AskUserQuestion tool" } + ), "inputSchema": { "type": "object", "properties": { @@ -247,7 +354,7 @@ fn bridge_tools() -> Vec { ), tool( "search_sessions", - format!("Search the user's Claude Code sessions by words in their title, project or folder. Returns id, title, project and created/updated times of the best matches; pass an id to link_session.{CONFIRM}"), + format!("Search the user's Claude Code sessions by words in their title, project or folder. Returns id, title, project and created/updated times of the best matches; pass an id to link_session. Read-only: use it when the user asks, or unasked to find a session to link."), json!({ "query": { "type": "string", "description": "Words to look for (optional: without it, the most recent)" } }), ), tool( @@ -255,7 +362,7 @@ fn bridge_tools() -> Vec { format!("Search the user's projects (name, folder, git branch) by words. Pass a project's name as the folder of start_code_session.{CONFIRM}"), json!({ "query": { "type": "string", "description": "Words to look for (optional: without it, every project)" } }), ), - tool("start_code_session", format!("Open a new Claude Code session, optionally with a first prompt.{CONFIRM}"), target), + tool("start_code_session", format!("Open a new Claude Code session, optionally with a first prompt. With a prompt, the user is asked to approve it first; without one, it opens at once.{CONFIRM}"), target), ] } @@ -284,8 +391,7 @@ fn attach_github(params: &Value, record: &str, dir: &Path) -> Value { Ok(item) => item, Err(e) => return e, }; - let title = args["title"].as_str().and_then(clean_title); - match append_line(dir, record, &json!({ "pull": pull, "number": number, "title": title })) { + match append_line(dir, record, &json!({ "pull": pull, "number": number })) { Ok(()) => reply(&format!("{} #{number} attached.", if pull { "Pull request" } else { "Issue" }), false), Err(e) => reply(&format!("could not attach: {e}"), true), } @@ -321,10 +427,15 @@ fn detach_github(params: &Value, record: &str, dir: &Path) -> Value { /// One JSON line for Claudiu to pick up, in the file of the calling session. fn append_line(dir: &Path, record: &str, line: &Value) -> std::io::Result<()> { - use std::io::Write as _; std::fs::create_dir_all(dir)?; let path = dir.join(format!("{}.jsonl", crate::datadir::safe_file_stem(record))); - writeln!(std::fs::OpenOptions::new().create(true).append(true).open(path)?, "{line}") + write_line(&mut std::fs::OpenOptions::new().create(true).append(true).open(path)?, line) +} + +/// The line goes out in one write: `writeln!` on a bare file writes it in many pieces, and `read_attached` could +/// catch half a line and drop it. +fn write_line(out: &mut impl std::io::Write, line: &Value) -> std::io::Result<()> { + out.write_all(format!("{line}\n").as_bytes()) } /// Ask Claudiu to show this session together with another one (`verb` "link"), or to stop. Claudiu checks that the @@ -345,11 +456,15 @@ fn link_session(params: &Value, record: &str, dir: &Path, verb: &str) -> Value { } /// Write the per-session MCP config and return its path (for `--mcp-config`). -pub fn prepare(claude_session_id: &str, record_id: &str) -> std::io::Result { +pub fn prepare(claude_session_id: &str, record_id: &str, off: &[&str]) -> std::io::Result { + let mut env = json!({ SESSION_ENV: claude_session_id, RECORD_ENV: record_id }); + if !off.is_empty() { + env[TOOLS_OFF_ENV] = off.join(",").into(); + } let config = json!({ "mcpServers": { "claudiu": { "command": std::env::current_exe()?.to_string_lossy(), "args": [FLAG], - "env": { SESSION_ENV: claude_session_id, RECORD_ENV: record_id }, + "env": env, }}}); let path = config_dir().join(format!("{}.json", crate::datadir::safe_file_stem(claude_session_id))); crate::datadir::write_atomic(&path, &config.to_string())?; @@ -429,17 +544,40 @@ pub fn cleanup_dirs() -> [PathBuf; 4] { mod tests { use super::*; - fn talk_with(requests: &[Value], session: &str, dir: &Path, ask: impl Fn(&str, &Value) -> Result) -> Vec { + fn talk_off(requests: &[Value], session: &str, dir: &Path, off: &[&str], ask: impl Fn(&str, &Value) -> Result) -> Vec { let input: String = requests.iter().map(|r| format!("{r}\n")).collect(); let mut out = Vec::new(); - serve(input.as_bytes(), &mut out, session, session, dir, ask); + serve(input.as_bytes(), &mut out, session, session, dir, off, ask); String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect() } + fn talk_with(requests: &[Value], session: &str, dir: &Path, ask: impl Fn(&str, &Value) -> Result) -> Vec { + talk_off(requests, session, dir, &[], ask) + } + fn talk(requests: &[Value], session: &str, dir: &Path) -> Vec { talk_with(requests, session, dir, |_, _| Err("no".into())) } + #[test] + fn a_line_for_claudiu_is_written_in_one_piece() { + #[derive(Default)] + struct Writes(Vec>); + impl std::io::Write for Writes { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.push(buf.to_vec()); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut out = Writes::default(); + write_line(&mut out, &json!({ "pull": false, "number": 71, "title": "New-session defaults" })).unwrap(); + assert_eq!(out.0.len(), 1, "a reader between two writes would see half a line"); + assert!(out.0[0].ends_with(b"\n")); + } + #[test] fn the_session_reaching_tools_are_forwarded_and_the_bookkeeping_ones_are_loaded_upfront() { let tmp = tempfile::tempdir().unwrap(); @@ -462,8 +600,8 @@ mod tests { assert_eq!(r[1]["result"]["isError"], false); assert_eq!(r[2]["result"]["content"][0]["text"], "The user declined."); assert_eq!(r[2]["result"]["isError"], true); - assert_eq!(allowed_tools().len(), BRIDGE_TOOLS.len() + OWN_TOOLS.len()); - assert!(allowed_tools().contains(&"mcp__claudiu__show_visual".to_string())); + assert_eq!(allowed_tools(&[]).len(), BRIDGE_TOOLS.len() + OWN_TOOLS.len()); + assert!(allowed_tools(&[]).contains(&"mcp__claudiu__show_visual".to_string())); } #[test] @@ -533,9 +671,9 @@ mod tests { let errors: Vec<_> = r.iter().map(|x| x["result"]["isError"].as_bool().unwrap()).collect(); assert_eq!(errors, [false, false, true, true, true]); let lines: Vec = std::fs::read_to_string(tmp.path().join("attach/s1.jsonl")).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); - assert_eq!(lines, [Attached { pull: false, number: 52, title: Some("Right sidebar".into()) }, Attached { pull: true, number: 7, title: None }]); + assert_eq!(lines, [Attached { pull: false, number: 52, title: None, state: None }, Attached { pull: true, number: 7, title: None, state: None }]); assert_eq!(talk(&[call(json!({"kind":"issue","number":1}))], "", tmp.path())[0]["result"]["isError"], true); - assert!(allowed_tools().contains(&"mcp__claudiu__attach_github".to_string())); + assert!(allowed_tools(&[]).contains(&"mcp__claudiu__attach_github".to_string())); } #[test] @@ -548,7 +686,7 @@ mod tests { let line = std::fs::read_to_string(tmp.path().join("attach/s1.jsonl")).unwrap(); assert_eq!(line.lines().count(), 1); assert_eq!(parse_attachment(line.lines().next().unwrap()), Some(Attachment::Link("abc-123".into()))); - assert_eq!(parse_attachment(r#"{"pull":true,"number":7,"title":null}"#), Some(Attachment::Github(Attached { pull: true, number: 7, title: None }))); + assert_eq!(parse_attachment(r#"{"pull":true,"number":7,"title":null}"#), Some(Attachment::Github(Attached { pull: true, number: 7, title: None, state: None }))); assert_eq!(parse_attachment(r#"{"unlink":"x"}"#), Some(Attachment::Unlink("x".into()))); assert_eq!(parse_attachment(r#"{"detach":{"pull":false,"number":3}}"#), Some(Attachment::Detach { pull: false, number: 3 })); assert_eq!(parse_attachment(r#"{"detach":{"number":3}}"#), None); @@ -565,4 +703,93 @@ mod tests { assert_eq!(std::fs::read_to_string(tmp.path().join("titles/s.txt")).unwrap().len(), 60); assert_eq!(talk(&[call(json!({"title":"hi"}))], "", tmp.path())[0]["result"]["isError"], true); } + + /// The tool names and the instruction text a server with `off` hands out. + fn offer(off: &[&str]) -> (Vec, String) { + let tmp = tempfile::tempdir().unwrap(); + let r = talk_off( + &[json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}), json!({"jsonrpc":"2.0","id":2,"method":"tools/list"})], + "s", + tmp.path(), + off, + |_, _| Err("no".into()), + ); + let names = r[1]["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect(); + (names, r[0]["result"]["instructions"].as_str().unwrap().to_string()) + } + + #[test] + fn with_nothing_off_the_server_offers_every_tool_and_all_the_text() { + let (names, text) = offer(&[]); + assert_eq!(names.len(), 12); + for part in [TITLE_INSTRUCTIONS, GITHUB_INSTRUCTIONS, LINK_INSTRUCTIONS, VISUAL_INSTRUCTIONS, BRIDGE_INSTRUCTIONS] { + assert!(text.contains(part)); + } + assert!(text.contains("ask with AskUserQuestion which model") && text.contains("Artifacts are for pages to share.")); + } + + #[test] + fn each_feature_takes_its_tools_and_its_text_away() { + let (names, text) = offer(&["visual"]); + assert!(!names.contains(&"show_visual".to_string()) && names.len() == 11); + assert!(!text.contains("Visual:") && !text.contains("show_visual")); + + let (names, text) = offer(&["github"]); + assert!(!names.iter().any(|n| n.ends_with("_github")) && names.len() == 10); + assert!(!text.contains("attach_github")); + + let (names, text) = offer(&["sessions"]); + for gone in ["link_session", "unlink_session", "list_code_sessions", "read_code_session", "search_sessions", "search_projects", "start_code_session"] { + assert!(!names.contains(&gone.to_string()), "{gone}"); + } + assert_eq!(names.len(), 5); + assert!(!text.contains("link_session") && !text.contains("start_code_session")); + + let (names, text) = offer(&["model"]); + assert!(!names.contains(&"set_model".to_string()) && names.len() == 11); + assert!(!text.contains("set_model") && !text.contains("Never switch models")); + } + + #[test] + fn the_tab_title_tool_and_text_stay_with_every_feature_off() { + let (names, text) = offer(&["visual", "github", "sessions", "model"]); + assert_eq!(names, ["set_tab_title"]); + assert_eq!(text, TITLE_INSTRUCTIONS); + } + + #[test] + fn a_call_for_an_off_tool_is_unknown_and_never_reaches_claudiu() { + let tmp = tempfile::tempdir().unwrap(); + let call = |name: &str| json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":name,"arguments":{"id":"x"}}}); + let r = talk_off(&[call("list_code_sessions"), call("attach_github")], "s", tmp.path(), &["sessions", "github"], |_, _| panic!("ask must not be called")); + for reply in &r { + assert_eq!((reply["result"]["isError"].as_bool(), reply["result"]["content"][0]["text"].as_str()), (Some(true), Some("unknown tool"))); + } + assert!(!tmp.path().join("attach").exists(), "nothing was attached"); + } + + #[test] + fn allowed_tools_leaves_out_the_tools_of_features_that_are_off() { + assert_eq!(allowed_tools(&["github", "sessions"]), ["mcp__claudiu__set_tab_title", "mcp__claudiu__show_visual"]); + } + + #[test] + fn trimming_ask_user_question_or_artifacts_changes_the_wording() { + let (_, text) = offer(&["ask_user_question", "artifacts"]); + assert!(!text.contains("AskUserQuestion") && text.contains("ask the user which model") && !text.contains("Artifacts")); + assert!(text.contains("Visual:"), "the Visual text itself stays"); + let tmp = tempfile::tempdir().unwrap(); + let described = |off: &[&str]| { + let r = talk_off(&[json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})], "s", tmp.path(), off, |_, _| Err("no".into())); + r[0]["result"]["tools"].as_array().unwrap().iter().find(|t| t["name"] == "set_model").unwrap()["description"].as_str().unwrap().to_string() + }; + assert!(described(&[]).contains("AskUserQuestion")); + assert!(!described(&["ask_user_question"]).contains("AskUserQuestion")); + } + + #[test] + fn the_off_list_comes_from_both_settings_in_the_pages_order() { + assert_eq!(tools_off(&[], &[]), Vec::<&str>::new()); + assert_eq!(tools_off(&[Feature::Model, Feature::Visual, Feature::Visual], &[Trim::Artifacts, Trim::PlanMode, Trim::AskUserQuestion]), ["visual", "model", "ask_user_question", "artifacts"]); + } } diff --git a/src/claude/mod.rs b/src/claude/mod.rs index 314a498..80b2147 100644 --- a/src/claude/mod.rs +++ b/src/claude/mod.rs @@ -9,8 +9,11 @@ pub mod accounts; pub mod ask; pub mod bridge; +pub mod config_sync; +pub mod defaults; pub mod mcp; pub mod plugin; +pub mod trim; pub mod usage; use std::fs::{self, File}; diff --git a/src/claude/plugin.rs b/src/claude/plugin.rs index 4fa8cc9..82c08ec 100644 --- a/src/claude/plugin.rs +++ b/src/claude/plugin.rs @@ -1,21 +1,78 @@ //! The mod Claudiu ships (`mod/` in the repository), embedded in the binary and written to the data folder so every //! Claude session can load it with `--plugin-dir`. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; + +/// The mod's files: path inside the mod folder, and contents. +const FILES: [(&str, &str); 3] = [ + (".claude-plugin/plugin.json", include_str!("../../mod/.claude-plugin/plugin.json")), + ("hooks/hooks.json", include_str!("../../mod/hooks/hooks.json")), + ("hooks/register.js", include_str!("../../mod/hooks/register.js")), +]; /// The mod that answers the MCP server's tools in-process (see `mod/`), written to the data dir and loaded per -/// process through `--plugin-dir`. Files are only rewritten when they changed: a rewrite reloads running sessions' mods. +/// process through `--plugin-dir`. Each distinct copy of the mod gets its own folder, so two builds of Claudiu (a +/// release and a dev build) never overwrite each other's files: a rewrite reloads the mod in every running session +/// that loaded the folder, including sessions the other build started. pub fn install() -> std::io::Result { - let dir = crate::datadir::data_dir().join("mod"); - for (rel, text) in [ - (".claude-plugin/plugin.json", include_str!("../../mod/.claude-plugin/plugin.json")), - ("hooks/hooks.json", include_str!("../../mod/hooks/hooks.json")), - ("hooks/register.js", include_str!("../../mod/hooks/register.js")), - ] { + install_into(&crate::datadir::data_dir(), &FILES) +} + +fn install_into(data: &Path, files: &[(&str, &str)]) -> std::io::Result { + let dir = data.join(folder_name(files)); + for (rel, text) in files { let path = dir.join(rel); - if std::fs::read_to_string(&path).ok().as_deref() != Some(text) { + if std::fs::read_to_string(&path).ok().as_deref() != Some(*text) { crate::datadir::write_atomic(&path, text)?; } } Ok(dir) } + +/// `mod-` and a hash of the files, so equal copies share a folder. FNV-1a, because the name must not change between +/// Rust versions (a std hasher may). +fn folder_name(files: &[(&str, &str)]) -> String { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for (rel, text) in files { + for byte in rel.bytes().chain([0]).chain(text.bytes()).chain([0]) { + hash = (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3); + } + } + format!("mod-{hash:016x}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn two_builds_with_different_mods_use_different_folders_and_leave_each_other_alone() { + let tmp = tempfile::tempdir().unwrap(); + let release = [("hooks/register.js", "release")]; + let dev = [("hooks/register.js", "dev")]; + let release_dir = install_into(tmp.path(), &release).unwrap(); + let dev_dir = install_into(tmp.path(), &dev).unwrap(); + assert_ne!(release_dir, dev_dir); + assert_eq!(std::fs::read_to_string(release_dir.join("hooks/register.js")).unwrap(), "release"); + assert_eq!(std::fs::read_to_string(dev_dir.join("hooks/register.js")).unwrap(), "dev"); + } + + #[test] + fn the_same_mod_keeps_its_folder_and_is_not_rewritten() { + let tmp = tempfile::tempdir().unwrap(); + let files = [("hooks/register.js", "same")]; + let first = install_into(tmp.path(), &files).unwrap(); + let written = std::fs::metadata(first.join("hooks/register.js")).unwrap().modified().unwrap(); + let again = install_into(tmp.path(), &files).unwrap(); + assert_eq!(first, again); + assert_eq!(std::fs::metadata(again.join("hooks/register.js")).unwrap().modified().unwrap(), written); + } + + #[test] + fn a_changed_path_or_content_changes_the_name() { + let a = folder_name(&[("a", "bc")]); + assert_ne!(a, folder_name(&[("ab", "c")]), "the split between path and text counts"); + assert_ne!(a, folder_name(&[("a", "bd")])); + assert!(a.starts_with("mod-") && a.len() == 4 + 16); + } +} diff --git a/src/claude/trim.rs b/src/claude/trim.rs new file mode 100644 index 0000000..c007f7b --- /dev/null +++ b/src/claude/trim.rs @@ -0,0 +1,316 @@ +//! Claude Code features and tools the user trimmed (Settings → Claude Code tools). Claudiu writes the trims into +//! Claude Code's own `settings.json` and takes them out again when a switch goes back on; every account gets the +//! same file through `config_sync`, and Claude Code sessions started outside Claudiu see the trims too. +//! +//! A feature flag such as `disableWorkflows` removes the feature, its tools and Claude Code's instructions about it. +//! A bare tool name in `permissions.deny` removes that tool's definition (a scoped rule like `Bash(rm *)` would only +//! block calls). See https://www.aihero.dev/how-to-kill-the-bloat-in-claude-codes-system-prompt. + +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value, json}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Trim { + BundledSkills, + Workflows, + RemoteControl, + ClaudeAiConnectors, + Artifacts, + PlanMode, + AskUserQuestion, + ScheduledTasks, + ScheduleWakeup, + RemoteTrigger, + SendMessage, + PushNotification, + DesignSync, + NotebookEdit, + ReportFindings, +} + +/// What turning an item off does in the settings file. +enum Effect { + /// Settings keys set to the given values. + Keys(&'static [(&'static str, bool)]), + /// Tool names added to `permissions.deny`. + Deny(&'static [&'static str]), +} + +impl Trim { + /// In the order the page lists them, grouped (see `GROUPS`). + pub const ALL: [Trim; 15] = [ + Self::BundledSkills, + Self::Workflows, + Self::RemoteControl, + Self::ClaudeAiConnectors, + Self::Artifacts, + Self::PlanMode, + Self::AskUserQuestion, + Self::ScheduledTasks, + Self::ScheduleWakeup, + Self::RemoteTrigger, + Self::SendMessage, + Self::PushNotification, + Self::DesignSync, + Self::NotebookEdit, + Self::ReportFindings, + ]; + + /// The page's groups: a heading and the items under it. + pub const GROUPS: [(&'static str, &'static [Trim]); 5] = [ + ("FEATURES", &[Self::BundledSkills, Self::Workflows, Self::RemoteControl, Self::ClaudeAiConnectors, Self::Artifacts]), + ("PLANNING", &[Self::PlanMode, Self::AskUserQuestion]), + ("SCHEDULING", &[Self::ScheduledTasks, Self::ScheduleWakeup, Self::RemoteTrigger]), + ("MESSAGING", &[Self::SendMessage, Self::PushNotification]), + ("OTHER", &[Self::DesignSync, Self::NotebookEdit, Self::ReportFindings]), + ]; + + pub fn label(self) -> &'static str { + match self { + Self::BundledSkills => "Bundled skills", + Self::Workflows => "Workflows", + Self::RemoteControl => "Remote control", + Self::ClaudeAiConnectors => "claude.ai connectors", + Self::Artifacts => "Artifacts", + Self::PlanMode => "Plan mode", + Self::AskUserQuestion => "AskUserQuestion", + Self::ScheduledTasks => "Scheduled tasks", + Self::ScheduleWakeup => "ScheduleWakeup", + Self::RemoteTrigger => "RemoteTrigger", + Self::SendMessage => "SendMessage", + Self::PushNotification => "PushNotification", + Self::DesignSync => "DesignSync", + Self::NotebookEdit => "NotebookEdit", + Self::ReportFindings => "ReportFindings", + } + } + + fn effect(self) -> Effect { + match self { + Self::BundledSkills => Effect::Keys(&[("disableBundledSkills", true)]), + Self::Workflows => Effect::Keys(&[("disableWorkflows", true)]), + Self::RemoteControl => Effect::Keys(&[("disableRemoteControl", true)]), + Self::ClaudeAiConnectors => Effect::Keys(&[("disableClaudeAiConnectors", true)]), + Self::Artifacts => Effect::Keys(&[("enableArtifact", false), ("disableArtifact", true)]), + Self::PlanMode => Effect::Deny(&["EnterPlanMode", "ExitPlanMode"]), + Self::AskUserQuestion => Effect::Deny(&["AskUserQuestion"]), + Self::ScheduledTasks => Effect::Deny(&["CronCreate", "CronDelete", "CronList"]), + Self::ScheduleWakeup => Effect::Deny(&["ScheduleWakeup"]), + Self::RemoteTrigger => Effect::Deny(&["RemoteTrigger"]), + Self::SendMessage => Effect::Deny(&["SendMessage"]), + Self::PushNotification => Effect::Deny(&["PushNotification"]), + Self::DesignSync => Effect::Deny(&["DesignSync"]), + Self::NotebookEdit => Effect::Deny(&["NotebookEdit"]), + Self::ReportFindings => Effect::Deny(&["ReportFindings"]), + } + } +} + +/// `trimmed` in the page's order, without repeats: how it is stored, so equal sets compare equal. +pub fn normalized(trimmed: &[Trim]) -> Vec { + Trim::ALL.into_iter().filter(|t| trimmed.contains(t)).collect() +} + +/// One line Claudiu adds to `settings.json` for a trim. +#[derive(Clone, Copy, PartialEq)] +enum Entry { + Key(&'static str, bool), + Deny(&'static str), +} + +impl Entry { + /// How `applied` remembers it. + fn id(self) -> String { + match self { + Entry::Key(key, _) => key.to_string(), + Entry::Deny(name) => format!("deny:{name}"), + } + } +} + +fn entries(trim: Trim) -> Vec { + match trim.effect() { + Effect::Keys(keys) => keys.iter().map(|(key, value)| Entry::Key(key, *value)).collect(), + Effect::Deny(names) => names.iter().map(|name| Entry::Deny(name)).collect(), + } +} + +fn present(settings: &Map, entry: Entry) -> bool { + match entry { + Entry::Key(key, value) => settings.get(key) == Some(&Value::Bool(value)), + Entry::Deny(name) => { + let list = settings.get("permissions").and_then(|p| p.get("deny")).and_then(Value::as_array); + list.is_some_and(|list| list.iter().any(|v| v.as_str() == Some(name))) + } + } +} + +fn add(settings: &mut Map, entry: Entry) { + match entry { + Entry::Key(key, value) => { + settings.insert(key.into(), Value::Bool(value)); + } + Entry::Deny(name) => { + let permissions = settings.entry("permissions").or_insert_with(|| json!({})); + if let Some(permissions) = permissions.as_object_mut() + && let Some(list) = permissions.entry("deny").or_insert_with(|| json!([])).as_array_mut() + { + list.push(Value::String(name.into())); + } + } + } +} + +fn remove(settings: &mut Map, entry: Entry) { + match entry { + Entry::Key(key, value) => { + if settings.get(key) == Some(&Value::Bool(value)) { + settings.remove(key); + } + } + Entry::Deny(name) => { + let Some(permissions) = settings.get_mut("permissions").and_then(Value::as_object_mut) else { return }; + if let Some(list) = permissions.get_mut("deny").and_then(Value::as_array_mut) { + list.retain(|v| v.as_str() != Some(name)); + if list.is_empty() { + permissions.remove("deny"); + } + } + if permissions.is_empty() { + settings.remove("permissions"); + } + } + } +} + +/// Put the trimmed items into `settings` and take out the ones Claudiu added earlier (`applied`) that are no longer +/// trimmed. A line the user had before Claudiu (a tool they denied themselves) is never recorded, so turning the trim +/// off leaves it. Returns what Claudiu now owns, to pass back next time. +pub fn apply(settings: &mut Map, trimmed: &[Trim], applied: &[String]) -> Vec { + let wanted: Vec = normalized(trimmed).into_iter().flat_map(entries).collect(); + let known: Vec = Trim::ALL.into_iter().flat_map(entries).collect(); + for entry in known.iter().filter(|e| applied.contains(&e.id()) && !wanted.contains(e)) { + remove(settings, *entry); + } + let mut owned = vec![]; + for entry in wanted { + let was_ours = applied.contains(&entry.id()); + if !present(settings, entry) { + add(settings, entry); + owned.push(entry.id()); + } else if was_ours { + owned.push(entry.id()); + } + } + owned +} + +/// `apply` to the `settings.json` at `path`, written only when something changed. A file that is not a JSON object is +/// never overwritten. +pub fn write_global(path: &std::path::Path, trimmed: &[Trim], applied: &[String]) -> std::io::Result> { + let text = match std::fs::read_to_string(path) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => "{}".into(), + Err(e) => return Err(e), + }; + let Ok(Value::Object(mut settings)) = serde_json::from_str(&text) else { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "settings.json is not a JSON object")); + }; + let before = settings.clone(); + let owned = apply(&mut settings, trimmed, applied); + if settings != before { + crate::datadir::write_atomic(path, &serde_json::to_string_pretty(&settings).map_err(std::io::Error::other)?)?; + } + Ok(owned) +} + +/// Where earlier versions wrote a settings file per session; only pruned now. +pub fn settings_dir() -> PathBuf { + crate::datadir::data_dir().join("settings") +} + +#[cfg(test)] +mod tests { + use super::Trim::*; + use super::*; + + fn object(v: Value) -> Map { + v.as_object().unwrap().clone() + } + + #[test] + fn a_flag_and_a_tool_group_give_the_flag_and_exactly_their_denies() { + let mut s = object(json!({ "model": "sonnet" })); + let owned = apply(&mut s, &[PlanMode, Workflows], &[]); + assert_eq!(Value::Object(s), json!({ "model": "sonnet", "disableWorkflows": true, "permissions": { "deny": ["EnterPlanMode", "ExitPlanMode"] } })); + assert_eq!(owned, ["disableWorkflows", "deny:EnterPlanMode", "deny:ExitPlanMode"]); + } + + #[test] + fn artifacts_are_turned_off_with_the_current_key_and_the_deprecated_one() { + let mut s = Map::new(); + apply(&mut s, &[Artifacts], &[]); + assert_eq!(Value::Object(s), json!({ "enableArtifact": false, "disableArtifact": true })); + } + + #[test] + fn turning_a_trim_off_takes_out_only_what_claudiu_added() { + let mut s = object(json!({ "permissions": { "deny": ["NotebookEdit"], "defaultMode": "auto" } })); + // The user already denied NotebookEdit; Claudiu adds the other two. + let owned = apply(&mut s, &[NotebookEdit, ScheduledTasks, Workflows], &[]); + assert_eq!(owned, ["disableWorkflows", "deny:CronCreate", "deny:CronDelete", "deny:CronList"], "the user's own deny is not recorded"); + let owned = apply(&mut s, &[], &owned); + assert!(owned.is_empty()); + assert_eq!(Value::Object(s), json!({ "permissions": { "deny": ["NotebookEdit"], "defaultMode": "auto" } })); + } + + #[test] + fn an_empty_deny_list_and_permissions_object_are_cleaned_up() { + let mut s = Map::new(); + let owned = apply(&mut s, &[SendMessage], &[]); + assert!(s.contains_key("permissions")); + apply(&mut s, &[], &owned); + assert!(s.is_empty()); + } + + #[test] + fn trimming_again_changes_nothing_and_keeps_ownership() { + let mut s = Map::new(); + let owned = apply(&mut s, &[BundledSkills], &[]); + let before = s.clone(); + assert_eq!(apply(&mut s, &[BundledSkills], &owned), owned); + assert_eq!(s, before); + } + + #[test] + fn the_file_keeps_the_users_key_order_and_is_not_rewritten_when_nothing_changes() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("settings.json"); + std::fs::write(&path, "{\n \"zeta\": 1,\n \"alpha\": 2\n}").unwrap(); + let owned = write_global(&path, &[Workflows], &[]).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.find("zeta").unwrap() < text.find("alpha").unwrap(), "keys keep their order: {text}"); + assert!(text.contains("disableWorkflows")); + let stamp = std::fs::metadata(&path).unwrap().modified().unwrap(); + write_global(&path, &[Workflows], &owned).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), stamp, "nothing to change, nothing written"); + } + + #[test] + fn a_settings_file_that_is_not_json_is_left_alone() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("settings.json"); + std::fs::write(&path, "{ not json").unwrap(); + assert!(write_global(&path, &[Workflows], &[]).is_err()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "{ not json"); + } + + #[test] + fn every_item_is_listed_once_in_the_page_groups() { + let listed: Vec = Trim::GROUPS.iter().flat_map(|(_, items)| items.iter().copied()).collect(); + assert_eq!(listed, Trim::ALL); + } +} diff --git a/src/claude/usage.rs b/src/claude/usage.rs index 35dba5a..17f304e 100644 --- a/src/claude/usage.rs +++ b/src/claude/usage.rs @@ -33,7 +33,8 @@ pub fn valid_model_name(name: &str) -> bool { !name.is_empty() && name.len() <= 60 && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) } -/// Ask the mod of a running session to change a setting: `auto_compact` (bool) or `advisor` (a model name or `off`). +/// Ask the mod of a running session to change a setting: `auto_compact` or `precompute_compact` (bool), `advisor` (a +/// model name or `off`), or `prompt` (a message for the session to send once it is idle). /// The file keeps the latest few commands, each with a number that only goes up, so none is lost if two come within /// the mod's one-second look and none is applied twice. pub fn send_ctl(file: &Path, key: &str, value: serde_json::Value) { @@ -68,6 +69,9 @@ pub struct Snapshot { /// The `/config` auto-compact switch. #[serde(default)] pub auto_compact: Option, + /// The `/config` "Precompute compaction" switch (background compaction); `None` while Claude Code does not offer it. + #[serde(default)] + pub precompute_compact: Option, /// The `advisorModel` setting (`opus`, `sonnet`, ...); `None` when the advisor is off. #[serde(default)] pub advisor: Option, @@ -107,7 +111,7 @@ mod tests { "context_fraction": 0.028, "context_tokens": 28062, "context_window": 1000000, "five_hour": {"utilization": 0.67, "resets_at": 1792659600, "seen_at": 1000}, "seven_day": {"utilization": 0.22, "resets_at": 1793167200, "seen_at": 1000}, - "auto_compact": true, "advisor": "opus", "advisor_active": "opus", "compact_at": 167000, "compacted_at": 1500 + "auto_compact": true, "precompute_compact": false, "advisor": "opus", "advisor_active": "opus", "compact_at": 167000, "compacted_at": 1500 }"#; #[test] @@ -139,7 +143,7 @@ mod tests { assert_eq!(s.seven_day.as_ref().unwrap().resets_at, Some(1793167200)); assert_eq!((s.context_tokens, s.context_window), (Some(28062), Some(1_000_000))); assert_eq!((s.auto_compact, s.advisor.as_deref(), s.advisor_active.as_deref(), s.compact_at), (Some(true), Some("opus"), Some("opus"), Some(167_000))); - assert_eq!(s.compacted_at, Some(1500)); + assert_eq!((s.compacted_at, s.precompute_compact), (Some(1500), Some(false))); } #[test] diff --git a/src/files.rs b/src/files.rs new file mode 100644 index 0000000..93d4708 --- /dev/null +++ b/src/files.rs @@ -0,0 +1,857 @@ +//! The files the editor shows: a folder listed without what Git ignores and with Git's changes marked, and a file read +//! as text when the editor can hold it. No GPUI here; callers run both off the UI thread. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use git2::{Repository, Status, StatusOptions}; + +use crate::platform::path_key; + +/// A file, or a folder with what it holds (folders first, then by name). +#[derive(Clone, Debug, PartialEq)] +pub struct Node { + pub path: PathBuf, + pub name: String, + /// `None` for a file. + pub children: Option>, +} + +pub struct Listing { + /// The folder as listed (long, canonical form), which every `Node::path` starts with. + pub root: PathBuf, + pub nodes: Vec, + /// By `path_key`: files Git sees as changed or new, and the folders above them. + pub changed: HashMap, + /// The walk stopped at its limit, so some files are missing. + pub truncated: bool, +} + +/// List `root`, at most `limit` entries. Skips `.git` and whatever the repository ignores. +pub fn list(root: &Path, limit: usize) -> Listing { + let root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let repo = Repository::discover(&root).ok(); + let workdir = repo.as_ref().and_then(|r| r.workdir()).map(Path::to_path_buf); + let ignored = |path: &Path| match (&repo, &workdir) { + (Some(repo), Some(wd)) => path.strip_prefix(wd).is_ok_and(|rel| repo.is_path_ignored(rel).unwrap_or(false)), + _ => false, + }; + let mut budget = limit; + let nodes = walk(&root, &ignored, &mut budget); + let changed = match (&repo, &workdir) { + (Some(repo), Some(wd)) => changed(repo, wd, &root), + _ => HashMap::new(), + }; + Listing { root, nodes, changed, truncated: budget == 0 } +} + +fn walk(dir: &Path, ignored: &dyn Fn(&Path) -> bool, budget: &mut usize) -> Vec { + let Ok(read) = std::fs::read_dir(dir) else { return vec![] }; + let mut entries: Vec<(PathBuf, String, bool)> = read + .flatten() + .map(|e| (e.path(), e.file_name().to_string_lossy().into_owned(), e.file_type().is_ok_and(|t| t.is_dir()))) + .filter(|(path, name, _)| name != ".git" && !ignored(path)) + .collect(); + entries.sort_by_cached_key(|(_, name, is_dir)| (!is_dir, name.to_lowercase())); + let mut nodes = Vec::new(); + for (path, name, is_dir) in entries { + if *budget == 0 { + break; + } + *budget -= 1; + if !is_dir { + nodes.push(Node { path, name, children: None }); + continue; + } + let children = walk(&path, ignored, budget); + nodes.push(Node { path, name, children: Some(children) }); + } + nodes +} + +/// What Git sees in a file since the last commit, staged or not. A folder takes the strongest change inside it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Change { + /// New, whether untracked or staged. + Added, + /// Edited, renamed or deleted. + Modified, +} + +/// Changed and new files under `root`, and every folder between them and `root`. +fn changed(repo: &Repository, workdir: &Path, root: &Path) -> HashMap { + let mut opts = StatusOptions::new(); + opts.include_untracked(true).recurse_untracked_dirs(true).include_ignored(false); + let Ok(statuses) = repo.statuses(Some(&mut opts)) else { return HashMap::new() }; + let under_root = format!("{}/", path_key(root)); + let mut marks = HashMap::new(); + for entry in statuses.iter().filter(|s| !s.status().is_ignored()) { + let Ok(path) = entry.path().map(|p| workdir.join(p)) else { continue }; + let change = if entry.status().intersects(Status::WT_NEW | Status::INDEX_NEW) { Change::Added } else { Change::Modified }; + for at in path.ancestors() { + let key = path_key(at); + if !key.starts_with(&under_root) { + break; + } + // Its folders already carry at least this much. + if marks.get(&key).is_some_and(|have| *have >= change) { + break; + } + marks.insert(key, change); + } + } + marks +} + +/// What opening a file gives the editor. +#[derive(Debug, PartialEq)] +pub enum Contents { + /// The editor gets the text as `format` describes, and `save` turns it back. + Text { text: String, format: Format, stamp: Stamp }, + /// Over `MAX_BYTES` or `MAX_LINES`: the editor would stall on it. + TooLarge, + /// Not UTF-8 text (binary, or another encoding). + NotText, +} + +/// The editor widget handles text "up to about 50K lines" (gpui-base's own note). +pub const MAX_LINES: usize = 50_000; +pub const MAX_BYTES: u64 = 8 * 1024 * 1024; + +/// A file's text exactly as stored, when the editor would open it. +fn read_stored(path: &Path, meta: &std::fs::Metadata) -> std::io::Result> { + if meta.len() > MAX_BYTES { + return Ok(Err(Contents::TooLarge)); + } + let bytes = std::fs::read(path)?; + if bytes.iter().take(8000).any(|b| *b == 0) { + return Ok(Err(Contents::NotText)); + } + let Ok(text) = String::from_utf8(bytes) else { return Ok(Err(Contents::NotText)) }; + if text.lines().count() > MAX_LINES { + return Ok(Err(Contents::TooLarge)); + } + Ok(Ok(text)) +} + +pub fn read(path: &Path) -> std::io::Result { + let meta = std::fs::metadata(path)?; + // Taken before reading: a write that lands in between shows up as a change on the next check. + let stamp = Stamp::of(&meta); + let text = match read_stored(path, &meta)? { + Ok(text) => text, + Err(refused) => return Ok(refused), + }; + let lf = text.matches('\n').count(); + // Mixed line ends are left as they are, so saving changes only what was edited. + let crlf = lf > 0 && text.matches("\r\n").count() == lf; + let text = if crlf { text.replace("\r\n", "\n") } else { text }; + let (text, tabs) = match untab(&text) { + Some((shown, indents)) => (shown, Some(std::sync::Arc::new(indents))), + None => (text, None), + }; + Ok(Contents::Text { text, format: Format { crlf, tabs }, stamp }) +} + +/// How a file's text differs from what the editor shows. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Format { + /// Every line ended in `\r\n`; the editor has `\n`. + pub crlf: bool, + /// The file is indented with tabs; the editor has spaces for each, because it draws a tab with no width. + /// `None` for a file shown as it is. + pub tabs: Option>, +} + +/// How the editor shows a file with tabs, and what saving needs to give it back (see `untab`). +#[derive(Debug, Default, PartialEq)] +pub struct Indents { + /// Most indented lines use tabs: new indents save as tabs too. Otherwise they stay spaces. + pub hard: bool, + /// The lines that saving gives back as they were, by how the editor shows them. + kept: HashMap, +} + +#[derive(Debug, PartialEq)] +enum Kept { + /// Every line that looks like this was this one. + One(String), + /// Different lines look the same (`\ta` and four spaces and `a`): each occurrence takes the next one, in file order. + InOrder(Vec), +} + +/// Spaces per tab while a file is in the editor. +pub const TAB_WIDTH: usize = 4; + +/// A file with tab-indented lines, as the editor shows it, because the editor draws a tab with no width: each tab as +/// spaces (those in a line's indent `TAB_WIDTH` each, the others up to the next multiple of `TAB_WIDTH`). Lines that +/// `ruled` would not give back as they were (tabs after the indent, spaces after the tabs to align, a template string +/// indented with spaces) are remembered, so they save unchanged until edited; an edited line keeps only the tabs in its +/// indent, and only in a file indented mostly with tabs. `None`, and the file is shown as it is, when no line is indented +/// with a tab (so a tab-separated table is never rewritten). +fn untab(text: &str) -> Option<(String, Indents)> { + fn indent(l: &str) -> &str { + &l[..l.len() - l.trim_start_matches([' ', '\t']).len()] + } + let tabbed = text.lines().filter(|l| indent(l).contains('\t')).count(); + if tabbed == 0 { + return None; + } + let space_indented = text.lines().filter(|l| indent(l).len() >= TAB_WIDTH && !indent(l).contains('\t')).count(); + let hard = tabbed >= space_indented; + let mut shown = String::with_capacity(text.len()); + let mut originals: HashMap> = HashMap::new(); + for line in text.split_inclusive('\n') { + let (body, end) = line.strip_suffix('\n').map_or((line, ""), |b| (b, "\n")); + let spaced = spaced(body); + shown.push_str(&spaced); + shown.push_str(end); + originals.entry(spaced).or_default().push(body); + } + let mut kept = HashMap::new(); + for (spaced, bodies) in originals { + if bodies.iter().all(|b| *b == bodies[0]) { + if ruled(&spaced, hard) != bodies[0] { + kept.insert(spaced, Kept::One(bodies[0].to_string())); + } + } else { + kept.insert(spaced, Kept::InOrder(bodies.into_iter().map(String::from).collect())); + } + } + Some((shown, Indents { hard, kept })) +} + +/// The editor's text back as the file: lines `untab` remembered as they were, every other one by `ruled`. +fn retab(text: &str, indents: &Indents) -> String { + let mut out = String::with_capacity(text.len()); + let mut taken: HashMap<&str, usize> = HashMap::new(); + for line in text.split_inclusive('\n') { + let (body, end) = line.strip_suffix('\n').map_or((line, ""), |b| (b, "\n")); + match indents.kept.get(body) { + Some(Kept::One(original)) => out.push_str(original), + Some(Kept::InOrder(originals)) => { + let n = taken.entry(body).or_default(); + out.push_str(originals.get(*n).map_or_else(|| ruled(body, indents.hard), |o| o.clone()).as_str()); + *n += 1; + } + None => out.push_str(&ruled(body, indents.hard)), + } + out.push_str(end); + } + out +} + +/// One line with each tab shown as spaces. +fn spaced(line: &str) -> String { + let rest = line.trim_start_matches([' ', '\t']); + let indent = &line[..line.len() - rest.len()]; + let mut out: String = indent.chars().map(|c| if c == '\t' { " ".repeat(TAB_WIDTH) } else { " ".into() }).collect(); + let mut column = out.chars().count(); + for c in rest.chars() { + if c == '\t' { + let width = TAB_WIDTH - column % TAB_WIDTH; + out.push_str(&" ".repeat(width)); + column += width; + } else { + out.push(c); + column += 1; + } + } + out +} + +/// One line with `TAB_WIDTH` leading spaces to a tab when the file is `hard` (indented with tabs), the rest staying spaces. +fn ruled(line: &str, hard: bool) -> String { + if !hard { + return line.to_string(); + } + let rest = line.trim_start_matches(' '); + let spaces = line.len() - rest.len(); + "\t".repeat(spaces / TAB_WIDTH) + &" ".repeat(spaces % TAB_WIDTH) + rest +} + +/// When a file was last written and how long it was, to notice a change made by someone else (usually Claude). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Stamp { + modified: Option, + len: u64, +} + +impl Stamp { + fn of(meta: &std::fs::Metadata) -> Self { + Self { modified: meta.modified().ok(), len: meta.len() } + } +} + +/// `None` when the file is gone (or can't be looked at). +pub fn stamp(path: &Path) -> Option { + std::fs::metadata(path).ok().map(|m| Stamp::of(&m)) +} + +#[derive(Debug)] +pub enum SaveError { + /// The file changed on disk since `expected`; nothing was written. + Changed, + Io(std::io::Error), +} + +/// Write `text` over `path` in place (keeping its permissions and links), turned back into the file's `format`. With +/// `expected`, refuse when the file on disk no longer matches it. Returns the file's new stamp. +pub fn save(path: &Path, text: &str, format: Format, expected: Option) -> Result { + if expected.is_some() && stamp(path) != expected { + return Err(SaveError::Changed); + } + let text = match &format.tabs { + Some(indents) => std::borrow::Cow::Owned(retab(text, indents)), + None => std::borrow::Cow::Borrowed(text), + }; + let text = if format.crlf { std::borrow::Cow::Owned(text.replace('\n', "\r\n")) } else { text }; + std::fs::write(path, text.as_bytes()).map_err(SaveError::Io)?; + stamp(path).ok_or_else(|| SaveError::Io(std::io::ErrorKind::NotFound.into())) +} + +/// The highlighter's name for a file's language, from its extension; `None` shows it as plain text. +pub fn language(path: &Path) -> Option<&'static str> { + let ext = path.extension()?.to_str()?.to_ascii_lowercase(); + Some(match ext.as_str() { + "rs" => "rust", + "ts" | "mts" | "cts" => "typescript", + "tsx" => "tsx", + "js" | "mjs" | "cjs" | "jsx" => "javascript", + "json" | "jsonc" => "json", + "toml" => "toml", + "yaml" | "yml" => "yaml", + "md" | "markdown" | "mdx" => "markdown", + "html" | "htm" => "html", + "css" | "scss" => "css", + "sh" | "bash" | "zsh" => "bash", + "gleam" => "gleam", + _ => return None, + }) +} + +/// Why `name` can't name a new file or a renamed one; `Ok` when it can. One entry, no path: a name that Windows, +/// macOS or Linux would refuse or change is refused everywhere, so a project stays usable on all three. +pub fn check_name(name: &str) -> Result<(), String> { + const RESERVED: [&str; 4] = ["con", "prn", "aux", "nul"]; + let stem = name.split('.').next().unwrap_or("").to_ascii_lowercase(); + let device = RESERVED.contains(&stem.as_str()) + || (stem.len() == 4 && (stem.starts_with("com") || stem.starts_with("lpt")) && stem.ends_with(|c: char| c.is_ascii_digit())); + if name.trim().is_empty() { + Err("Enter a name.".into()) + } else if name == "." || name == ".." { + Err("That name is taken by the system.".into()) + } else if let Some(c) = name.chars().find(|c| matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control()) { + Err(format!("A name can't contain {}.", if c.is_control() { "control characters".to_string() } else { format!("“{c}”") })) + } else if name.ends_with('.') || name.ends_with(' ') || name.starts_with(' ') { + Err("A name can't start with a space or end with a space or a dot.".into()) + } else if device { + Err(format!("“{name}” is a device name on Windows.")) + } else { + Ok(()) + } +} + +/// `path` in its canonical form, with its last part left as it is (so a link is the link, not what it points to), when it +/// lies inside `root` (the folder itself only with `allow_root`); an error otherwise. +fn inside(root: &Path, path: &Path, allow_root: bool) -> std::io::Result { + let root = dunce::canonicalize(root)?; + let path = match (path.parent(), path.file_name()) { + (Some(parent), Some(name)) => dunce::canonicalize(parent)?.join(name), + _ => dunce::canonicalize(path)?, + }; + let is_root = path_key(&path) == path_key(&root); + if (is_root && allow_root) || (!is_root && crate::platform::is_same_or_under(&path, &root)) { + Ok(path) + } else { + Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "That is outside the session's folder.")) + } +} + +fn bad_name(why: String) -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::InvalidInput, why) +} + +/// Create the empty file `name` in folder `dir` (inside `root`); never over an existing one. +pub fn create_file(root: &Path, dir: &Path, name: &str) -> std::io::Result { + check_name(name).map_err(bad_name)?; + let path = inside(root, dir, true)?.join(name); + std::fs::OpenOptions::new().write(true).create_new(true).open(&path)?; + Ok(path) +} + +/// Create the empty folder `name` in folder `dir` (inside `root`); never over an existing file or folder. +pub fn create_folder(root: &Path, dir: &Path, name: &str) -> std::io::Result { + check_name(name).map_err(bad_name)?; + let path = inside(root, dir, true)?.join(name); + std::fs::create_dir(&path)?; + Ok(path) +} + +/// Rename `path` (inside `root`) to `name` in the same folder; never over another file. A change of case alone is +/// allowed where the file system ignores case. +pub fn rename(root: &Path, path: &Path, name: &str) -> std::io::Result { + check_name(name).map_err(bad_name)?; + let from = inside(root, path, false)?; + let to = from.with_file_name(name); + // `fs::rename` replaces an existing file on macOS and Linux, so look first. + if to.symlink_metadata().is_ok() && !same_file(&to, &from) { + return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, format!("“{name}” already exists."))); + } + std::fs::rename(&from, &to)?; + Ok(to) +} + +/// Whether two paths name the same file, as a change of case does where the file system ignores case. By inode on +/// macOS and Linux, where `path_key` keeps case although macOS usually ignores it. +fn same_file(a: &Path, b: &Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + match (a.symlink_metadata(), b.symlink_metadata()) { + (Ok(a), Ok(b)) => (a.dev(), a.ino()) == (b.dev(), b.ino()), + _ => false, + } + } + #[cfg(not(unix))] + { + path_key(a) == path_key(b) + } +} + +/// Delete the file or folder `path` (inside `root`, never `root` itself), a folder with everything in it. A link is +/// removed, not what it points to. +pub fn delete(root: &Path, path: &Path) -> std::io::Result<()> { + let path = inside(root, path, false)?; + if path.symlink_metadata()?.is_dir() { std::fs::remove_dir_all(&path) } else { std::fs::remove_file(&path) } +} + +/// Every file in a listing, folders left out. +pub fn files_of(nodes: &[Node]) -> Vec { + let mut out = Vec::new(); + for n in nodes { + match &n.children { + Some(children) => out.extend(files_of(children)), + None => out.push(n.path.clone()), + } + } + out +} + +/// Quick open: the indexes of `paths` (relative, `/`-separated) that hold the letters of `query` in order, best first. +/// Matches in the file name beat matches in folders, then letters that follow each other, then shorter paths. +pub fn rank_paths(query: &str, paths: &[String], limit: usize) -> Vec { + let query: Vec = query.to_lowercase().chars().filter(|c| !c.is_whitespace()).collect(); + let mut scored: Vec<(i64, usize)> = paths.iter().enumerate().filter_map(|(i, p)| fuzzy_score(&query, p).map(|s| (s, i))).collect(); + scored.sort_by_key(|(score, i)| (std::cmp::Reverse(*score), paths[*i].len(), *i)); + scored.into_iter().take(limit).map(|(_, i)| i).collect() +} + +fn fuzzy_score(query: &[char], path: &str) -> Option { + let lower: Vec = path.to_lowercase().chars().collect(); + let name_start = lower.iter().rposition(|c| *c == '/').map_or(0, |i| i + 1); + let (mut score, mut at, mut prev) = (0i64, 0usize, None::); + for q in query { + let found = at + lower[at..].iter().position(|c| c == q)?; + score += 1; + if found >= name_start { + score += 4; + } + if prev.is_some_and(|p| p + 1 == found) { + score += 3; + } + prev = Some(found); + at = found + 1; + } + Some(score) +} + +/// A line that holds the searched text. +#[derive(Clone, Debug, PartialEq)] +pub struct Hit { + pub path: PathBuf, + /// 0-based. + pub line: usize, + pub text: String, +} + +/// Find in files: lines of `files` that contain `query`, ignoring case, at most `limit`. Files `read` refuses are skipped. +pub fn search(files: &[PathBuf], query: &str, limit: usize, stale: &dyn Fn() -> bool) -> Vec { + let needle = query.to_lowercase(); + let mut hits = Vec::new(); + if needle.is_empty() { + return hits; + } + for path in files { + // A newer query replaced this one: its hits would be thrown away. + if stale() { + return hits; + } + // Line numbers and trimmed lines come out the same as in the editor, which only changes line ends and indents. + let Ok(Ok(text)) = std::fs::metadata(path).and_then(|meta| read_stored(path, &meta)) else { continue }; + for (line, l) in text.lines().enumerate().filter(|(_, l)| l.to_lowercase().contains(&needle)) { + if hits.len() == limit { + return hits; + } + hits.push(Hit { path: path.clone(), line, text: l.trim().chars().take(200).collect() }); + } + } + hits +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn names(nodes: &[Node]) -> Vec { + nodes.iter().map(|n| n.name.clone()).collect() + } + + fn find<'a>(nodes: &'a [Node], name: &str) -> &'a Node { + nodes.iter().find(|n| n.name == name).unwrap_or_else(|| panic!("{name} missing from {:?}", names(nodes))) + } + + fn commit_all(repo: &Repository) { + let mut index = repo.index().unwrap(); + index.add_all(["*"], git2::IndexAddOption::DEFAULT, None).unwrap(); + index.write().unwrap(); + let tree = repo.find_tree(index.write_tree().unwrap()).unwrap(); + let sig = git2::Signature::now("t", "t@t").unwrap(); + repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[]).unwrap(); + } + + #[test] + fn lists_folders_first_without_ignored_files_or_git() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fs::create_dir_all(root.join("src")).unwrap(); + fs::create_dir_all(root.join("target/debug")).unwrap(); + fs::create_dir_all(root.join("empty")).unwrap(); + fs::write(root.join("src/main.rs"), "fn main() {}").unwrap(); + fs::write(root.join("target/debug/app"), "bin").unwrap(); + fs::write(root.join(".gitignore"), "target/\n*.log\n").unwrap(); + fs::write(root.join("debug.log"), "x").unwrap(); + fs::write(root.join("README.md"), "# hi").unwrap(); + Repository::init(root).unwrap(); + + let listing = list(root, 1000); + assert_eq!(names(&listing.nodes), [String::from("empty"), "src".into(), ".gitignore".into(), "README.md".into()]); + assert_eq!(find(&listing.nodes, "empty").children, Some(vec![]), "an empty folder is still a folder"); + assert_eq!(names(find(&listing.nodes, "src").children.as_ref().unwrap()), ["main.rs"]); + assert!(find(&listing.nodes, "README.md").children.is_none()); + assert!(!listing.truncated); + } + + #[test] + fn marks_changed_and_new_files_and_their_folders() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + fs::create_dir_all(root.join("src/deep")).unwrap(); + fs::create_dir_all(root.join("docs")).unwrap(); + fs::write(root.join("src/deep/a.rs"), "a").unwrap(); + fs::write(root.join("docs/b.md"), "b").unwrap(); + let repo = Repository::init(&root).unwrap(); + commit_all(&repo); + fs::write(root.join("src/deep/a.rs"), "changed").unwrap(); + fs::write(root.join("new.txt"), "new").unwrap(); + + fs::write(root.join("docs/c.md"), "new").unwrap(); + let mut index = repo.index().unwrap(); + index.add_path(Path::new("docs/c.md")).unwrap(); + index.write().unwrap(); + fs::create_dir_all(root.join("fresh")).unwrap(); + fs::write(root.join("fresh/d.md"), "new").unwrap(); + + let changed = list(&root, 1000).changed; + let mark = |p: &str| changed.get(&path_key(&root.join(p))).copied(); + for p in ["src/deep/a.rs", "src/deep", "src"] { + assert_eq!(mark(p), Some(Change::Modified), "{p}"); + } + for p in ["new.txt", "docs/c.md", "docs", "fresh/d.md", "fresh"] { + assert_eq!(mark(p), Some(Change::Added), "{p}: untracked and staged files are both new"); + } + assert_eq!(mark("docs/b.md"), None); + assert_eq!(mark(""), None, "the listed folder itself"); + } + + #[test] + fn a_plain_folder_is_listed_and_the_limit_stops_the_walk() { + let tmp = tempfile::tempdir().unwrap(); + for i in 0..10 { + fs::write(tmp.path().join(format!("f{i}.txt")), "x").unwrap(); + } + assert_eq!(list(tmp.path(), 1000).nodes.len(), 10); + let capped = list(tmp.path(), 4); + assert_eq!(capped.nodes.len(), 4); + assert!(capped.truncated); + } + + #[test] + fn reads_text_and_refuses_what_the_editor_cannot_hold() { + let tmp = tempfile::tempdir().unwrap(); + let p = |n: &str| tmp.path().join(n); + fs::write(p("a.rs"), "fn main() {}\n").unwrap(); + fs::write(p("bin"), [0x7f, b'E', b'L', b'F', 0, 0, 1]).unwrap(); + fs::write(p("latin1.txt"), [b'c', b'a', b'f', 0xe9]).unwrap(); + fs::write(p("long.txt"), "x\n".repeat(MAX_LINES + 1)).unwrap(); + assert!(matches!(read(&p("a.rs")).unwrap(), Contents::Text { text, format: Format { crlf: false, tabs: None }, .. } if text == "fn main() {}\n")); + assert_eq!(read(&p("bin")).unwrap(), Contents::NotText); + assert_eq!(read(&p("latin1.txt")).unwrap(), Contents::NotText); + assert_eq!(read(&p("long.txt")).unwrap(), Contents::TooLarge); + assert!(read(&p("missing")).is_err()); + } + #[test] + fn quick_open_prefers_the_file_name_and_letters_in_a_row() { + let paths: Vec = ["src/app/mod.rs", "src/main.rs", "README.md", "src/panels/sidebar.rs", "web/src/pages/index.astro", "modules/a.rs"].map(String::from).into(); + let ranked = |q: &str| rank_paths(q, &paths, 10).into_iter().map(|i| paths[i].as_str()).collect::>(); + assert_eq!(ranked("main")[0], "src/main.rs"); + assert_eq!(ranked("side")[0], "src/panels/sidebar.rs"); + assert_eq!(ranked("mod")[0], "src/app/mod.rs", "a match in the file name beats a shorter path"); + assert_eq!(ranked("SRCMOD"), ["src/app/mod.rs"], "case is ignored and letters may be apart"); + assert!(ranked("zzz").is_empty()); + assert_eq!(ranked("").len(), paths.len(), "an empty query lists everything"); + assert_eq!(rank_paths("s", &paths, 2).len(), 2); + } + + #[test] + fn find_in_files_reports_the_lines_the_editor_shows() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join("tabs.rs"); + fs::write(&file, "fn a() { + let total = 1; +} +").unwrap(); + let hits = search(&[file.clone()], "total", 100, &|| false); + assert_eq!(hits, [Hit { path: file.clone(), line: 1, text: "let total = 1;".into() }]); + let Ok(Contents::Text { text, .. }) = read(&file) else { panic!("readable") }; + assert_eq!(text.lines().nth(hits[0].line).unwrap().trim(), hits[0].text, "the editor has the same line there"); + } + + #[test] + fn find_in_files_lists_matching_lines_and_skips_what_it_cannot_read() { + let tmp = tempfile::tempdir().unwrap(); + let p = |n: &str| tmp.path().join(n); + fs::write(p("a.rs"), "fn main() { + let Total = 1; +} +").unwrap(); + fs::write(p("b.md"), "the total +nothing +").unwrap(); + fs::write(p("bin"), [b't', b'o', b't', b'a', b'l', 0]).unwrap(); + let files = vec![p("a.rs"), p("b.md"), p("bin")]; + let hits = search(&files, "total", 100, &|| false); + assert_eq!(hits, [ + Hit { path: p("a.rs"), line: 1, text: "let Total = 1;".into() }, + Hit { path: p("b.md"), line: 0, text: "the total".into() }, + ]); + assert_eq!(search(&files, "total", 1, &|| false).len(), 1); + assert!(search(&files, "", 100, &|| false).is_empty()); + assert!(search(&files, "total", 100, &|| true).is_empty(), "a stale search reads nothing"); + } + + #[test] + fn languages_come_from_the_extension() { + for (file, lang) in [("src/main.rs", Some("rust")), ("a.TS", Some("typescript")), ("app.tsx", Some("tsx")), ("x.mjs", Some("javascript")), ("Cargo.toml", Some("toml")), ("ci.yml", Some("yaml")), ("README.md", Some("markdown")), ("app.gleam", Some("gleam")), ("run.sh", Some("bash")), ("notes.txt", None), ("Makefile", None)] { + assert_eq!(language(Path::new(file)), lang, "{file}"); + } + } + + #[test] + fn files_of_a_listing_leaves_folders_out() { + let f = |n: &str| Node { path: n.into(), name: n.into(), children: None }; + let nodes = vec![Node { path: "src".into(), name: "src".into(), children: Some(vec![f("src/a.rs")]) }, f("b.md")]; + assert_eq!(files_of(&nodes), [PathBuf::from("src/a.rs"), PathBuf::from("b.md")]); + } + + #[test] + fn crlf_files_are_edited_with_lf_and_saved_back_with_crlf() { + let tmp = tempfile::tempdir().unwrap(); + let p = tmp.path().join("win.txt"); + fs::write(&p, "a\r\nb\r\n").unwrap(); + let Contents::Text { text, format, stamp: read_stamp } = read(&p).unwrap() else { panic!("not text") }; + assert_eq!((text.as_str(), format.crlf), ("a\nb\n", true)); + save(&p, "a\nb\nc\n", format, Some(read_stamp)).unwrap(); + assert_eq!(fs::read_to_string(&p).unwrap(), "a\r\nb\r\nc\r\n"); + + fs::write(&p, "a\r\nb\n").unwrap(); + let Contents::Text { text, format, .. } = read(&p).unwrap() else { panic!("not text") }; + assert_eq!((text.as_str(), format.crlf), ("a\r\nb\n", false), "mixed line ends are left alone"); + } + + #[test] + fn tab_indents_are_edited_as_spaces_and_saved_back_as_tabs() { + let tmp = tempfile::tempdir().unwrap(); + let p = tmp.path().join("a.ts"); + let file = "class A {\r\n\t/**\r\n\t * Doc.\r\n\t */\r\n\tf() {\r\n\t\treturn\t1;\r\n\t}\r\n}\r\n"; + fs::write(&p, file).unwrap(); + let Contents::Text { text, format, stamp: s } = read(&p).unwrap() else { panic!("not text") }; + assert!(format.crlf && format.tabs.is_some()); + assert_eq!(text, "class A {\n /**\n * Doc.\n */\n f() {\n return 1;\n }\n}\n", "every tab becomes spaces"); + let s = save(&p, &text, format.clone(), Some(s)).unwrap(); + assert_eq!(fs::read_to_string(&p).unwrap(), file, "an unedited file saves unchanged"); + save(&p, "a\n b\n", format, Some(s)).unwrap(); + assert_eq!(fs::read_to_string(&p).unwrap(), "a\r\n\t b\r\n", "new indents become tabs too"); + + // Tab-indented files with lines whose indent doesn't turn back by the rule: shown without tabs, saved unchanged. + let jsx = "export function App() {\n\treturn (\n\t\t\n\t\t\t go()}\n\t\t/>\n\t);\n}\nconst css = `\n color: red;\n`;\n"; + for (file, why) in [(jsx, "aligned with spaces after the tabs, and a template string indented with spaces"), ("\ta\n b\n", "a line indented with spaces"), ("\t a\n", "spaces after the tabs"), (" \ta\n", "a tab after spaces")] { + fs::write(&p, file).unwrap(); + let Contents::Text { text, format, stamp: s } = read(&p).unwrap() else { panic!("not text") }; + assert!(format.tabs.is_some() && !text.contains('\t'), "{why}: shown without tabs: {text:?}"); + save(&p, &text, format, Some(s)).unwrap(); + assert_eq!(fs::read_to_string(&p).unwrap(), file, "{why}: saved unchanged"); + } + // An edited line takes the rule; the lines around it keep their own indents. + fs::write(&p, jsx).unwrap(); + let Contents::Text { text, format, stamp: s } = read(&p).unwrap() else { panic!("not text") }; + save(&p, &text.replace("return (", "return ("), format, Some(s)).unwrap(); + assert_eq!(fs::read_to_string(&p).unwrap(), jsx.replace("return (", "return (")); + + for (file, why) in [("a\n b\n", "no tabs"), ("a\tb\n c\n", "tabs only inside lines")] { + fs::write(&p, file).unwrap(); + let Contents::Text { text, format, .. } = read(&p).unwrap() else { panic!("not text") }; + assert_eq!((text.as_str(), format.tabs.is_none()), (file, true), "{why}: left alone"); + } + } + + #[test] + fn tabs_after_the_indent_are_shown_too() { + let tmp = tempfile::tempdir().unwrap(); + let p = tmp.path().join("a.go"); + for (file, shown, why) in [ + ("type A struct {\n\tName\tstring\n\tId\tint\n}\n", "type A struct {\n Name string\n Id int\n}\n", "tabs that align"), + ] { + fs::write(&p, file).unwrap(); + let Contents::Text { text, format, stamp: s } = read(&p).unwrap() else { panic!("not text") }; + assert_eq!(text, shown, "{why}"); + save(&p, &text, format, Some(s)).unwrap(); + assert_eq!(fs::read_to_string(&p).unwrap(), file, "{why}: saved unchanged"); + } + // A line edited by hand keeps the tabs of its indent, not the ones inside it. + fs::write(&p, "type A struct {\n\tName\tstring\n}\n").unwrap(); + let Contents::Text { format, stamp: s, .. } = read(&p).unwrap() else { panic!("not text") }; + save(&p, "type A struct {\n Name int\n}\n", format, Some(s)).unwrap(); + assert_eq!(fs::read_to_string(&p).unwrap(), "type A struct {\n\tName int\n}\n"); + // Lines that look the same but differ, and a file mostly indented with spaces, still show their tabs and save as they were. + for file in ["\t\ta\n\t a\n \t\ta\n", "a\n b\n c\n\td\n e\n"] { + fs::write(&p, file).unwrap(); + let Contents::Text { text, format, stamp: s } = read(&p).unwrap() else { panic!("not text") }; + assert!(!text.contains('\t'), "{text:?}"); + save(&p, &text, format, Some(s)).unwrap(); + assert_eq!(fs::read_to_string(&p).unwrap(), file); + } + // Without tab indents, tabs are the file's data (a table): it is shown and saved as it is. + fs::write(&p, "a\tb\nc\td\n").unwrap(); + let Contents::Text { text, format, .. } = read(&p).unwrap() else { panic!("not text") }; + assert_eq!((text.as_str(), format.tabs.is_none()), ("a\tb\nc\td\n", true)); + } + + #[test] + fn saving_refuses_to_overwrite_a_file_changed_on_disk() { + let tmp = tempfile::tempdir().unwrap(); + let p = tmp.path().join("a.rs"); + fs::write(&p, "one\n").unwrap(); + let Contents::Text { stamp: read_stamp, .. } = read(&p).unwrap() else { panic!("not text") }; + fs::write(&p, "changed by Claude\n").unwrap(); + assert!(matches!(save(&p, "mine\n", Format::default(), Some(read_stamp)), Err(SaveError::Changed))); + assert_eq!(fs::read_to_string(&p).unwrap(), "changed by Claude\n", "nothing was written"); + + let newer = save(&p, "mine\n", Format::default(), None).unwrap(); + assert_eq!(fs::read_to_string(&p).unwrap(), "mine\n", "without an expected stamp it overwrites"); + assert_eq!(stamp(&p), Some(newer)); + fs::remove_file(&p).unwrap(); + assert_eq!(stamp(&p), None); + } + + #[test] + fn a_name_is_one_plain_entry() { + for good in ["main.rs", ".env", "a b.txt", "notes"] { + assert!(check_name(good).is_ok(), "{good}"); + } + for bad in ["", " ", ".", "..", "a/b", "a\\b", "x:y", "what?", "nul\0", "trailing.", "CON", "nul.txt", "com1.rs"] { + assert!(check_name(bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn creates_a_file_and_never_overwrites_one() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let root = root.as_path(); + fs::create_dir(root.join("src")).unwrap(); + let made = create_file(root, &root.join("src"), "new.rs").unwrap(); + assert_eq!(made, root.join("src/new.rs")); + assert_eq!(fs::read_to_string(&made).unwrap(), ""); + + fs::write(&made, "keep").unwrap(); + assert_eq!(create_file(root, &root.join("src"), "new.rs").unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(fs::read_to_string(&made).unwrap(), "keep"); + assert!(create_file(root, &root.join("src"), "../escape.rs").is_err()); + let outside = tempfile::tempdir().unwrap(); + assert!(create_file(root, outside.path(), "x.rs").is_err(), "only inside the session folder"); + } + + #[test] + fn creates_a_folder_and_never_over_anything() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let root = root.as_path(); + let made = create_folder(root, root, "lib").unwrap(); + assert_eq!(made, root.join("lib")); + assert!(made.is_dir()); + + fs::write(made.join("keep.rs"), "keep").unwrap(); + assert_eq!(create_folder(root, root, "lib").unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(fs::read_to_string(made.join("keep.rs")).unwrap(), "keep"); + fs::write(root.join("file"), "").unwrap(); + assert_eq!(create_folder(root, root, "file").unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + assert!(create_folder(root, root, "a/b").is_err()); + let outside = tempfile::tempdir().unwrap(); + assert!(create_folder(root, outside.path(), "x").is_err(), "only inside the session folder"); + } + + #[test] + fn renames_in_place_and_never_over_another_file() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let root = root.as_path(); + fs::create_dir(root.join("src")).unwrap(); + fs::write(root.join("src/a.rs"), "a").unwrap(); + fs::write(root.join("src/b.rs"), "b").unwrap(); + + let moved = rename(root, &root.join("src/a.rs"), "c.rs").unwrap(); + assert_eq!(moved, root.join("src/c.rs")); + assert_eq!(fs::read_to_string(&moved).unwrap(), "a"); + assert!(!root.join("src/a.rs").exists()); + + assert_eq!(rename(root, &moved, "b.rs").unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(fs::read_to_string(root.join("src/b.rs")).unwrap(), "b", "the other file is untouched"); + assert!(rename(root, &moved, "../c.rs").is_err()); + + let recased = rename(root, &moved, "C.rs").unwrap(); + assert_eq!(recased.file_name().unwrap(), "C.rs", "a change of case alone is a rename, not a clash"); + assert_eq!(fs::read_to_string(&recased).unwrap(), "a"); + } + + #[test] + fn deletes_files_and_folders_inside_the_session_folder_only() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fs::create_dir_all(root.join("src/deep")).unwrap(); + fs::write(root.join("src/deep/x.rs"), "x").unwrap(); + fs::write(root.join("top.rs"), "t").unwrap(); + + delete(root, &root.join("top.rs")).unwrap(); + assert!(!root.join("top.rs").exists()); + delete(root, &root.join("src")).unwrap(); + assert!(!root.join("src").exists(), "a folder goes with everything in it"); + + assert!(delete(root, root).is_err(), "never the session folder itself"); + let outside = tempfile::tempdir().unwrap(); + fs::write(outside.path().join("o.rs"), "o").unwrap(); + assert!(delete(root, &outside.path().join("o.rs")).is_err()); + assert!(outside.path().join("o.rs").exists()); + } +} diff --git a/src/git/commit.rs b/src/git/commit.rs index f8c41ed..eb7d03b 100644 --- a/src/git/commit.rs +++ b/src/git/commit.rs @@ -46,6 +46,32 @@ pub fn commit_and_push(complete: Complete, cwd: &Path) -> Result } } +/// What Commit & Push would have to do in a folder. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Pending { + /// Changed or new files in the working tree. + pub changes: bool, + /// Commits origin hasn't got, or a branch origin doesn't have yet. + pub unpushed: bool, +} + +impl Pending { + pub fn any(self) -> bool { + self.changes || self.unpushed + } +} + +/// Blocking. Runs every few seconds beside Claude's own git commands, so it must not take `index.lock` to refresh the index. +pub fn pending(cwd: &Path) -> Result { + let changes = !git(cwd, &["--no-optional-locks", "status", "--porcelain"], None)?.trim().is_empty(); + let unpushed = match git(cwd, &["rev-list", "--count", "@{u}..HEAD"], None) { + Ok(count) => count.trim() != "0", + // No upstream: the first push publishes the branch, if there is an origin and a commit to publish. + Err(_) => has_origin(cwd) && git(cwd, &["rev-parse", "--verify", "-q", "HEAD"], None).is_ok(), + }; + Ok(Pending { changes, unpushed }) +} + /// `git pull` with the user's own pull config (merge / rebase / ff-only). Blocking. pub fn pull(cwd: &Path) -> Result { let out = git(cwd, &["pull"], None)?; @@ -281,6 +307,33 @@ mod tests { assert!(b.join("two.txt").exists()); } + #[test] + fn pending_work_is_changes_or_commits_origin_lacks() { + let tmp = tempfile::tempdir().unwrap(); + let (root, a) = (tmp.path(), tmp.path().join("a")); + git(root, &["init", "-q", "--bare", "remote.git"], None).unwrap(); + git(root, &["clone", "-q", "remote.git", "a"], None).unwrap(); + assert_eq!(pending(&a).unwrap(), Pending::default(), "an empty clone has nothing to do"); + commit(&a, "one.txt"); + assert_eq!(pending(&a).unwrap(), Pending { changes: false, unpushed: true }, "a branch origin doesn't have yet"); + commit_and_push(&no_model, &a).unwrap(); + assert!(!pending(&a).unwrap().any(), "pushed and clean"); + commit(&a, "two.txt"); + assert_eq!(pending(&a).unwrap(), Pending { changes: false, unpushed: true }, "a commit origin lacks"); + git(&a, &["push", "-q"], None).unwrap(); + std::fs::write(a.join("three.txt"), "x").unwrap(); + assert_eq!(pending(&a).unwrap(), Pending { changes: true, unpushed: false }, "a new file"); + } + + #[test] + fn a_folder_without_origin_has_nothing_to_push() { + let tmp = tempfile::tempdir().unwrap(); + git(tmp.path(), &["init", "-q", "c"], None).unwrap(); + let c = tmp.path().join("c"); + commit(&c, "c.txt"); + assert!(!pending(&c).unwrap().any()); + } + #[test] fn pull_conflict_is_classified_and_blocks_commit_and_push() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/git/lines.rs b/src/git/lines.rs new file mode 100644 index 0000000..1607aea --- /dev/null +++ b/src/git/lines.rs @@ -0,0 +1,138 @@ +//! Which lines of a file differ from the last commit, for the editor's gutter. Staged and unstaged changes both +//! count, and a file Git doesn't know yet is all new. + +use std::ops::Range; +use std::path::Path; + +use git2::{DiffOptions, Repository}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Kind { + Added, + Modified, + /// Lines were removed just above `Change::lines.start`. + Deleted, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Change { + /// 0-based lines of the file as it is now; empty for `Deleted`, where `start` is the line below the removal. + pub lines: Range, + pub kind: Kind, +} + +/// The changes in `file` since HEAD, in file order. Empty when the file isn't in a repository. +pub fn changed_lines(file: &Path) -> Vec { + let Some(dir) = file.parent() else { return vec![] }; + let Ok(repo) = Repository::discover(dir) else { return vec![] }; + let Some(relative) = repo.workdir().and_then(|root| file.strip_prefix(root).or_else(|_| file.strip_prefix(dunce::simplified(root))).ok()) else { + return vec![]; + }; + let mut options = DiffOptions::new(); + // The path is one file, not a pattern: `[id].tsx` or `a*b` must not also match their neighbours. Git paths use `/`. + let relative = relative.to_string_lossy(); + let relative = if cfg!(windows) { relative.replace('\\', "/") } else { relative.into_owned() }; + options.pathspec(relative).disable_pathspec_match(true).context_lines(0).include_untracked(true).show_untracked_content(true); + // A repository without commits has no HEAD tree: everything in it is new. + let head = repo.head().ok().and_then(|h| h.peel_to_tree().ok()); + let Ok(diff) = repo.diff_tree_to_workdir_with_index(head.as_ref(), Some(&mut options)) else { return vec![] }; + let mut changes = Vec::new(); + let _ = diff.foreach( + &mut |_, _| true, + None, + Some(&mut |_, hunk| { + let (old, new, start) = (hunk.old_lines() as usize, hunk.new_lines() as usize, hunk.new_start() as usize); + changes.push(if new == 0 { + // `new_start` counts lines from 1 and names the line above the removal, so as a 0-based index it is the line below. + Change { lines: start..start, kind: Kind::Deleted } + } else { + Change { lines: start - 1..start - 1 + new, kind: if old == 0 { Kind::Added } else { Kind::Modified } } + }); + true + }), + None, + ); + changes +} + +#[cfg(test)] +mod tests { + use super::*; + + fn commit_all(repo: &Repository) { + let mut index = repo.index().unwrap(); + index.add_all(["*"], git2::IndexAddOption::DEFAULT, None).unwrap(); + index.write().unwrap(); + let tree = repo.find_tree(index.write_tree().unwrap()).unwrap(); + let sig = git2::Signature::now("t", "t@t").unwrap(); + let parents: Vec<_> = repo.head().ok().and_then(|h| h.peel_to_commit().ok()).into_iter().collect(); + repo.commit(Some("HEAD"), &sig, &sig, "c", &tree, &parents.iter().collect::>()).unwrap(); + } + + #[test] + fn added_modified_and_deleted_lines_are_told_apart() { + let tmp = tempfile::tempdir().unwrap(); + let dir = dunce::canonicalize(tmp.path()).unwrap(); + let repo = Repository::init(&dir).unwrap(); + let file = dir.join("f.txt"); + std::fs::write(&file, "a\nb\nc\nd\ne\nf\n").unwrap(); + commit_all(&repo); + assert_eq!(changed_lines(&file), vec![], "nothing changed yet"); + + // a -> A, d removed, g appended + std::fs::write(&file, "A\nb\nc\ne\nf\ng\n").unwrap(); + assert_eq!( + changed_lines(&file), + vec![ + Change { lines: 0..1, kind: Kind::Modified }, + Change { lines: 3..3, kind: Kind::Deleted }, + Change { lines: 5..6, kind: Kind::Added }, + ] + ); + } + + #[test] + fn a_file_in_a_folder_is_found() { + let tmp = tempfile::tempdir().unwrap(); + let dir = dunce::canonicalize(tmp.path()).unwrap(); + let repo = Repository::init(&dir).unwrap(); + std::fs::create_dir_all(dir.join("src").join("deep")).unwrap(); + let file = dir.join("src").join("deep").join("f.txt"); + std::fs::write(&file, "a\nb\n").unwrap(); + commit_all(&repo); + std::fs::write(&file, "a\nB\n").unwrap(); + assert_eq!(changed_lines(&file), vec![Change { lines: 1..2, kind: Kind::Modified }]); + } + + #[test] + fn a_name_with_glob_characters_is_not_a_pattern() { + let tmp = tempfile::tempdir().unwrap(); + let dir = dunce::canonicalize(tmp.path()).unwrap(); + let repo = Repository::init(&dir).unwrap(); + std::fs::write(dir.join("[ab].txt"), "x\n").unwrap(); + std::fs::write(dir.join("a.txt"), "x\n").unwrap(); + commit_all(&repo); + std::fs::write(dir.join("a.txt"), "changed\n").unwrap(); + assert_eq!(changed_lines(&dir.join("[ab].txt")), vec![], "a.txt's change is not [ab].txt's"); + } + + #[test] + fn a_file_git_does_not_know_yet_is_all_new() { + let tmp = tempfile::tempdir().unwrap(); + let dir = dunce::canonicalize(tmp.path()).unwrap(); + let repo = Repository::init(&dir).unwrap(); + std::fs::write(dir.join("old.txt"), "x\n").unwrap(); + commit_all(&repo); + let file = dir.join("new.txt"); + std::fs::write(&file, "1\n2\n3\n").unwrap(); + assert_eq!(changed_lines(&file), vec![Change { lines: 0..3, kind: Kind::Added }]); + } + + #[test] + fn a_file_outside_a_repository_has_no_changes() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join("f.txt"); + std::fs::write(&file, "x\n").unwrap(); + assert_eq!(changed_lines(&file), vec![]); + } +} diff --git a/src/git/mod.rs b/src/git/mod.rs index 77e70d6..1e9b672 100644 --- a/src/git/mod.rs +++ b/src/git/mod.rs @@ -2,6 +2,7 @@ //! `commit` is the Commit & Push flow built on top of it. pub mod commit; +pub mod lines; use std::path::{Path, PathBuf}; diff --git a/src/github/cli.rs b/src/github/cli.rs index a63e9ec..4483702 100644 --- a/src/github/cli.rs +++ b/src/github/cli.rs @@ -234,6 +234,12 @@ impl Gh { serde_json::from_str(&out).map_err(|e| Error::other(format!("unexpected answer from gh: {e}"))) } + /// The title and state GitHub holds for an issue or pull request. + pub fn item_status(&self, repo: &RepoRef, number: u32) -> Result<(String, super::model::State), Error> { + let answer = self.rest("GET", &format!("repos/{}/issues/{number}", repo.full()), None)?; + super::model::parse_status(&answer).ok_or_else(|| Error::other("unexpected answer from GitHub")) + } + /// `gh pr checkout ` in this folder. pub fn checkout(&self, number: u32) -> Result { self.run(&["pr", "checkout", &number.to_string()], None)?; diff --git a/src/github/mod.rs b/src/github/mod.rs index 3b804d9..023d085 100644 --- a/src/github/mod.rs +++ b/src/github/mod.rs @@ -144,6 +144,26 @@ mod render { } } +#[cfg(test)] +mod tabs { + use super::model::*; + use super::view::*; + use gpui::{AppContext, TestAppContext}; + + #[test] + fn opening_a_pull_request_selects_the_pull_requests_tab() { + let mut cx = TestAppContext::single(); + cx.update(|app| gpui_kit::init(app)); + let (window, view) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| GithubView::new(".".into(), "x".into(), None, window, cx)))) + .unwrap(); + for (kind, number) in [(Kind::Pull, 7), (Kind::Issue, 3)] { + cx.update_window(window, |_, window, app| view.update(app, |v, cx| v.open_item(kind, number, window, cx))).unwrap(); + assert_eq!(view.read_with(&cx, |v, _| v.kind), kind); + } + } +} + #[cfg(test)] mod schema { //! Sends every mutation with made-up ids: GitHub validates the query text (variable types, field names) diff --git a/src/github/model.rs b/src/github/model.rs index 72b2d8b..163b7ea 100644 --- a/src/github/model.rs +++ b/src/github/model.rs @@ -276,6 +276,17 @@ pub fn parse_item(v: &Value) -> Option { }) } +/// Title and state out of REST `repos/{owner}/{name}/issues/{number}`, which answers for pull requests too. +pub fn parse_status(v: &Value) -> Option<(String, State)> { + let title = v["title"].as_str()?.to_string(); + let state = match v["state"].as_str()? { + "open" => State::Open, + _ if !v["pull_request"]["merged_at"].is_null() => State::Merged, + _ => State::Closed, + }; + Some((title, state)) +} + pub fn parse_page(data: &Value) -> Page { let s = &data["search"]; Page { @@ -629,6 +640,17 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn status_reads_title_and_whether_it_is_open_closed_or_merged() { + let open = json!({"title": "Fix it", "state": "open"}); + assert_eq!(parse_status(&open), Some(("Fix it".into(), State::Open))); + let closed = json!({"title": "Fix it", "state": "closed", "pull_request": {"merged_at": null}}); + assert_eq!(parse_status(&closed), Some(("Fix it".into(), State::Closed))); + let merged = json!({"title": "Fix it", "state": "closed", "pull_request": {"merged_at": "2026-10-01T10:00:00Z"}}); + assert_eq!(parse_status(&merged), Some(("Fix it".into(), State::Merged))); + assert_eq!(parse_status(&json!({"message": "Not Found"})), None); + } + #[test] fn qualifiers_are_edited_in_place() { let q = "is:open label:bug label:\"good first issue\" author:me crash"; diff --git a/src/github/view/act.rs b/src/github/view/act.rs index 37d7ff5..ae1184f 100644 --- a/src/github/view/act.rs +++ b/src/github/view/act.rs @@ -22,6 +22,16 @@ impl GithubView { self.query_input.update(cx, |s, cx| s.set_value(shown, window, cx)); } + /// Switch the Issues / Pull requests tab: show that kind's search and load its list if it hasn't been. + pub(super) fn select_kind(&mut self, kind: Kind, window: &mut Window, cx: &mut Context) { + self.kind = kind; + let q = self.queries[idx(kind)].clone(); + self.set_query_text(&q, window, cx); + if !self.lists[idx(kind)].loaded { + self.load_list(kind, false, window, cx); + } + } + pub fn act(&mut self, act: GhAct, window: &mut Window, cx: &mut Context) { // Choosing anything closes an open picker, except the multi-select ones that stay for more clicks. if !matches!(act, GhAct::ToggleLabel(_) | GhAct::ToggleAssignee(_) | GhAct::ToggleReviewer(_) | GhAct::Popup(..)) { @@ -35,14 +45,9 @@ impl GithubView { GhAct::Retry => self.connect(window, cx), GhAct::SignIn => cx.emit(GhEvent::SignIn), GhAct::SetKind(k) => { - self.kind = k; self.detail = None; self.mode = Mode::Browse; - let q = self.queries[idx(k)].clone(); - self.set_query_text(&q, window, cx); - if !self.lists[idx(k)].loaded { - self.load_list(k, false, window, cx); - } + self.select_kind(k, window, cx); } GhAct::SetQuery(q) => { let q = q.split_whitespace().collect::>().join(" "); diff --git a/src/github/view/load.rs b/src/github/view/load.rs index 6c733d4..69cfb81 100644 --- a/src/github/view/load.rs +++ b/src/github/view/load.rs @@ -235,6 +235,8 @@ impl GithubView { self.mode = Mode::Browse; self.editing = None; self.popup = None; + // The tab strip and the list behind the detail follow the item, so Back lands on the item's own list. + self.select_kind(kind, window, cx); self.composer.update(cx, |s, cx| s.set_value("", window, cx)); let mut state = DetailState::new(kind, number); // Show the list row's facts at once; the skeleton stands in for the rest until the answer comes. diff --git a/src/lsp/mod.rs b/src/lsp/mod.rs new file mode 100644 index 0000000..81ae8e2 --- /dev/null +++ b/src/lsp/mod.rs @@ -0,0 +1,398 @@ +//! A small Language Server Protocol client for editor mode: start a server found on PATH, talk to it over stdio, and +//! pass its diagnostics on. Nothing is downloaded or installed. No GPUI here; +//! `app::language_servers` wires it to tabs. + +pub mod rpc; + +use std::collections::{HashMap, VecDeque}; +use std::io::{BufReader, BufWriter, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::Duration; + +use futures::channel::{mpsc as async_mpsc, oneshot}; +use lsp_types::notification::Notification; +use lsp_types::request::Request; +use lsp_types::{Diagnostic, Uri}; +use serde_json::{Value, json}; + +/// A language server Claudiu knows how to start, and the editor languages (see `files::language`) it serves. +pub struct Kind { + pub program: &'static str, + args: &'static [&'static str], + languages: &'static [&'static str], + /// It gives diagnostics only when asked for them (`Server::diagnostics`), instead of sending them. + pub pull_diagnostics: bool, +} + +pub const KINDS: [Kind; 3] = [ + Kind { program: "rust-analyzer", args: &[], languages: &["rust"], pull_diagnostics: false }, + // TypeScript 7's own server. typescript-language-server drives the older JavaScript `tsserver`, which TypeScript 7 + // no longer ships, so it fails on projects that use it. + Kind { program: "tsc", args: &["--lsp", "--stdio"], languages: &["typescript", "tsx", "javascript"], pull_diagnostics: true }, + Kind { program: "gleam", args: &["lsp"], languages: &["gleam"], pull_diagnostics: false }, +]; + +pub fn kind_for(language: &str) -> Option<&'static Kind> { + KINDS.iter().find(|k| k.languages.contains(&language)) +} + +/// The LSP `languageId` for an editor language. +pub fn language_id(language: &str) -> &str { + match language { + "tsx" => "typescriptreact", + other => other, + } +} + +/// A column on `line` counted in UTF-16 units, as most servers count, in characters, as the editor does. A column +/// inside a character (half of an emoji) moves past it. +pub fn utf16_to_chars(line: &str, units: u32) -> u32 { + let mut seen = 0; + for (chars, c) in line.chars().enumerate() { + if seen >= units { + return chars as u32; + } + seen += c.len_utf16() as u32; + } + line.chars().count() as u32 +} + +/// A column on `line` counted in characters, as the editor does, in UTF-16 units. +pub fn chars_to_utf16(line: &str, chars: u32) -> u32 { + line.chars().take(chars as usize).map(|c| c.len_utf16() as u32).sum() +} + +pub fn uri(path: &Path) -> Option { + url::Url::from_file_path(path).ok()?.as_str().parse().ok() +} + +pub fn path_of(uri: &Uri) -> Option { + url::Url::parse(uri.as_str()).ok()?.to_file_path().ok() +} + +/// What a server tells the UI without being asked. +#[derive(Debug)] +pub enum Event { + Diagnostics(PathBuf, Vec), + /// The server stopped on its own; the text is its last words on stderr, if any. + Exited(String), +} + +type Pending = Arc>>>>; + +/// A running language server. Dropping it asks the server to exit, then ends the process. +pub struct Server { + outgoing: mpsc::Sender, + pending: Pending, + next_id: AtomicI64, + child: Option, + pull: bool, + utf16: bool, +} + +impl Server { + /// Start `kind` in `root` and complete the `initialize` handshake. Blocks, so call it off the UI thread. + pub fn start(kind: &Kind, program: &Path, root: &Path, events: async_mpsc::UnboundedSender) -> Result { + let mut cmd = Command::new(program); + cmd.args(kind.args).current_dir(root).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + crate::platform::no_window(&mut cmd); + let mut child = cmd.spawn().map_err(|e| format!("could not start {}: {e}", kind.program))?; + let (stdin, stdout, stderr) = (child.stdin.take().unwrap(), child.stdout.take().unwrap(), child.stderr.take().unwrap()); + match Self::connect(stdout, stdin, Some(stderr), root, kind.pull_diagnostics, events) { + Ok(mut server) => { + server.child = Some(child); + Ok(server) + } + // Dropping a `Child` leaves the process running, so a server stuck in the handshake would outlive the pane. + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + Err(e) + } + } + } + + /// Talk to a server over `reader` and `writer` (its stdout and stdin) and complete the handshake. `pull`: ask it for + /// diagnostics (see `Kind::pull_diagnostics`); offered only to servers that need it, since a server that does both may + /// then send fewer. + pub fn connect( + reader: impl Read + Send + 'static, + writer: impl Write + Send + 'static, + stderr: Option, + root: &Path, + pull: bool, + events: async_mpsc::UnboundedSender, + ) -> Result { + let (outgoing, queue) = mpsc::channel::(); + std::thread::spawn(move || { + let mut writer = BufWriter::new(writer); + while let Ok(message) = queue.recv() { + if rpc::write_message(&mut writer, &message).is_err() { + break; + } + } + }); + // Kept only to explain a crash; never logged. + let last_words = Arc::new(Mutex::new(VecDeque::::new())); + if let Some(stderr) = stderr { + let last_words = last_words.clone(); + std::thread::spawn(move || { + use std::io::BufRead; + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + let mut lines = last_words.lock().unwrap(); + lines.push_back(line); + if lines.len() > 3 { + lines.pop_front(); + } + } + }); + } + let pending: Pending = Default::default(); + { + let (pending, outgoing) = (pending.clone(), outgoing.clone()); + std::thread::spawn(move || { + let mut reader = BufReader::new(reader); + while let Ok(Some(message)) = rpc::read_message(&mut reader) { + handle(message, &pending, &outgoing, &events); + } + pending.lock().unwrap().clear(); + // Give stderr a moment to deliver the reason before reporting it. + std::thread::sleep(Duration::from_millis(200)); + let words = last_words.lock().unwrap().iter().map(|l| l.trim()).filter(|l| !l.is_empty()).collect::>().join(" "); + let _ = events.unbounded_send(Event::Exited(words)); + }); + } + let mut server = Server { outgoing, pending, next_id: AtomicI64::new(1), child: None, pull, utf16: true }; + let mut params = json!({ + "processId": std::process::id(), + "rootUri": uri(root).map(|u| u.as_str().to_string()), + "workspaceFolders": [{"uri": uri(root).map(|u| u.as_str().to_string()), "name": root.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()}], + "capabilities": { + // The editor counts columns in characters; a server that keeps to UTF-16 has its columns converted. + "general": {"positionEncodings": ["utf-32", "utf-16"]}, + "textDocument": { + "synchronization": {"didSave": true}, + "publishDiagnostics": {}, + "hover": {"contentFormat": ["markdown", "plaintext"]}, + "definition": {"linkSupport": true}, + }, + }, + }); + if pull { + params["capabilities"]["textDocument"]["diagnostic"] = json!({}); + } + let reply = server.send_request(lsp_types::request::Initialize::METHOD, params); + let (done, answered) = mpsc::channel(); + std::thread::spawn(move || done.send(futures::executor::block_on(reply))); + let initialized = answered + .recv_timeout(Duration::from_secs(30)) + .unwrap_or_else(|_| Err("no answer within 30 seconds".into())) + .map_err(|e| format!("the handshake failed: {e}"))?; + // A server that names no encoding uses UTF-16, as the protocol says. + server.utf16 = initialized["capabilities"]["positionEncoding"].as_str() != Some("utf-32"); + server.notify::(lsp_types::InitializedParams {}); + Ok(server) + } + + fn send_request(&self, method: &str, params: Value) -> impl Future> + use<> { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let (tx, rx) = oneshot::channel(); + self.pending.lock().unwrap().insert(id, tx); + let _ = self.outgoing.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})); + async move { rx.await.unwrap_or_else(|_| Err("the server stopped".into())) } + } + + pub fn request(&self, params: R::Params) -> impl Future> + use { + let reply = self.send_request(R::METHOD, serde_json::to_value(params).unwrap_or(Value::Null)); + async move { serde_json::from_value(reply.await?).map_err(|e| e.to_string()) } + } + + /// Whether the server counts columns in UTF-16 units rather than characters (see `utf16_to_chars`). + pub fn counts_utf16(&self) -> bool { + self.utf16 + } + + /// Whether diagnostics come from `diagnostics` rather than `Event::Diagnostics`. + pub fn pulls_diagnostics(&self) -> bool { + self.pull + } + + /// Ask for a document's diagnostics. `None` when they haven't changed since the last answer. + pub fn diagnostics(&self, uri: &Uri) -> impl Future>, String>> + use<> { + let reply = self.send_request(lsp_types::request::DocumentDiagnosticRequest::METHOD, json!({"textDocument": {"uri": uri.as_str()}})); + async move { full_report(reply.await?) } + } + + pub fn notify(&self, params: N::Params) { + let params = serde_json::to_value(params).unwrap_or(Value::Null); + let _ = self.outgoing.send(json!({"jsonrpc": "2.0", "method": N::METHOD, "params": params})); + } +} + +impl Drop for Server { + fn drop(&mut self) { + // The reply isn't waited for: the server gets `exit` right after, and the process is ended if it lingers. + drop(self.send_request(lsp_types::request::Shutdown::METHOD, Value::Null)); + self.notify::(()); + if let Some(mut child) = self.child.take() { + // A polite server is gone well within this; one that isn't gets ended, off the UI thread. + std::thread::spawn(move || { + for _ in 0..20 { + if child.try_wait().ok().flatten().is_some() { + return; + } + std::thread::sleep(Duration::from_millis(100)); + } + let _ = child.kill(); + let _ = child.wait(); + }); + } + } +} + +/// The items of a full diagnostic report; an `unchanged` one has none. +fn full_report(reply: Value) -> Result>, String> { + match reply.get("kind").and_then(Value::as_str) { + Some("full") => serde_json::from_value(reply["items"].clone()).map(Some).map_err(|e| e.to_string()), + _ => Ok(None), + } +} + +fn handle(message: Value, pending: &Pending, outgoing: &mpsc::Sender, events: &async_mpsc::UnboundedSender) { + let method = message.get("method").and_then(Value::as_str); + let id = message.get("id").cloned(); + match (method, id) { + // A reply to one of ours. + (None, Some(id)) => { + let Some(tx) = id.as_i64().and_then(|id| pending.lock().unwrap().remove(&id)) else { return }; + let reply = match message.get("error") { + Some(e) => Err(e.get("message").and_then(Value::as_str).unwrap_or("error").to_string()), + None => Ok(message.get("result").cloned().unwrap_or(Value::Null)), + }; + let _ = tx.send(reply); + } + // The server asks something; answer every request so none waits forever. Settings are left at its defaults. + (Some(method), Some(id)) => { + let result = match method { + "workspace/configuration" => { + let n = message.pointer("/params/items").and_then(Value::as_array).map_or(0, Vec::len); + Value::Array(vec![Value::Null; n]) + } + _ => Value::Null, + }; + let _ = outgoing.send(json!({"jsonrpc": "2.0", "id": id, "result": result})); + } + (Some(lsp_types::notification::PublishDiagnostics::METHOD), None) => { + let Ok(params) = serde_json::from_value::(message["params"].clone()) else { return }; + if let Some(path) = path_of(¶ms.uri) { + let _ = events.unbounded_send(Event::Diagnostics(path, params.diagnostics)); + } + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use futures::StreamExt; + use std::io::BufReader; + + /// A fake server on the other end of two pipes: it answers `initialize`, asks for configuration, publishes a + /// diagnostic when a document opens, answers hover and a request for diagnostics, and stops when told. + fn fake_server(from_client: std::io::PipeReader, mut to_client: std::io::PipeWriter, root: PathBuf) { + std::thread::spawn(move || { + let mut input = BufReader::new(from_client); + while let Ok(Some(m)) = rpc::read_message(&mut input) { + let reply = |out: &mut std::io::PipeWriter, result: Value| rpc::write_message(out, &json!({"jsonrpc": "2.0", "id": m["id"], "result": result})).unwrap(); + match m["method"].as_str() { + Some("initialize") => { + assert_eq!(m["params"]["capabilities"]["textDocument"]["diagnostic"], json!({}), "pull diagnostics are offered"); + rpc::write_message(&mut to_client, &json!({"jsonrpc": "2.0", "id": "cfg", "method": "workspace/configuration", "params": {"items": [{}, {}]}})).unwrap(); + reply(&mut to_client, json!({"capabilities": {}})); + } + Some("textDocument/didOpen") => { + let uri = uri(&root.join("main.rs")).unwrap(); + let d = json!({"uri": uri.as_str(), "diagnostics": [{"range": {"start": {"line": 0, "character": 3}, "end": {"line": 0, "character": 7}}, "message": "unused", "severity": 2}]}); + rpc::write_message(&mut to_client, &json!({"jsonrpc": "2.0", "method": "textDocument/publishDiagnostics", "params": d})).unwrap(); + } + Some("textDocument/hover") => reply(&mut to_client, json!({"contents": {"kind": "markdown", "value": "fn main()"}})), + Some("textDocument/diagnostic") => { + assert_eq!(m["params"]["textDocument"]["uri"], uri(&root.join("main.rs")).unwrap().as_str()); + let d = json!({"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 2}}, "message": "asked for"}); + reply(&mut to_client, json!({"kind": "full", "items": [d]})); + } + Some("shutdown") => reply(&mut to_client, Value::Null), + Some("exit") => return, + _ => {} + } + if m["id"] == "cfg" { + assert_eq!(m["result"], json!([null, null]), "configuration is answered item by item"); + } + } + }); + } + + #[test] + fn handshake_diagnostics_hover_and_exit() { + let root = std::env::temp_dir(); + let (server_in, client_out) = std::io::pipe().unwrap(); + let (client_in, server_out) = std::io::pipe().unwrap(); + fake_server(server_in, server_out, root.clone()); + let (tx, mut rx) = async_mpsc::unbounded(); + let server = Server::connect(client_in, client_out, None::, &root, true, tx).unwrap(); + assert!(server.counts_utf16(), "a server that names no encoding counts in UTF-16"); + let doc = uri(&root.join("main.rs")).unwrap(); + server.notify::(lsp_types::DidOpenTextDocumentParams { + text_document: lsp_types::TextDocumentItem::new(doc.clone(), "rust".into(), 0, "fn main() {}".into()), + }); + match futures::executor::block_on(rx.next()) { + Some(Event::Diagnostics(path, d)) => { + assert_eq!(path, root.join("main.rs")); + assert_eq!((d.len(), d[0].message.as_str()), (1, "unused")); + } + other => panic!("expected diagnostics, got {other:?}"), + } + let hover = server.request::(lsp_types::HoverParams { + text_document_position_params: lsp_types::TextDocumentPositionParams::new(lsp_types::TextDocumentIdentifier::new(doc.clone()), lsp_types::Position::new(0, 4)), + work_done_progress_params: Default::default(), + }); + let hover = futures::executor::block_on(hover).unwrap().unwrap(); + assert!(matches!(hover.contents, lsp_types::HoverContents::Markup(m) if m.value == "fn main()")); + let pulled = futures::executor::block_on(server.diagnostics(&doc)).unwrap().unwrap(); + assert_eq!(pulled.iter().map(|d| d.message.as_str()).collect::>(), ["asked for"]); + drop(server); + assert!(matches!(futures::executor::block_on(rx.next()), Some(Event::Exited(_))), "the end of the server is reported"); + } + + #[test] + fn columns_convert_between_characters_and_utf16() { + let line = "let 😀 = é;"; + // Characters: l e t ␠ 😀 ␠ = ␠ é ; — the emoji is one character but two UTF-16 units. + assert_eq!(chars_to_utf16(line, 4), 4, "before the emoji"); + assert_eq!(chars_to_utf16(line, 5), 6, "after the emoji"); + assert_eq!(chars_to_utf16(line, 9), 10, "é is one unit"); + assert_eq!(utf16_to_chars(line, 6), 5); + assert_eq!(utf16_to_chars(line, 10), 9); + assert_eq!(utf16_to_chars(line, 5), 5, "inside the emoji moves past it"); + assert_eq!(utf16_to_chars(line, 99), 10, "past the end stays at the end"); + for chars in 0..=10 { + assert_eq!(utf16_to_chars(line, chars_to_utf16(line, chars)), chars, "round trip at {chars}"); + } + } + + #[test] + fn languages_map_to_servers() { + assert_eq!(kind_for("rust").map(|k| k.program), Some("rust-analyzer")); + assert_eq!(kind_for("tsx").map(|k| k.program), Some("tsc")); + assert_eq!(kind_for("javascript").map(|k| k.program), Some("tsc")); + assert_eq!(kind_for("gleam").map(|k| k.program), Some("gleam")); + assert!(kind_for("markdown").is_none()); + assert_eq!(language_id("tsx"), "typescriptreact"); + let p = std::env::temp_dir().join("a b.rs"); + assert_eq!(path_of(&uri(&p).unwrap()), Some(p), "paths with spaces survive the round trip"); + } +} diff --git a/src/lsp/rpc.rs b/src/lsp/rpc.rs new file mode 100644 index 0000000..587304c --- /dev/null +++ b/src/lsp/rpc.rs @@ -0,0 +1,59 @@ +//! The language server wire format: JSON-RPC messages, each after a `Content-Length` header. + +use std::io::{self, BufRead, Write}; + +use serde_json::Value; + +pub fn write_message(out: &mut impl Write, message: &Value) -> io::Result<()> { + let body = serde_json::to_vec(message)?; + write!(out, "Content-Length: {}\r\n\r\n", body.len())?; + out.write_all(&body)?; + out.flush() +} + +/// The next message, or `None` at the end of the stream. Headers other than `Content-Length` are skipped. +pub fn read_message(input: &mut impl BufRead) -> io::Result> { + let mut length = None; + loop { + let mut line = String::new(); + if input.read_line(&mut line)? == 0 { + return Ok(None); + } + let line = line.trim_end(); + if line.is_empty() { + break; + } + if let Some((name, value)) = line.split_once(':') + && name.trim().eq_ignore_ascii_case("content-length") + { + length = value.trim().parse::().ok(); + } + } + let length = length.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "a message without Content-Length"))?; + let mut body = vec![0; length]; + input.read_exact(&mut body)?; + serde_json::from_slice(&body).map(Some).map_err(io::Error::from) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn messages_round_trip_and_extra_headers_are_skipped() { + let mut wire = Vec::new(); + write_message(&mut wire, &json!({"jsonrpc": "2.0", "id": 1, "result": "é"})).unwrap(); + wire.extend_from_slice(b"Content-Type: application/vscode-jsonrpc; charset=utf-8\r\ncontent-length: 2\r\n\r\n{}"); + let mut input = io::Cursor::new(wire); + assert_eq!(read_message(&mut input).unwrap(), Some(json!({"jsonrpc": "2.0", "id": 1, "result": "é"}))); + assert_eq!(read_message(&mut input).unwrap(), Some(json!({}))); + assert_eq!(read_message(&mut input).unwrap(), None); + } + + #[test] + fn a_message_without_length_is_an_error() { + let mut input = io::Cursor::new(b"X-Other: 1\r\n\r\n{}".to_vec()); + assert!(read_message(&mut input).is_err()); + } +} diff --git a/src/main.rs b/src/main.rs index c150224..29886a2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,10 +3,13 @@ mod app; mod claude; mod datadir; +mod files; mod git; +mod lsp; mod github; mod panels; mod platform; +mod priority; mod store; mod terminal; mod updater; @@ -21,15 +24,15 @@ gpui_kit::assets::icon_assets!( AppIcons, [ WindowMinimize, WindowMaximize, WindowRestore, WindowClose, Archive, ArchiveRestore, ArrowDownToLine, ArrowLeft, Brackets, Check, ChevronDown, ChevronRight, - CircleCheck, CircleDot, CircleSlash, CircleX, Clock, Ellipsis, Eye, ExternalLink, FolderOpen, GitBranch, GitCommitHorizontal, GitMerge, GitPullRequest, - GitPullRequestClosed, GitPullRequestDraft, HeartPlus, LoaderCircle, Lock, MessageSquare, PanelBottom, PanelLeft, PanelRight, Pencil, RefreshCw, Search, + CircleCheck, CircleDot, CircleSlash, CircleX, Clock, Ellipsis, Eye, ExternalLink, File, FileText, Folder, FolderOpen, GitBranch, GitCommitHorizontal, GitMerge, GitPullRequest, + GitPullRequestClosed, GitPullRequestDraft, HeartPlus, LoaderCircle, Lock, MessageSquare, FileCode, PanelBottom, PanelLeft, PanelRight, Pencil, RefreshCw, Search, Settings, Terminal, X ] ); use app::{ CloseSession, FocusSearch, HideApp, HideOthers, ImportProject, NewClaude, NextSession, OpenGithub, OpenSettings, PrevSession, Quit, ShowAllApps, - SwapFocus, ToggleRight, ToggleShell, ToggleSidebar, Workspace, + SwapFocus, ToggleEditor, ToggleRight, ToggleShell, ToggleSidebar, Workspace, }; /// The macOS menu bar. Every item is an existing Claudiu action, so menu, shortcut and sidebar share one code path; @@ -53,6 +56,7 @@ fn menu_bar() -> Vec { Menu::new("File").items([ MenuItem::action("New Claude Session", NewClaude), MenuItem::action("Show or Hide Shell", ToggleShell), + MenuItem::action("Editor Mode", ToggleEditor), MenuItem::action("GitHub Issues & Pull Requests", OpenGithub), MenuItem::separator(), MenuItem::action("Add Project…", ImportProject), @@ -111,6 +115,8 @@ fn main() { std::process::exit(claude::mcp::run()); } install_crash_log(); + #[cfg(windows)] + priority::restore_own_priority(); // Velopack install/update hooks must run before anything else. A no-op for dev builds. velopack::VelopackApp::build().run(); @@ -123,6 +129,7 @@ fn main() { gpui_kit::application().with_assets(AppIcons).run(move |cx: &mut App| { gpui_kit::init(cx); + app::register_languages(); gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, cx); // Claudiu-global shortcuts. Deliberately Ctrl+Shift (Cmd+Shift on macOS) so every plain Ctrl/Alt // chord, e.g. Alt+P, still reaches Claude Code untouched. @@ -138,7 +145,26 @@ fn main() { KeyBinding::new("secondary-shift-g", OpenGithub, None), KeyBinding::new("secondary-,", OpenSettings, None), KeyBinding::new("secondary-shift-]", SwapFocus, None), + KeyBinding::new("secondary-shift-e", ToggleEditor, None), + // Only over the editor pane: elsewhere Ctrl+P belongs to Claude Code. + KeyBinding::new("secondary-p", app::QuickOpen, Some("EditorPane")), + KeyBinding::new("secondary-s", app::SaveFile, Some("EditorPane")), + KeyBinding::new("ctrl-g", app::GoToLine, Some("EditorPane")), + // VS Code's keys: Alt+arrows move by word on macOS. + KeyBinding::new(if cfg!(target_os = "macos") { "ctrl--" } else { "alt-left" }, app::GoBack, Some("EditorPane")), + KeyBinding::new(if cfg!(target_os = "macos") { "ctrl-shift--" } else { "alt-right" }, app::GoForward, Some("EditorPane")), + // The editor answers it from its language server; Ctrl+click (Cmd+click) does the same. + KeyBinding::new("f12", gpui_kit::component::input::GoToDefinition, Some("Input")), KeyBinding::new("ctrl-tab", NextSession, None), + KeyBinding::new("secondary-1", app::ShowSession(1), None), + KeyBinding::new("secondary-2", app::ShowSession(2), None), + KeyBinding::new("secondary-3", app::ShowSession(3), None), + KeyBinding::new("secondary-4", app::ShowSession(4), None), + KeyBinding::new("secondary-5", app::ShowSession(5), None), + KeyBinding::new("secondary-6", app::ShowSession(6), None), + KeyBinding::new("secondary-7", app::ShowSession(7), None), + KeyBinding::new("secondary-8", app::ShowSession(8), None), + KeyBinding::new("secondary-9", app::ShowSession(9), None), KeyBinding::new("ctrl-shift-tab", PrevSession, None), ]); // The text-input library binds these globally (focus traversal, copy, select all, ...). A focused @@ -252,3 +278,24 @@ mod icon_tests { assert!(used > 20, "found only {used} icon uses; the scan is broken"); } } + +#[cfg(test)] +mod source_tests { + /// A NUL byte in a source file makes git treat it as binary, hiding it from diffs and blame. + #[test] + fn no_source_file_holds_a_nul_byte() { + fn walk(dir: &std::path::Path, bad: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap().flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, bad); + } else if path.extension().is_some_and(|e| e == "rs") && std::fs::read(&path).unwrap().contains(&0) { + bad.push(path); + } + } + } + let mut bad = vec![]; + walk(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut bad); + assert!(bad.is_empty(), "NUL byte in {bad:?}; write '\0' instead"); + } +} diff --git a/src/panels/editor_pane.rs b/src/panels/editor_pane.rs new file mode 100644 index 0000000..0334055 --- /dev/null +++ b/src/panels/editor_pane.rs @@ -0,0 +1,454 @@ +//! Editor mode's right-hand panel: the shown session's files beside an editor (state in `app::editor_mode`). + +use gpui::{ + AnyElement, ClickEvent, Context, InteractiveElement, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement, SharedString, StatefulInteractiveElement, Styled, + div, prelude::FluentBuilder, px, +}; +use gpui_kit::assets::IconName; +use gpui_kit::component::input::{Editor, EditorState, Input, RopeExt}; +use crate::git::lines::{Change as LineChange, Kind}; +use gpui_kit::component::list::ListItem; +use gpui_kit::component::tree::tree; + +use crate::app::picker::{Picker, PickerKind, relative}; +use crate::app::editing::Conflict; +use crate::files::Change; +use crate::app::{Act, Ask, AskExplain, AskFix, AskFixProblem, AskTests, EditorCommand, EditorPane, MenuItem, GoBack, GoForward, GoToLine, QuickOpen, SaveFile, Tab, Workspace}; +use crate::panels::theme::{self, hsla}; +use crate::panels::widgets::{button, icon}; +use crate::platform::path_key; + +const TREE_W: f32 = 240.0; + +impl Workspace { + pub fn render_editor_pane(&mut self, cx: &mut Context) -> Option { + let ws = cx.entity().downgrade(); + let menu_ws = ws.clone(); + let server = self.active_id().cloned().and_then(|id| self.server_status(&id)); + let (id, pane) = self.shown_pane(cx)?; + let tabs = render_tabs(&id, pane, cx); + let changed = pane.changed.clone(); + let empty_folders = pane.empty_folders.clone(); + let tree_id = id.clone(); + let files = tree(&pane.tree, move |_ix, entry, _selected, _w, _cx| { + let path = std::path::PathBuf::from(entry.item().id.as_ref()); + let folder = entry.is_folder() || empty_folders.contains(entry.item().id.as_ref()); + let change = changed.get(&path_key(&path)).copied(); + let color = match change { + Some(Change::Modified) => theme::WARN, + Some(Change::Added) => theme::OK, + None => theme::TEXT, + }; + let chevron = folder.then(|| icon(if entry.is_expanded() { IconName::ChevronDown } else { IconName::ChevronRight }, 12.0)); + let glyph = match (folder, entry.is_expanded()) { + (true, true) => IconName::FolderOpen, + (true, false) => IconName::Folder, + (false, _) => file_icon(&path), + }; + // Like VS Code: a letter on a changed file, a dot on a folder holding changes. + let badge = change.map(|c| match (folder, c) { + (true, _) => "●", + (false, Change::Modified) => "M", + (false, Change::Added) => "A", + }); + let row = div() + .flex() + .items_center() + .gap(px(5.0)) + .pl(px(8.0 + 12.0 * entry.depth() as f32 + if folder { 0.0 } else { 17.0 })) + .pr(px(10.0)) + .text_size(crate::panels::scale::px(12.5)) + .text_color(hsla(color)) + .children(chevron) + .child(icon(glyph, 13.0).text_color(hsla(color))) + .child(div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().child(entry.item().label.clone())) + .children(badge.map(|b| div().flex_none().text_size(crate::panels::scale::px(if folder { 8.0 } else { 11.0 })).child(b))); + let (menu_ws, menu_id, menu_path) = (ws.clone(), tree_id.clone(), path.clone()); + let item = ListItem::new(entry.item().id.clone()).py(px(2.0)).child(row).on_mouse_down(MouseButton::Right, move |ev, _w, cx| { + cx.stop_propagation(); // the tree's own menu is for the session folder + let _ = menu_ws.update(cx, |ws, cx| { + let items = ws.file_menu(&menu_id, Some(&menu_path), folder); + ws.open_menu(ev.position, items, cx); + }); + }); + if folder { + return item; + } + let (ws, id) = (ws.clone(), tree_id.clone()); + item.on_click(move |_, window, cx| { + let _ = ws.update(cx, |ws, cx| ws.open_file(&id, path.clone(), None, window, cx)); + }) + }); + let truncated = pane.truncated.then(|| { + div() + .px(px(10.0)) + .py(px(6.0)) + .text_size(crate::panels::scale::px(11.0)) + .text_color(hsla(theme::TEXT_FAINT)) + .child("Too many files to list them all here.") + }); + let body: AnyElement = match pane.shown() { + Some(Tab { note: Some(note), .. }) => centered(note.clone()), + Some(tab) => div() + .size_full() + .flex() + .flex_col() + .children(tab.conflict.map(|c| render_conflict(&id, &tab.path, c, cx))) + .child( + div() + .flex_1() + .min_h_0() + .relative() + .child(Editor::new(&tab.buffer).appearance(false).h_full().context_menu(move |menu, window, cx| { + // The menu is Claudiu's own: the system's menu keeps the editor's text cursor over it. + let at = window.mouse_position(); + let _ = menu_ws.update(cx, |ws, cx| ws.open_menu(at, editor_menu(), cx)); + menu + })) + .child(change_marks(tab.buffer.clone(), tab.marks.clone())), + ) + .children(server.map(|s| { + div() + .flex_none() + .flex() + .items_center() + .gap(px(8.0)) + .px(px(12.0)) + .py(px(3.0)) + .border_t_1() + .border_color(hsla(theme::BORDER)) + .text_size(crate::panels::scale::px(11.0)) + .text_color(hsla(theme::TEXT_FAINT)) + .child(div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().child(s)) + })) + .into_any_element(), + None => centered("Pick a file on the left, or press Ctrl+P.".into()), + }; + let picker = pane.picker.as_ref().map(|p| render_picker(p, &pane.root, cx)); + Some( + div() + .id("editor-pane") + .key_context("EditorPane") + .track_focus(&pane.focus) + .on_action(cx.listener(|ws, _: &QuickOpen, window, cx| ws.open_picker(PickerKind::Files, window, cx))) + .on_action(cx.listener(|ws, _: &SaveFile, _w, cx| ws.save_shown(cx))) + .on_action(cx.listener(|ws, _: &GoToLine, window, cx| ws.ask_go_to_line(window, cx))) + .on_action(cx.listener(|ws, _: &GoBack, window, cx| ws.go_back(window, cx))) + .on_action(cx.listener(|ws, _: &GoForward, window, cx| ws.go_forward(window, cx))) + .on_action(cx.listener(|ws, _: &AskExplain, window, cx| ws.ask_claude(Ask::Explain, window, cx))) + .on_action(cx.listener(|ws, _: &AskFix, window, cx| ws.ask_claude(Ask::Fix, window, cx))) + .on_action(cx.listener(|ws, _: &AskTests, window, cx| ws.ask_claude(Ask::Tests, window, cx))) + .on_action(cx.listener(|ws, _: &AskFixProblem, window, cx| ws.ask_claude(Ask::Problem, window, cx))) + .relative() + .flex() + .flex_1() + .min_w_0() + .h_full() + .rounded(px(theme::PANEL_RADIUS)) + .overflow_hidden() + .border_1() + .border_color(hsla(theme::PANEL_BORDER)) + .bg(hsla(theme::PANEL_BG)) + .child( + div() + .flex() + .flex_col() + .flex_none() + .w(px(TREE_W)) + .h_full() + .py(px(6.0)) + .border_r_1() + .border_color(hsla(theme::BORDER)) + // Rows don't take the keyboard themselves; the pane does, so its shortcuts work from here. + .on_mouse_down(MouseButton::Left, cx.listener(|ws, _: &MouseDownEvent, window, cx| { + if let Some(pane) = ws.active_id().and_then(|id| ws.panes.get(id)) { + window.focus(&pane.focus, cx); + } + })) + // Right-click below the rows (or on a row, which opens its own menu instead). + .on_mouse_down(MouseButton::Right, cx.listener(|ws, ev: &MouseDownEvent, _w, cx| { + if let Some(id) = ws.active_id().cloned() { + let items = ws.file_menu(&id, None, true); + ws.open_menu(ev.position, items, cx); + } + })) + .child(div().flex_1().min_h_0().child(files)) + .children(truncated), + ) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .h_full() + .child(tabs) + .child(div().flex_1().min_h_0().child(body)), + ) + .children(picker) + .into_any_element(), + ) + } +} + +/// One tab per open file: click to show it, × or a middle click to close it. The full path is in the tab's tooltip. +/// The editor's right-click menu: the usual editing items, then requests to Claude about the selection (or the clicked +/// line) and about the language server's problem there. The same for every click: the editor builds it while it is +/// itself being updated, so it can't be read for a selection or a problem here; each request checks when it runs. +fn editor_menu() -> Vec { + let entry = |label: &str, command| MenuItem::new(label, Act::Editor(command)); + let mut items = vec![ + entry("Go to Definition", EditorCommand::GoToDefinition), + entry("Cut", EditorCommand::Cut), + entry("Copy", EditorCommand::Copy), + entry("Paste", EditorCommand::Paste), + entry("Select All", EditorCommand::SelectAll), + entry("Ask Claude to explain this", EditorCommand::Ask(Ask::Explain)), + entry("Ask Claude to fix this", EditorCommand::Ask(Ask::Fix)), + entry("Ask Claude to write tests for this", EditorCommand::Ask(Ask::Tests)), + entry("Ask Claude to fix the problem on this line", EditorCommand::Ask(Ask::Problem)), + ]; + for ix in [1, 5] { + items[ix].separator_before = true; + } + items +} + +/// A bar at the editor's left edge, over the line numbers, for each line that differs from the last commit. The editor +/// has no gutter of its own to draw in, so this paints over it and asks the editor where each line is, which +/// follows scrolling, soft wrapping and folds. Changes are as of the last save (`Tab::marks`). +fn change_marks(buffer: gpui::Entity, marks: std::sync::Arc>) -> impl IntoElement { + const BAR_WIDTH: f32 = 3.0; + gpui::canvas( + |_, _, _| (), + move |_, _, window, cx| { + let editor = buffer.read(cx); + let (Some(area), Some(visible)) = (editor.text_bounds(), editor.visible_row_range()) else { return }; + let text = editor.text(); + let lines = text.lines_len(); + window.with_content_mask(Some(gpui::ContentMask { bounds: area }), |window| { + for mark in marks.iter() { + let color = match mark.kind { + Kind::Added => hsla(theme::OK), + Kind::Modified => hsla(0x61afef), + Kind::Deleted => hsla(theme::DANGER), + }; + if mark.kind == Kind::Deleted { + // A removal has no line of its own: a short bar on the border between the two lines it was between. + let at = mark.lines.start.min(lines.saturating_sub(1)); + if let Some(top) = editor.range_to_bounds(&(text.line_start_offset(at)..text.line_start_offset(at))) { + window.paint_quad(gpui::fill(gpui::Bounds::new(gpui::point(area.origin.x, top.origin.y - px(1.0)), gpui::size(px(BAR_WIDTH * 2.0), px(2.0))), color)); + } + continue; + } + // A line cannot lie below the rows on screen, so the rest of a long change is skipped. + for line in mark.lines.clone().take_while(|&l| l <= visible.end && l < lines) { + let (start, end) = (text.line_start_offset(line), text.line_end_offset(line)); + if let Some(bounds) = editor.range_to_bounds(&(start..end)) { + window.paint_quad(gpui::fill(gpui::Bounds::new(gpui::point(area.origin.x, bounds.origin.y), gpui::size(px(BAR_WIDTH), bounds.size.height)), color)); + } + } + } + }); + }, + ) + .absolute() + .top_0() + .left_0() + .size_full() +} + +fn render_tabs(id: &crate::store::Id, pane: &EditorPane, cx: &mut Context) -> AnyElement { + let tabs = pane.tabs.iter().enumerate().map(|(i, tab)| { + let shown = pane.active == Some(i); + let name = tab.path.file_name().map_or_else(|| tab.path.to_string_lossy(), |n| n.to_string_lossy()).to_string(); + let rel = relative(&tab.path, &pane.root); + let (show, close, middle) = (id.clone(), id.clone(), id.clone()); + div() + .id(SharedString::from(format!("tab-{i}"))) + .group(SharedString::from(format!("tab-{i}"))) + .flex() + .flex_none() + .items_center() + .gap(px(6.0)) + .h_full() + .pl(px(12.0)) + .pr(px(6.0)) + .border_r_1() + .border_color(hsla(theme::BORDER)) + .text_size(crate::panels::scale::px(12.0)) + .text_color(hsla(if shown { theme::TEXT } else { theme::TEXT_DIM })) + .when(shown, |d| d.bg(hsla(theme::ROW_ACTIVE))) + .cursor_pointer() + .tooltip(move |window, cx| gpui_kit::component::tooltip::Tooltip::new(rel.clone()).build(window, cx)) + .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| ws.show_tab(&show, i, window, cx))) + .on_mouse_up(MouseButton::Middle, cx.listener(move |ws, _: &gpui::MouseUpEvent, window, cx| ws.request_close_tab(&middle, i, window, cx))) + .child(name) + .when(tab.dirty, |d| d.child(div().text_color(hsla(theme::ACCENT)).child("●"))) + .child( + div() + .id(SharedString::from(format!("tab-close-{i}"))) + .rounded(px(3.0)) + .hover(|s| s.bg(hsla(0x2a2a2a))) + .invisible() + .when(shown, |d| d.visible()) + .group_hover(SharedString::from(format!("tab-{i}")), |s| s.visible()) + .child(icon(IconName::X, 12.0)) + .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { + cx.stop_propagation(); + ws.request_close_tab(&close, i, window, cx); + })), + ) + }); + div() + .id("tabs") + .flex_none() + .h(px(30.0)) + .flex() + .overflow_x_scroll() + .border_b_1() + .border_color(hsla(theme::BORDER)) + .children(tabs) + .into_any_element() +} + +/// Above the editor when the file and the buffer disagree: reload from disk, or keep the buffer and save over it later. +fn render_conflict(id: &crate::store::Id, path: &std::path::Path, conflict: Conflict, cx: &mut Context) -> AnyElement { + let text = match conflict { + Conflict::Changed => "This file changed on disk while you had unsaved edits.", + Conflict::Deleted => "This file was deleted on disk.", + }; + let (reload_id, reload_path, keep_id, keep_path) = (id.clone(), path.to_path_buf(), id.clone(), path.to_path_buf()); + div() + .flex_none() + .flex() + .items_center() + .justify_between() + .gap(px(8.0)) + .px(px(12.0)) + .py(px(6.0)) + .bg(hsla(0x1d1512)) + .border_b_1() + .border_color(hsla(0x3a2a24)) + .text_size(crate::panels::scale::px(12.0)) + .text_color(hsla(theme::WARN)) + .child(text) + .child( + div() + .flex() + .gap(px(6.0)) + .when(conflict == Conflict::Changed, |d| { + d.child(button("conflict-reload", "Reload", false).on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { + ws.reload_tab(&reload_id, reload_path.clone(), window, cx) + }))) + }) + .child(button("conflict-keep", "Keep mine", true).on_click(cx.listener(move |ws, _: &ClickEvent, _w, cx| ws.keep_mine(&keep_id, &keep_path, cx)))), + ) + .into_any_element() +} + +/// The quick open / find in files box: a field over a list, Up/Down to move, Enter to open, Escape to close. +fn render_picker(p: &Picker, root: &std::path::Path, cx: &mut Context) -> AnyElement { + let start = p.selected.saturating_sub(VISIBLE_ROWS - 1); + let rows = p.hits.iter().enumerate().skip(start).take(VISIBLE_ROWS).map(|(i, hit)| { + let (label, detail) = match p.kind { + PickerKind::Files => (hit.text.clone(), None), + PickerKind::Text => (format!("{}:{}", relative(&hit.path, root), hit.line + 1), Some(hit.text.clone())), + }; + div() + .id(SharedString::from(format!("picked-{i}"))) + .flex() + .flex_col() + .px(px(10.0)) + .py(px(4.0)) + .rounded(px(5.0)) + .cursor_pointer() + .when(i == p.selected, |d| d.bg(hsla(theme::ROW_ACTIVE))) + .hover(|s| s.bg(hsla(theme::ROW_HOVER))) + .child(div().text_size(crate::panels::scale::px(12.5)).overflow_hidden().whitespace_nowrap().text_ellipsis().child(label)) + .children(detail.map(|d| { + div().text_size(crate::panels::scale::px(11.5)).text_color(hsla(theme::TEXT_DIM)).overflow_hidden().whitespace_nowrap().text_ellipsis().child(d) + })) + .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { + ws.pick(i, cx); + ws.choose_picked(window, cx); + })) + }); + let list = div() + .flex() + .flex_col() + .gap(px(4.0)) + .capture_key_down(cx.listener(|ws, ev: &KeyDownEvent, _w, cx| { + match ev.keystroke.key.as_str() { + "up" => ws.move_picked(-1, cx), + "down" => ws.move_picked(1, cx), + _ => return, + } + cx.stop_propagation(); + })) + .child(Input::new(&p.input)) + .child(div().flex().flex_col().children(rows)); + floating("picker", list, |ws, window, cx| ws.close_picker(window, cx), cx) +} + +/// A box floating near the top of the editor pane (quick open, find in files); Escape closes it. +fn floating( + id: &'static str, + content: impl IntoElement, + close: impl Fn(&mut Workspace, &mut gpui::Window, &mut Context) + 'static, + cx: &mut Context, +) -> AnyElement { + div() + .absolute() + .top(px(36.0)) + .left_0() + .right_0() + .flex() + .justify_center() + .child( + div() + .id(id) + .occlude() + .w(px(560.0)) + .max_w_full() + .p(px(6.0)) + .rounded(px(8.0)) + .bg(hsla(0x181818)) + .border_1() + .border_color(hsla(0x2c2c2c)) + .shadow_lg() + .capture_key_down(cx.listener(move |ws, ev: &KeyDownEvent, window, cx| { + if ev.keystroke.key == "escape" { + close(ws, window, cx); + cx.stop_propagation(); + } + })) + .child(content), + ) + .into_any_element() +} + +const VISIBLE_ROWS: usize = 12; + +/// Source code, prose, or anything else. +fn file_icon(path: &std::path::Path) -> IconName { + match crate::files::language(path) { + Some("markdown") => IconName::FileText, + Some(_) => IconName::FileCode, + None if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("txt")) => IconName::FileText, + None => IconName::File, + } +} + +fn centered(text: String) -> AnyElement { + div() + .size_full() + .flex() + .items_center() + .justify_center() + .px(px(24.0)) + .text_size(crate::panels::scale::px(12.5)) + .text_color(hsla(theme::TEXT_FAINT)) + .child(text) + .into_any_element() +} diff --git a/src/panels/inspector.rs b/src/panels/inspector.rs index 8dca3eb..82f1e9b 100644 --- a/src/panels/inspector.rs +++ b/src/panels/inspector.rs @@ -10,14 +10,15 @@ use gpui::{ use std::time::Duration; -use gpui::{Animation, AnimationExt}; +use gpui::{Animation, AnimationExt, prelude::FluentBuilder}; use crate::app::{Act, GitOp, MenuItem, SideDrag, Workspace}; use crate::panels::widgets::{Trigger, button}; use crate::platform::Editor; +use crate::github::model::State; use crate::store::{Attached, Id, Project, SessionKind, SessionRecord}; use crate::panels::theme::{self, hsla}; -use crate::panels::widgets::{countdown, icon, icon_button, meter, section_label, tick}; +use crate::panels::widgets::{countdown, icon, icon_button, key_hint, meter, section_label, tick}; use gpui_kit::assets::IconName; /// What the top bar and the right sidebar describe: the shown session and the folder and project it is in. @@ -36,7 +37,7 @@ impl Workspace { } pub fn render_right(&mut self, window_w: f32, window: &mut Window, cx: &mut Context) -> Option { - let open = self.right_reveal.step(!self.store.data.layout.right_hidden, window); + let open = self.right_reveal.step(!self.store.data.layout.right_hidden && !self.editing(), window); if open <= 0.0 { return None; } @@ -272,6 +273,7 @@ impl Workspace { let target = shown.project.as_ref().map(|p| p.path.clone()).or_else(|| shown.cwd.clone()); let repo = shown.project.as_ref().filter(|p| p.git.is_some()).and(shown.cwd.clone()); let busy = self.git_busy; + let hints = self.shortcuts_shown; let mut actions = div().flex().flex_col().gap(px(1.0)); if let Some(target) = target { @@ -302,6 +304,14 @@ impl Workspace { )), ); } + // Editor mode works on the shown session's folder, so it needs a session; also in the top bar. + if id.is_some() { + actions = actions.child( + row("editor-mode", IconName::FileCode, "Editor mode") + .when(hints, |d| d.child(key_hint("Shift+E"))) + .on_click(cx.listener(|ws, _: &ClickEvent, window, cx| ws.act(Act::ToggleEditor, window, cx))), + ); + } actions = actions.child( row("reveal", IconName::FolderOpen, "Open folder") .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| ws.act(Act::Reveal(target.clone()), window, cx))), @@ -318,7 +328,10 @@ impl Workspace { } }; // The commit message is written through the running session's mod, so it needs one. + // Until it has been read, assume there is work. + let nothing_to_do = self.pending.as_ref().is_some_and(|(dir, p)| *dir == repo && !p.any()); let commit = match id.filter(|_| running && claude) { + Some(_) if nothing_to_do && busy.is_none() => dim_row("commit-push", IconName::GitCommitHorizontal, "Commit & Push · nothing to commit or push"), Some(id) => { let id = id.clone(); git_row(cx, "commit-push", IconName::GitCommitHorizontal, "Commit & Push", "Committing…", GitOp::CommitPush, Box::new(move |cwd| Act::CommitPush(id.clone(), cwd))) @@ -331,12 +344,14 @@ impl Workspace { let open = self.shells.get(&id).is_some_and(|p| p.open); actions = actions.child( row("shell", IconName::Terminal, if open { "Hide shell" } else { "Show shell" }) + .when(hints, |d| d.child(key_hint("J"))) .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| ws.act(Act::ToggleShell(id.clone()), window, cx))), ); } let cwd = self.active_cwd(); actions.child( row("github", IconName::GitPullRequest, "GitHub") + .when(hints, |d| d.child(key_hint("Shift+G"))) .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| ws.act(Act::OpenGithub { cwd: cwd.clone() }, window, cx))), ) } @@ -347,7 +362,12 @@ impl Workspace { for a in attached { let (pull, number) = (a.pull, a.number); let owner = id.cloned(); - let title = a.title.map_or_else(|| format!("#{number}"), |t| format!("#{number} {t}")); + let title = match (a.title, a.state) { + (None, _) => format!("#{number}"), + (Some(t), Some(State::Closed)) => format!("#{number} {t} (closed)"), + (Some(t), Some(State::Merged)) => format!("#{number} {t} (merged)"), + (Some(t), _) => format!("#{number} {t}"), + }; let key = format!("attached-{pull}-{number}"); rows = rows.child(removable_row( cx, @@ -411,9 +431,9 @@ impl Workspace { // The figures come from the snapshot the session's mod reports. let meta = shown.rec.as_ref().filter(|r| r.kind == SessionKind::Claude).and_then(|r| r.claude.as_ref()); - let (compact, advisor, active, chrome, known) = match meta { - Some(m) => (m.auto_compact, m.advisor.clone(), m.advisor_active.clone(), m.chrome, true), - None => (None, None, None, false, false), + let (compact, precompute, advisor, active, chrome, known) = match meta { + Some(m) => (m.auto_compact, m.precompute_compact, m.advisor.clone(), m.advisor_active.clone(), m.chrome, true), + None => (None, None, None, None, false, false), }; let advisor = advisor.map(|a| a.to_lowercase()); let active = active.map(|a| a.to_lowercase()); @@ -425,6 +445,14 @@ impl Workspace { Some(sid) => pick_row(cx, "set-auto-compact", "Auto-compact", compact_text, move || auto_compact_menu(&sid, compact)).into_any_element(), None => kv("Auto-compact", compact_text).into_any_element(), }; + // Only while Claude Code offers the setting; without its feature flag the setting does nothing. + let precompute_row = precompute.map(|on| { + let text = if on { "On" } else { "Off" }.to_string(); + match settable.clone() { + Some(sid) => pick_row(cx, "set-precompute-compact", "Background compaction", text, move || precompute_compact_menu(&sid, on)).into_any_element(), + None => kv("Background compaction", text).into_any_element(), + } + }); let chrome_row = match settable.clone() { Some(sid) => pick_row(cx, "set-chrome", "Claude in Chrome", if chrome { "On" } else { "Off" }.into(), move || chrome_menu(&sid, chrome)).into_any_element(), None => kv("Claude in Chrome", if chrome { "On" } else { "Off" }.into()).into_any_element(), @@ -440,7 +468,7 @@ impl Workspace { .px(px(8.0)) .child(meter("CONTEXT", ctx_fraction, ctx_caption, None)) .child(cache) - .child(div().flex().flex_col().gap(px(2.0)).child(compact_row).child(advisor_row).child(chrome_row)) + .child(div().flex().flex_col().gap(px(2.0)).child(compact_row).children(precompute_row).child(advisor_row).child(chrome_row)) } } @@ -448,6 +476,10 @@ fn auto_compact_menu(sid: &Id, current: Option) -> Vec { [(true, "On"), (false, "Off")].into_iter().map(|(on, name)| MenuItem::new(format!("{}{name}", tick(current == Some(on))), Act::SetAutoCompact(sid.clone(), on))).collect() } +fn precompute_compact_menu(sid: &Id, current: bool) -> Vec { + [(true, "On"), (false, "Off")].into_iter().map(|(on, name)| MenuItem::new(format!("{}{name}", tick(current == on)), Act::SetPrecomputeCompact(sid.clone(), on))).collect() +} + /// Off, the two aliases, and "Other…" (ticked for any other model) which asks for a name. fn chrome_menu(sid: &Id, current: bool) -> Vec { [(true, "On"), (false, "Off")].into_iter().map(|(on, name)| MenuItem::new(format!("{}{name}", tick(current == on)), Act::SetChrome(sid.clone(), on))).collect() @@ -636,6 +668,7 @@ mod tests { let sid = "s".to_string(); assert_eq!(labels(&auto_compact_menu(&sid, Some(false))), [" On", "✓ Off"]); assert_eq!(labels(&auto_compact_menu(&sid, None)), [" On", " Off"]); + assert_eq!(labels(&precompute_compact_menu(&sid, true)), ["✓ On", " Off"]); assert_eq!(labels(&advisor_menu(&sid, None)), ["✓ Off", " Opus", " Sonnet", " Other…"]); assert_eq!(labels(&advisor_menu(&sid, Some("sonnet"))), [" Off", " Opus", "✓ Sonnet", " Other…"]); assert_eq!(labels(&advisor_menu(&sid, Some("claude-opus-5-5"))), [" Off", "✓ Opus", " Sonnet", " Other…"]); diff --git a/src/panels/mod.rs b/src/panels/mod.rs index 92cf4d8..590a8a0 100644 --- a/src/panels/mod.rs +++ b/src/panels/mod.rs @@ -1,7 +1,8 @@ //! What Claudiu draws around the terminals. `workspace_view` is the root view (main area, overlays, toasts), `sidebar` -//! and `inspector` are the two side panels, `widgets` holds the small shared pieces. `theme` and `scale` set the look, -//! and `glide` does the smooth scrolling. +//! and `inspector` are the two side panels, `editor_pane` is editor mode's files and editor, `widgets` holds the small +//! shared pieces. `theme` and `scale` set the look, and `glide` does the smooth scrolling. +pub mod editor_pane; pub mod glide; pub mod inspector; pub mod scale; diff --git a/src/panels/sidebar.rs b/src/panels/sidebar.rs index dc90b53..9aa50eb 100644 --- a/src/panels/sidebar.rs +++ b/src/panels/sidebar.rs @@ -13,14 +13,12 @@ use crate::app::{Act, Activity, MenuItem, SideDrag, Workspace}; use crate::store::{ExternalState, Id, Project, SessionKind, SessionRecord, now}; use crate::panels::theme::{self, hsla}; use gpui_kit::assets::IconName; -use crate::panels::widgets::{Trigger, ago, avatar, button, clawd, countdown, icon, icon_button, meter, section_label, tick}; +use crate::panels::widgets::{Trigger, ago, avatar, button, clawd, countdown, icon, icon_button, key_hint, meter, section_label, shortcut, tick}; pub const SIDEBAR_W: f32 = 284.0; pub const SIDEBAR_MIN: f32 = 220.0; pub const SIDEBAR_MAX: f32 = 520.0; /// The account warning's entrance: its height at the end of the expand (the box grows to it), and its duration. -const OFFER_H: f32 = 72.0; -const OFFER_MS: u64 = 260; /// Entries shown under RECENT before the rest go behind OLDER. const RECENT_LIMIT: usize = 12; @@ -290,6 +288,7 @@ impl Workspace { let click_id = id.clone(); let menu_id = id.clone(); let close_id = id.clone(); + let middle_id = id.clone(); let archive_id = id.clone(); let dot =session_dot(row.dot, row.scope, &id); div() @@ -341,7 +340,12 @@ impl Workspace { .child(if row.archived { "archived".to_string() } else if row.stale { "stale".to_string() } else { row.right }), ) .when(row.running, |d| { - d.child( + // A middle click ends a running session, like its ×. + d.on_mouse_up( + MouseButton::Middle, + cx.listener(move |ws, _: &gpui::MouseUpEvent, window, cx| ws.act(Act::CloseLive(middle_id.clone()), window, cx)), + ) + .child( icon_button(gpui::SharedString::from(format!("close-{}-{close_id}", row.scope)), IconName::X) .invisible() .group_hover("row", |s| s.visible()) @@ -386,13 +390,21 @@ impl Workspace { let filter = self.project_filter().map(|p| p.id.clone()); // ---- RUNNING - let running: Vec = self - .live + let numbered = self.running_ids(cx); + let running: Vec = numbered .iter() - .filter(|l| l.view.read(cx).is_running()) - .filter_map(|l| self.store.session(&l.id)) + .filter_map(|id| self.store.session(id)) .filter(|r| self.listed(&q, filter.as_ref(), r)) - .map(|r| self.row_for(r, true, true)) + .map(|r| { + let mut row = self.row_for(r, true, true); + // Numbered among all running sessions, so a search or project filter doesn't renumber them. + if self.shortcuts_shown + && let Some(n) = numbered.iter().position(|id| *id == r.id).filter(|&i| i < 9) + { + row.right = shortcut(&(n + 1).to_string()); + } + row + }) .collect(); // ---- RECENT: everything else, newest first @@ -579,6 +591,7 @@ impl Workspace { fn render_sidebar_header(&mut self, cx: &mut Context) -> impl IntoElement + use<> { // With a project chosen a new session starts there (and the button says so); with "All projects" it asks. let filter = self.project_filter().map(|p| p.name.clone()); + let hints = self.shortcuts_shown; let label = match filter { Some(name) => format!("+ New in {}", if name.chars().count() > 12 { format!("{}…", name.chars().take(11).collect::()) } else { name }), None => "+ New".to_string(), @@ -598,6 +611,7 @@ impl Workspace { .px(px(2.0)) .child(clawd(24.0)) .child(div().flex_1().text_size(crate::panels::scale::px(13.0)).font_weight(FontWeight::BOLD).text_color(hsla(theme::TEXT)).child("CLAUDIU")) + .when(hints, |d| d.child(key_hint(","))) .child(icon_button("settings", IconName::Settings).occlude().on_click(cx.listener(|ws, _: &ClickEvent, window, cx| ws.act(Act::OpenSettings, window, cx)))), ) .child( @@ -618,7 +632,8 @@ impl Workspace { ws.open_dropdown(at, items, cx); } }, - )), + )) + .when(hints, |d| d.items_center().child(key_hint("Shift+N"))), ) .child(self.render_project_filter(cx)) .child( @@ -626,7 +641,8 @@ impl Workspace { Input::new(&self.search_input) .h(px(26.0)) .text_size(crate::panels::scale::px(12.5)) - .prefix(div().text_color(hsla(theme::TEXT_FAINT)).child(icon(IconName::Search, 14.0))), + .prefix(div().text_color(hsla(theme::TEXT_FAINT)).child(icon(IconName::Search, 14.0))) + .when(hints, |i| i.suffix(key_hint("Shift+F"))), ), ) } @@ -710,7 +726,6 @@ impl Workspace { fn render_footer(&self, cx: &mut Context) -> impl IntoElement + use<> { let t = now(); let usage = self.store.active_account().map(|a| a.usage.clone()).unwrap_or_default(); - let offer = self.switch_offer(); // Captions are short: two meters share a row. let limit = |label: &str, l: &Option| -> Div { @@ -740,29 +755,6 @@ impl Workspace { .pb(px(8.0)) .border_t_1() .border_color(hsla(theme::BORDER)) - // Stays while the limit is high (no toast); the button only opens the account menu. - .children(offer.map(|o| { - let ease = || Animation::new(Duration::from_millis(OFFER_MS)).with_easing(ease_out_quint()); - // Slides up into place while the section above it grows upward (the box is clipped from below). - let body = div() - .relative() - .flex() - .flex_col() - .gap(px(6.0)) - .child(div().text_size(crate::panels::scale::px(12.0)).text_color(hsla(theme::WARN)).child(o)) - .child(button("switch-offer", "Choose account", true).dropdown(cx, |ws, at, _window, cx| { - let items = ws.account_menu(); - ws.open_dropdown(at, items, cx); - })) - .with_animation("switch-offer-slide", ease(), |d, t| d.top(px((1.0 - t) * 14.0)).opacity(t)); - div() - .flex() - .flex_col() - .justify_end() - .overflow_hidden() - .child(body) - .with_animation("switch-offer-expand", ease(), |d, t| if t < 1.0 { d.h(px(OFFER_H * t)) } else { d }) - })) .child(self.render_account_switcher(cx)) .child(pair(limit("5 HOUR", &usage.five_hour), limit("7 DAY", &usage.seven_day))) } diff --git a/src/panels/widgets.rs b/src/panels/widgets.rs index f9a627d..1ac9b86 100644 --- a/src/panels/widgets.rs +++ b/src/panels/widgets.rs @@ -226,6 +226,28 @@ pub fn icon_button(id: impl Into, glyph: IconName) -> Stateful
String { + shortcut_for(cfg!(target_os = "macos"), keys) +} + +fn shortcut_for(macos: bool, keys: &str) -> String { + if macos { format!("⌘{}", keys.replace("Shift+", "⇧")) } else { format!("Ctrl+{keys}") } +} + +/// The small key label drawn beside a control while Ctrl (Cmd) is held. +pub fn key_hint(keys: &str) -> Div { + div() + .flex_none() + .px(px(4.0)) + .rounded(px(4.0)) + .bg(hsla(0x26262a)) + .text_size(crate::panels::scale::px(10.5)) + .text_color(hsla(theme::TEXT_DIM)) + .whitespace_nowrap() + .child(shortcut(keys)) +} + /// Monogram avatar: the first letter of `seed` on a color picked from it, so each account keeps its color. pub fn avatar(seed: &str, size: f32) -> Div { const COLORS: [u32; 6] = [theme::ACCENT, 0x61afef, 0x98c379, 0xc678dd, 0xe5c07b, 0x56b6c2]; @@ -355,6 +377,14 @@ pub fn fade_in(el: E, key: impl Into) -> impl IntoElement + use<> { - let shortcut = |keys: &str, what: &str| { + let shortcut_row = |keys: &str, what: &str| { div() .flex() .justify_between() @@ -336,10 +343,10 @@ impl Workspace { .flex() .flex_col() .gap(px(4.0)) - .child(shortcut("Ctrl+Shift+N", "New code session")) - .child(shortcut("Ctrl+`", "Show or hide shell")) - .child(shortcut("Ctrl+Tab", "Next session")) - .child(shortcut("Ctrl+Shift+W", "End session")), + .child(shortcut_row(&shortcut("Shift+N"), "New code session")) + .child(shortcut_row(&shortcut("J"), "Show or hide shell")) + .child(shortcut_row("Ctrl+Tab", "Next session")) + .child(shortcut_row(&shortcut("Shift+W"), "End session")), ) } @@ -351,6 +358,7 @@ impl Workspace { let mut card = div() .id("menu") .occlude() + .cursor_default() .w(px(232.0)) .min_w(menu.min_w) .p(px(4.0)) @@ -402,7 +410,7 @@ impl Workspace { .on_mouse_down(MouseButton::Right, cx.listener(close)) .child(anchored().position(pos).snap_to_window_with_margin(px(8.0)).child(fade_in(card, "menu-in", 110, 0.0))), ) - .with_priority(10) + .with_priority(25) .into_any_element(), ) } @@ -417,71 +425,7 @@ impl Workspace { confirm.clone(), *danger, ), - Modal::Settings { shell, claude, updates, scale } => { - let toggle = |on: bool| if on { "On" } else { "Off" }; - ( - "Settings".into(), - div() - .flex() - .flex_col() - .gap(px(10.0)) - .child(div().flex().flex_col().gap(px(4.0)).child(section_label("SHELL".to_string())).child(Input::new(shell))) - .child(div().flex().flex_col().gap(px(4.0)).child(section_label("CLAUDE CODE PATH".to_string())).child(Input::new(claude))) - .child( - div() - .h(px(32.0)) - .px(px(10.0)) - .flex() - .items_center() - .justify_between() - .rounded(px(6.0)) - .bg(hsla(0x111111)) - .border_1() - .border_color(hsla(0x242424)) - .text_size(px(13.0)) - .child("Scale (text and terminal)") - .child( - div() - .flex() - .items_center() - .gap(px(10.0)) - .child(scale_step("scale-down", "−", -(crate::panels::scale::STEP as i32), cx)) - .child(div().w(px(40.0)).flex().justify_center().child(format!("{scale}%"))) - .child(scale_step("scale-up", "+", crate::panels::scale::STEP as i32, cx)), - ), - ) - .child( - div() - .id("settings-updates") - .h(px(32.0)) - .px(px(10.0)) - .flex() - .items_center() - .justify_between() - .rounded(px(6.0)) - .bg(hsla(0x111111)) - .border_1() - .border_color(hsla(0x242424)) - .text_size(crate::panels::scale::px(13.0)) - .cursor_pointer() - .child("Check for updates") - .child(div().text_color(hsla(if *updates { theme::ACCENT } else { theme::TEXT_FAINT })).child(toggle(*updates))) - .on_click(cx.listener(|ws, _: &ClickEvent, _w, cx| { - if let Some(Modal::Settings { updates, .. }) = ws.modal.as_mut() { - *updates = !*updates; - } - cx.notify(); - })), - ) - .child(div().text_size(crate::panels::scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(format!( - "Claudiu {} · An independent project, not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic.", - env!("CARGO_PKG_VERSION") - ))) - .into_any_element(), - "Save".into(), - false, - ) - } + Modal::Settings { .. } => ("Settings".into(), settings_body(self.settings_page, modal, cx), "Save".into(), false), Modal::Advisor { input, .. } => ( "Advisor model".into(), div() @@ -494,6 +438,22 @@ impl Workspace { "Set".into(), false, ), + Modal::FileName { purpose, input, .. } => ( + match purpose { + crate::app::NameFor::FileIn(_) => "New file", + crate::app::NameFor::FolderIn(_) => "New folder", + crate::app::NameFor::Rename(_) => "Rename", + } + .into(), + Input::new(input).into_any_element(), + match purpose { + crate::app::NameFor::FileIn(_) | crate::app::NameFor::FolderIn(_) => "Create", + crate::app::NameFor::Rename(_) => "Rename", + } + .into(), + false, + ), + Modal::GoToLine { input, .. } => ("Go to line".into(), Input::new(input).into_any_element(), "Go".into(), false), Modal::Rename { input, .. } | Modal::NewBranch { input, .. } => ( if matches!(modal, Modal::NewBranch { .. }) { "New branch" } else { "Rename session" }.into(), Input::new(input).into_any_element(), @@ -505,7 +465,11 @@ impl Workspace { .id("modal-card") .occlude() .track_focus(&self.modal_focus) - .w(px(if matches!(modal, Modal::Settings { .. }) { 520.0 } else { 420.0 })) + .when(matches!(modal, Modal::Settings { .. }), |c| { + // One size for every page, growing with Scale. + c.w(crate::panels::scale::px(720.0)).h(crate::panels::scale::px(480.0)) + }) + .when(!matches!(modal, Modal::Settings { .. }), |c| c.w(px(420.0))) .p(px(20.0)) .rounded(px(12.0)) .bg(hsla(0x151515)) @@ -515,6 +479,7 @@ impl Workspace { .flex() .flex_col() .gap(px(12.0)) + .capture_key_down(cx.listener(|ws, ev: &KeyDownEvent, window, cx| ws.settings_key(ev, window, cx))) .on_key_down(cx.listener(|ws, ev: &KeyDownEvent, window, cx| { let key = ev.keystroke.key.as_str(); match (key, ws.modal.as_ref()) { @@ -576,6 +541,8 @@ impl Workspace { div().absolute().bottom(px(18.0)).right(px(18.0)).child( fade_in( div() + .occlude() + .cursor_default() .max_w(px(420.0)) .px(px(14.0)) .py(px(10.0)) @@ -611,7 +578,8 @@ impl Render for Workspace { self.window_title = title; } - let left_open = self.left_reveal.step(self.store.data.layout.sidebar_visible, window); + // Editor mode hides both sidebars without changing the remembered layout, so leaving it brings them back. + let left_open = self.left_reveal.step(self.store.data.layout.sidebar_visible && !self.editing(), window); let left_w = self.left_width(f32::from(window.viewport_size().width)); let sidebar = (left_open > 0.0).then(|| { div() @@ -637,6 +605,8 @@ impl Render for Workspace { } let right = self.render_right(f32::from(window.viewport_size().width), window, cx); let shell = self.render_shell(window, cx); + let editor = self.render_editor_pane(cx); + let window_w = f32::from(window.viewport_size().width); let main: AnyElement = match &self.main { Main::Terminals => self.render_session(cx), Main::Home => self.render_home(cx).into_any_element(), @@ -672,14 +642,17 @@ impl Render for Workspace { } })) .on_action(cx.listener(|ws, _: &NextSession, window, cx| ws.cycle(1, window, cx))) + .on_action(cx.listener(|ws, a: &crate::app::ShowSession, window, cx| ws.show_numbered(a.0, window, cx))) + .on_modifiers_changed(cx.listener(|ws, ev: &gpui::ModifiersChangedEvent, _w, cx| ws.modifiers_changed(&ev.modifiers, cx))) .on_action(cx.listener(|ws, _: &PrevSession, window, cx| ws.cycle(-1, window, cx))) - .on_action(cx.listener(|ws, _: &ToggleSidebar, _w, cx| { - ws.store.data.layout.sidebar_visible = !ws.store.data.layout.sidebar_visible; - ws.store.mark_dirty(); - cx.notify(); - })) + .on_action(cx.listener(|ws, _: &ToggleSidebar, _w, cx| ws.toggle_left(cx))) .on_action(cx.listener(|ws, _: &ToggleRight, window, cx| ws.toggle_right(window, cx))) .on_action(cx.listener(|ws, _: &FocusSearch, window, cx| { + // In editor mode the search that fits is the session's files. + if ws.editing() { + ws.open_picker(crate::app::picker::PickerKind::Text, window, cx); + return; + } ws.store.data.layout.sidebar_visible = true; ws.search_input.update(cx, |s, cx| s.focus(window, cx)); cx.notify(); @@ -691,6 +664,7 @@ impl Render for Workspace { })) .on_action(cx.listener(|ws, _: &OpenSettings, window, cx| ws.act(Act::OpenSettings, window, cx))) .on_action(cx.listener(|ws, _: &SwapFocus, window, cx| ws.swap_focus(window, cx))) + .on_action(cx.listener(|ws, _: &ToggleEditor, window, cx| ws.act(Act::ToggleEditor, window, cx))) .on_mouse_move(cx.listener(|ws, ev: &gpui::MouseMoveEvent, window, cx| { if ws.shell_drag.is_none() && ws.right_drag.is_none() && ws.left_drag.is_none() { return; @@ -743,7 +717,16 @@ impl Render for Workspace { .min_h_0() .children(sidebar) .child( - div().flex().flex_col().flex_1().min_w_0().h_full().child( + div() + .flex() + .flex_col() + .h_full() + // In editor mode the terminal narrows to the left and the editor takes the rest. + .map(|d| match editor.is_some() { + true => d.flex_none().w(px((window_w * 0.36).clamp(380.0, 640.0))), + false => d.flex_1().min_w_0(), + }) + .child( div() .flex() .flex_col() @@ -759,6 +742,7 @@ impl Render for Workspace { ) .children(shell), ) + .when_some(editor, |d, editor| d.child(div().flex_none().w(px(theme::PANEL_GAP))).child(editor)) .children(right), ), ) @@ -768,6 +752,226 @@ impl Render for Workspace { } } +/// The Settings dialog's body: the category list on the left and the chosen page on the right. +fn settings_body(page: SettingsPage, modal: &Modal, cx: &mut Context) -> AnyElement { + let Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, list_focus } = modal else { + return div().into_any_element(); + }; + let (updates, chrome, scale) = (*updates, *chrome, *scale); + let scaled = crate::panels::scale::px; + let faint = |text: String| div().text_size(scaled(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(text); + let field = |label: &str, input: &Entity| { + div().flex().flex_col().gap(px(4.0)).child(section_label(label.to_string())).child(Input::new(input)) + }; + let content = match page { + SettingsPage::General => div() + .flex() + .flex_col() + .gap(px(10.0)) + .child(field("SHELL", shell)) + .child(field("CLAUDE CODE PATH", claude)) + .child( + div() + .h(px(32.0)) + .px(px(10.0)) + .flex() + .items_center() + .justify_between() + .rounded(px(6.0)) + .bg(hsla(0x111111)) + .border_1() + .border_color(hsla(0x242424)) + .text_size(px(13.0)) + .child("Scale (text and terminal)") + .child( + div() + .flex() + .items_center() + .gap(px(10.0)) + .child(scale_step("scale-down", "−", -(crate::panels::scale::STEP as i32), cx)) + .child(div().w(px(40.0)).flex().justify_center().child(format!("{scale}%"))) + .child(scale_step("scale-up", "+", crate::panels::scale::STEP as i32, cx)), + ), + ) + .child(settings_toggle("settings-updates", "Check for updates", updates, |m| match m { + Modal::Settings { updates, .. } => Some(updates), + _ => None, + }, cx)), + SettingsPage::Sessions => div() + .flex() + .flex_col() + .gap(px(10.0)) + .child(field("MODEL FOR NEW SESSIONS", model)) + .child(picker_row("settings-effort", "Effort", *effort, &Effort::ALL, Effort::name, Act::PickEffort, cx)) + .child(picker_row("settings-permission", "Permission mode", *permission, &PermissionMode::ALL, PermissionMode::name, Act::PickPermission, cx)) + .children((*permission == Some(PermissionMode::BypassPermissions)).then(|| faint("Every new session will run commands and edit files without asking.".to_string()))) + .children((*permission == Some(PermissionMode::Plan) && trimmed.contains(&Trim::PlanMode)).then(|| { + faint("Plan mode is off under Claude Code tools, so new sessions start in Claude Code's default mode.".to_string()) + })) + .child(settings_toggle("settings-chrome", "Claude in Chrome for new sessions", chrome, |m| match m { + Modal::Settings { chrome, .. } => Some(chrome), + _ => None, + }, cx)), + SettingsPage::ClaudeTools => { + let plan_trimmed = trimmed.contains(&Trim::PlanMode); + let mut list = div().flex().flex_col().gap(px(8.0)); + list = list.child(faint( + "Applies to new sessions. Running sessions keep their tools. Resumed sessions get the new tools, and the old instructions stay until their next compaction. These switches edit Claude Code's own settings.json, for every account and for Claude Code outside Claudiu. Claudiu only turns things off; anything you turned off yourself stays off." + .to_string(), + )); + for (heading, items) in Trim::GROUPS { + list = list.child(div().mt(px(4.0)).child(section_label(heading.to_string()))); + for &item in items { + list = list.child(switch_row(("settings-trim", item as usize), item.label(), !trimmed.contains(&item), move |ws| { + if let Some(Modal::Settings { trimmed, .. }) = ws.modal.as_mut() { + flip(trimmed, item); + } + }, cx)); + } + } + if plan_trimmed { + list = list.child(faint("With Plan mode off, Claude can't leave plan mode itself; press Shift+Tab.".to_string())); + } + list + } + SettingsPage::ClaudiuTools => { + let mut list = div().flex().flex_col().gap(px(8.0)).child(faint( + "Applies to new sessions. Running sessions keep their tools. Resumed sessions get the new tools, and the old instructions stay until their next compaction." + .to_string(), + )); + for feature in Feature::ALL { + list = list.child(switch_row(("settings-claudiu", feature as usize), feature.label(), !claudiu_off.contains(&feature), move |ws| { + if let Some(Modal::Settings { claudiu_off, .. }) = ws.modal.as_mut() { + flip(claudiu_off, feature); + } + }, cx)); + } + list + } + SettingsPage::About => div().child(faint(format!( + "Claudiu {} · An independent project, not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic.", + env!("CARGO_PKG_VERSION") + ))), + }; + let categories = SettingsPage::ALL.into_iter().enumerate().fold( + div().id("settings-categories").track_focus(list_focus).w(scaled(160.0)).flex_none().flex().flex_col().gap(px(2.0)), + |list, (i, p)| { + let selected = p == page; + let focus = list_focus.clone(); + list.child( + div() + .id(("settings-category", i)) + .h(scaled(28.0)) + .px(px(10.0)) + .flex() + .items_center() + .rounded(px(6.0)) + .text_size(scaled(13.0)) + .text_color(hsla(if selected { theme::ACCENT } else { theme::TEXT_DIM })) + .when(selected, |d| d.bg(hsla(0x1f1f1f))) + .cursor_pointer() + .hover(|s| s.bg(hsla(0x1f1f1f))) + .child(p.label()) + .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { + ws.settings_page = p; + window.focus(&focus, cx); + cx.notify(); + })), + ) + }, + ); + div() + .flex_1() + .min_h_0() + .flex() + .gap(px(16.0)) + .child(categories) + .child(div().id("settings-page").flex_1().min_w_0().overflow_y_scroll().child(content)) + .into_any_element() +} + +/// An On/Off row in the Settings modal; `field` picks the flag it flips. +fn settings_toggle(id: &'static str, label: &'static str, on: bool, field: fn(&mut Modal) -> Option<&mut bool>, cx: &mut Context) -> impl IntoElement { + switch_row(id, label, on, move |ws| { + if let Some(flag) = ws.modal.as_mut().and_then(field) { + *flag = !*flag; + } + }, cx) +} + +/// A row that opens a menu of `options` under itself; the first entry, "Claude Code default", clears the choice. +fn picker_row( + id: &'static str, + label: &'static str, + current: Option, + options: &'static [T], + name: fn(T) -> &'static str, + pick: fn(Option) -> Act, + cx: &mut Context, +) -> impl IntoElement { + const DEFAULT: &str = "Claude Code default"; + div() + .id(id) + .h(px(32.0)) + .px(px(10.0)) + .flex() + .items_center() + .justify_between() + .rounded(px(6.0)) + .bg(hsla(0x111111)) + .border_1() + .border_color(hsla(0x242424)) + .text_size(crate::panels::scale::px(13.0)) + .cursor_pointer() + .child(label) + .child(div().text_color(hsla(if current.is_some() { theme::ACCENT } else { theme::TEXT_FAINT })).child(current.map_or(DEFAULT, name))) + .dropdown(cx, move |ws, at, _window, cx| { + let items = std::iter::once(MenuItem::new(format!("{}{DEFAULT}", tick(current.is_none())), pick(None))) + .chain(options.iter().map(|&o| MenuItem::new(format!("{}{}", tick(current == Some(o)), name(o)), pick(Some(o))))) + .collect(); + ws.open_dropdown(at, items, cx); + }) +} + +/// Adds `item` to `items`, or removes it when it is there. +fn flip(items: &mut Vec, item: T) { + match items.iter().position(|i| *i == item) { + Some(at) => { + items.remove(at); + } + None => items.push(item), + } +} + +/// An On/Off row that runs `flip` on the workspace when clicked. +fn switch_row( + id: impl Into, + label: &'static str, + on: bool, + flip: impl Fn(&mut Workspace) + 'static, + cx: &mut Context, +) -> impl IntoElement { + div() + .id(id) + .h(px(32.0)) + .px(px(10.0)) + .flex() + .items_center() + .justify_between() + .rounded(px(6.0)) + .bg(hsla(0x111111)) + .border_1() + .border_color(hsla(0x242424)) + .text_size(crate::panels::scale::px(13.0)) + .cursor_pointer() + .child(label) + .child(div().text_color(hsla(if on { theme::ACCENT } else { theme::TEXT_FAINT })).child(if on { "On" } else { "Off" })) + .on_click(cx.listener(move |ws, _: &ClickEvent, _w, cx| { + flip(ws); + cx.notify(); + })) +} + /// A − / + button in the Settings modal that moves the scale by `by` percent, within the allowed range. fn scale_step(id: &'static str, label: &'static str, by: i32, cx: &mut Context) -> impl IntoElement { div().id(id).w(px(22.0)).h(px(22.0)).flex().items_center().justify_center().rounded(px(4.0)).cursor_pointer().hover(|s| s.bg(hsla(0x242424))).child(label).on_click( diff --git a/src/priority.rs b/src/priority.rs new file mode 100644 index 0000000..21db62b --- /dev/null +++ b/src/priority.rs @@ -0,0 +1,131 @@ +//! Windows only: run the programs Claude Code starts (bash, cargo, rustc, test binaries) below normal priority, so a +//! heavy build in one session cannot starve the other sessions' `claude` processes. A child inherits its parent's +//! priority class, so lowering a program once also covers what it starts later. + +/// Every process below `roots` in the parent/child tree, not including the roots. `processes` holds +/// `(pid, parent pid)` pairs. The `apps` and everything they started are left out: Claudiu itself may have been +/// started from a Claude session, and must not end up slower than the sessions it shows. +#[cfg_attr(not(windows), allow(dead_code))] +fn descendants(roots: &[u32], processes: &[(u32, u32)], apps: &[u32]) -> Vec { + let mut found: Vec = Vec::new(); + let mut parents: Vec = roots.to_vec(); + while let Some(parent) = parents.pop() { + for &(pid, parent_pid) in processes { + // Process ids get reused, so a stale parent id can make the tree loop back on itself. + if parent_pid == parent && !roots.contains(&pid) && !apps.contains(&pid) && !found.contains(&pid) { + found.push(pid); + parents.push(pid); + } + } + } + found +} + +/// Lower everything the given `claude` processes have started to below normal priority. The `claude` processes +/// themselves stay as they are, and so do descendants that already run at a non-default priority. +#[cfg(windows)] +pub fn lower_tool_priority(claude_pids: &[u32]) { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS, + }; + use windows_sys::Win32::System::Threading::{ + BELOW_NORMAL_PRIORITY_CLASS, GetPriorityClass, NORMAL_PRIORITY_CLASS, OpenProcess, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_INFORMATION, SetPriorityClass, + }; + + if claude_pids.is_empty() { + return; + } + let mut processes: Vec<(u32, u32)> = Vec::new(); + let mut apps: Vec = Vec::new(); + // SAFETY: `entry` is initialised with its size as the API requires, and the snapshot handle is closed below. + unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if snapshot == INVALID_HANDLE_VALUE { + return; + } + let mut entry: PROCESSENTRY32W = std::mem::zeroed(); + entry.dwSize = size_of::() as u32; + let mut more = Process32FirstW(snapshot, &mut entry) != 0; + while more { + processes.push((entry.th32ProcessID, entry.th32ParentProcessID)); + let name = String::from_utf16_lossy(&entry.szExeFile); + if name.trim_end_matches('\0').eq_ignore_ascii_case("claudiu.exe") { + apps.push(entry.th32ProcessID); + } + more = Process32NextW(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + } + for pid in descendants(claude_pids, &processes, &apps) { + // SAFETY: the handle is checked for null before use and closed after. + unsafe { + let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SET_INFORMATION, 0, pid); + if handle.is_null() { + continue; + } + if GetPriorityClass(handle) == NORMAL_PRIORITY_CLASS { + SetPriorityClass(handle, BELOW_NORMAL_PRIORITY_CLASS); + } + CloseHandle(handle); + } + } +} + +/// A process started from a Claude session inherits the tools' lowered priority; Claudiu, its window included, runs +/// at normal priority whatever started it. +#[cfg(windows)] +pub fn restore_own_priority() { + use windows_sys::Win32::System::Threading::{ + BELOW_NORMAL_PRIORITY_CLASS, GetCurrentProcess, GetPriorityClass, NORMAL_PRIORITY_CLASS, SetPriorityClass, + }; + // SAFETY: the pseudo handle of the current process is always valid. + unsafe { + let me = GetCurrentProcess(); + if GetPriorityClass(me) == BELOW_NORMAL_PRIORITY_CLASS { + SetPriorityClass(me, NORMAL_PRIORITY_CLASS); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_children_and_grandchildren_but_not_the_root() { + // claude 10 -> bash 11 -> cargo 12 -> rustc 13; 20 is another program's tree. + let processes = [(10, 1), (11, 10), (12, 11), (13, 12), (20, 1), (21, 20)]; + let mut found = descendants(&[10], &processes, &[]); + found.sort(); + assert_eq!(found, vec![11, 12, 13]); + } + + #[test] + fn leaves_other_claude_processes_alone() { + // Two claude processes under the same parent: neither is a descendant of the other. + let processes = [(10, 1), (30, 1), (11, 10), (31, 30)]; + let mut found = descendants(&[10, 30], &processes, &[]); + found.sort(); + assert_eq!(found, vec![11, 31]); + } + + #[test] + fn leaves_claudiu_and_what_it_started_alone() { + // claude 10 -> bash 11 -> claudiu 12 -> claude 13; the tools below the nested Claudiu are its own business. + let processes = [(10, 1), (11, 10), (12, 11), (13, 12), (14, 11)]; + let mut found = descendants(&[10], &processes, &[12]); + found.sort(); + assert_eq!(found, vec![11, 14]); + } + + #[test] + fn a_reused_pid_cannot_loop_forever() { + // 11 claims 12 as its parent and 12 claims 11, so the tree below 10 loops. + let processes = [(10, 1), (11, 10), (12, 11), (11, 12)]; + let mut found = descendants(&[10], &processes, &[]); + found.sort(); + assert_eq!(found, vec![11, 12]); + } +} diff --git a/src/store.rs b/src/store.rs index e80bdd7..e9adc6b 100644 --- a/src/store.rs +++ b/src/store.rs @@ -44,8 +44,11 @@ pub enum ExternalState { pub struct Attached { pub pull: bool, pub number: u32, + /// Both come from GitHub (`app/attached_sync.rs`), never from the model. #[serde(default)] pub title: Option, + #[serde(default)] + pub state: Option, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -69,9 +72,16 @@ pub struct ClaudeMeta { pub auto_compact: Option, #[serde(default)] pub advisor: Option, + /// Background compaction ("Precompute compaction" in `/config`); `None` while Claude Code does not offer it. + #[serde(default)] + pub precompute_compact: Option, /// Claude in Chrome: the session is (re)started with `--chrome`. Claudiu's own choice, so it survives restarts. #[serde(default)] pub chrome: bool, + /// The account this conversation runs under. It starts there again after closing it or restarting Claudiu, until a + /// hand-off moves it. `None` until Claudiu first starts it. + #[serde(default)] + pub account: Option, /// The advisor declared for the current conversation. A model change is saved in `advisor` at once but only /// becomes `advisor_active` on `/clear` or `/compact`; turning the advisor off/on changes it immediately. #[serde(default)] @@ -162,18 +172,6 @@ pub struct AccountUsage { pub seven_day: Option, } -impl AccountUsage { - /// The higher of the 5-hour and 7-day use that still applies at `now`; a window past its reset counts as 0. - pub fn peak(&self, now: i64) -> f32 { - [&self.five_hour, &self.seven_day] - .into_iter() - .flatten() - .filter(|l| l.resets_at.is_none_or(|r| r > now)) - .filter_map(|l| l.utilization) - .fold(0.0, f32::max) - } -} - impl Account { pub fn is_main(&self) -> bool { self.dir.is_none() @@ -248,6 +246,23 @@ pub struct Settings { /// UI scale in percent (text and terminal font); 100 when unset. #[serde(default)] pub scale: Option, + /// Whether new Claude sessions start with Claude in Chrome (`--chrome`); each session can still switch it. + #[serde(default)] + pub chrome_default: bool, + /// Model, effort and permission mode for new Claude sessions; empty fields leave Claude Code's own default. + #[serde(default)] + pub new_session: crate::claude::defaults::NewSessionDefaults, + /// Parts of Claudiu's own MCP server switched off for new sessions (`claude/mcp.rs`). Empty means everything is on, + /// which is also what a state file from before this setting loads as. + #[serde(default)] + pub claudiu_tools_off: Vec, + /// Claude Code features and tools switched off for the sessions Claudiu starts (`claude/trim.rs`). Empty means + /// nothing is trimmed, which is also what a state file from before this setting loads as. + #[serde(default)] + pub trimmed_tools: Vec, + /// The lines Claudiu added to Claude Code's `settings.json` for those trims, so turning one off removes only them. + #[serde(default)] + pub applied_trims: Vec, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -352,6 +367,14 @@ impl Store { self.data.active_account.as_deref().and_then(|id| self.account(id)).or_else(|| self.account(MAIN_ACCOUNT)) } + /// The account a session starts under: its own while that account exists, else the active one. + pub fn session_account(&self, session_id: &str) -> Option<&Account> { + self.session(session_id) + .and_then(|r| r.claude.as_ref()?.account.as_deref()) + .and_then(|id| self.account(id)) + .or_else(|| self.active_account()) + } + pub fn mark_dirty(&mut self) { self.dirty = true; } @@ -724,16 +747,6 @@ mod tests { assert_eq!(b.data.sessions[0].id, "cl"); } - #[test] - fn peak_usage_ignores_windows_that_have_reset() { - let lim = |u: f32, reset: Option| Some(RateLimit { utilization: Some(u), resets_at: reset, seen_at: 0 }); - let u = AccountUsage { five_hour: lim(0.9, Some(100)), seven_day: lim(0.4, Some(1000)) }; - assert_eq!(u.peak(50), 0.9); - assert_eq!(u.peak(500), 0.4, "the 5-hour window reset"); - assert_eq!(u.peak(5000), 0.0); - assert_eq!(AccountUsage::default().peak(0), 0.0, "unknown counts as unused"); - } - #[test] fn usage_from_before_accounts_moves_into_the_main_account() { let tmp = tempfile::tempdir().unwrap(); @@ -748,6 +761,36 @@ mod tests { assert_eq!(Store::load(path).data.accounts.len(), 1, "migrates once"); } + #[test] + fn a_session_starts_under_its_own_account_while_that_exists() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = Store::load(tmp.path().join("s.json")); + s.data.accounts.push(Account { id: "alt".into(), ..Default::default() }); + s.data.active_account = Some("alt".into()); + let session = |id: &str, account: Option<&str>| SessionRecord { + id: id.into(), + kind: SessionKind::Claude, + title: "Claude".into(), + custom_title: None, + auto_title: None, + cwd: PathBuf::from("/w"), + project_id: None, + created_at: 1, + last_active: 1, + exit_code: None, + hidden: false, + claude: Some(ClaudeMeta { session_id: id.into(), account: account.map(Into::into), ..Default::default() }), + }; + s.add_session(session("main-owned", Some(MAIN_ACCOUNT))); + s.add_session(session("never-started", None)); + s.add_session(session("removed-owner", Some("gone"))); + let account = |s: &Store, id: &str| s.session_account(id).map(|a| a.id.clone()); + assert_eq!(account(&s, "main-owned").as_deref(), Some(MAIN_ACCOUNT), "not the active alt"); + assert_eq!(account(&s, "never-started").as_deref(), Some("alt")); + assert_eq!(account(&s, "removed-owner").as_deref(), Some("alt")); + assert_eq!(account(&s, "not-yet-stored").as_deref(), Some("alt"), "a new session"); + } + #[test] fn save_load_roundtrip_and_corrupt_file_is_kept() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/terminal/mod.rs b/src/terminal/mod.rs index 4c9077e..f69f234 100644 --- a/src/terminal/mod.rs +++ b/src/terminal/mod.rs @@ -87,7 +87,8 @@ pub struct Terminal { start_error: Arc>>, cols: AtomicU32, rows: AtomicU32, - /// The child's process id (Unix; 0 until it exists), so closing can make sure it ends. + /// The child's process id (0 until it exists), so closing can make sure it ends (Unix) and its tools can be + /// lowered in priority (Windows). pid: Arc, /// When it was made, and what to call it in the start-up trace (`trace.rs`). pub born: Instant, @@ -121,8 +122,8 @@ fn start_pty( .map_err(|_| anyhow::anyhow!("the pseudo terminal could not be created"))??; #[cfg(unix)] pid.store(pty.child().id(), Ordering::Relaxed); - #[cfg(not(unix))] - let _ = pid; + #[cfg(windows)] + pid.store(pty.child_watcher().pid().map_or(0, |p| p.get()), Ordering::Relaxed); let event_loop = EventLoop::new(term, listener, pty, true, false)?; let sender = event_loop.channel(); event_loop.spawn(); @@ -199,6 +200,12 @@ impl Terminal { (this, rx) } + /// The child's process id, once it exists. + #[cfg(windows)] + pub fn process_id(&self) -> Option { + Some(self.pid.load(Ordering::Relaxed)).filter(|&pid| pid != 0) + } + /// Why the child could not be started, for a terminal made by `spawn_deferred`. pub fn start_error(&self) -> Option { self.start_error.lock().unwrap().clone() diff --git a/src/terminal/view/element.rs b/src/terminal/view/element.rs index d283b1a..919d847 100644 --- a/src/terminal/view/element.rs +++ b/src/terminal/view/element.rs @@ -113,6 +113,7 @@ impl Element for TerminalElement { let mut preedit_at = None; { + let hovered = self.view.read(cx).hovered_link.clone(); let terminal = &self.view.read(cx).terminal; let term = terminal.term.lock(); let content = term.renderable_content(); @@ -204,8 +205,9 @@ impl Element for TerminalElement { } // Text + let hovered_link = hovered.as_ref().is_some_and(|(r, columns)| *r == row && columns.as_ref().is_some_and(|c| c.contains(&col))); let underline = - cell.flags.intersects(Flags::ALL_UNDERLINES) || cell.hyperlink().is_some(); + cell.flags.intersects(Flags::ALL_UNDERLINES) || cell.hyperlink().is_some() || hovered_link; let ch = cell.c; if cell.flags.contains(Flags::HIDDEN) || (ch == ' ' && !underline) || ch == '\0' { continue; diff --git a/src/terminal/view/mod.rs b/src/terminal/view/mod.rs index b2f4db1..87a40a3 100644 --- a/src/terminal/view/mod.rs +++ b/src/terminal/view/mod.rs @@ -3,6 +3,7 @@ mod element; mod mouse; +mod paths; mod typing; use element::TerminalElement; @@ -38,6 +39,9 @@ use crate::panels::theme; pub enum TerminalEvent { Exited(Option), Bell, + /// Ctrl+click on a file path in the text, or on a `file:` link: the path as written (maybe relative to the + /// session's folder), and its line (1-based) when one was given. + OpenPath(String, Option), } #[derive(Clone, Copy)] @@ -49,6 +53,12 @@ struct Metrics { shift: Pixels, } +/// A session moving to another account: who to, and when it began (the old process compacts first, then restarts). +pub struct Handover { + pub to: String, + pub since: Instant, +} + pub struct TerminalView { pub terminal: Terminal, focus: FocusHandle, @@ -76,10 +86,27 @@ pub struct TerminalView { font_size: Pixels, /// Show a startup animation until the program first draws something (set for Claude sessions). pub loading: bool, - /// The account the session is handing over to: the skeleton says so until the new process is ready. - pub handover: Option, + /// The skeleton says the session is handing over until the new process is ready. + pub handover: Option, /// Whether a pane currently shows this terminal (kept up to date by the workspace's render). pub visible: bool, + /// A line Claudiu put into Claude's input for the user (`insert_reference`), until it is kept or taken back. + reference: Option, + /// While Ctrl is held over a link: its viewport row and the columns to underline (none when it is drawn as a link already). + hovered_link: Option<(usize, Option>)>, +} + +/// What Ctrl+click opens. +enum Link { + /// A file path and the line it names. + File(String, Option), + Url(String), +} + +struct Inserted { + chars: usize, + /// The user typed or pasted after it, so it can no longer be erased without erasing their text too. + typed: bool, } impl EventEmitter for TerminalView {} @@ -166,6 +193,8 @@ impl TerminalView { loading: false, handover: None, visible: true, + reference: None, + hovered_link: None, } } @@ -378,7 +407,7 @@ impl Render for TerminalView { } } let phase = match (&self.handover, self.handing, self.last_output) { - (Some(to), _, _) => format!("Handing over to {to}…"), + (Some(h), _, _) => format!("Handing over to {}…", h.to), (None, true, _) => "Handing your message to Claude Code…".into(), (None, false, Some(_)) => "Loading skills, plugins and MCP servers…".into(), (None, false, None) => "Starting Claude Code…".into(), @@ -405,13 +434,15 @@ impl Render for TerminalView { .on_mouse_up(MouseButton::Middle, cx.listener(Self::on_mouse_up)) .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up)) .on_mouse_move(cx.listener(Self::on_mouse_move)) + .when(self.hovered_link.is_some(), |d| d.cursor_pointer()) .on_scroll_wheel(cx.listener(Self::on_scroll)) .child(TerminalElement { view: cx.entity() }) .when(self.loading || self.handover.is_some(), |d| { let (cols, rows) = self.terminal.size(); let (cell_w, line_h) = self.metrics.map_or((8.0, LINE_H), |m| (f32::from(m.cell_w), f32::from(m.line_h))); let grid = skeleton::Grid { cell_w, line_h, cols, rows }; - d.child(skeleton::overlay(&self.draft, self.terminal.born.elapsed(), &phase, grid)) + let since = self.handover.as_ref().map_or(self.terminal.born, |h| h.since); + d.child(skeleton::overlay(&self.draft, since.elapsed(), &phase, grid)) }) } } diff --git a/src/terminal/view/mouse.rs b/src/terminal/view/mouse.rs index 3c30771..2de6b2c 100644 --- a/src/terminal/view/mouse.rs +++ b/src/terminal/view/mouse.rs @@ -88,6 +88,18 @@ impl TerminalView { return; }; + // Ctrl+click on a path or link opens it even when the program (Claude Code's full-screen view) has asked for the + // mouse; any other click goes to the program. + if event.button == MouseButton::Left && event.modifiers.control { + if let Some((link, _)) = self.link_at(point, col) { + match link { + Link::File(path, line) => cx.emit(TerminalEvent::OpenPath(path, line)), + Link::Url(url) => cx.open_url(&url), + } + return; + } + } + if self.mouse_reporting(&event.modifiers) { let button = match event.button { MouseButton::Left => 0, @@ -101,13 +113,6 @@ impl TerminalView { match event.button { MouseButton::Left => { - if event.modifiers.control { - let link = self.terminal.term.lock().grid()[point].hyperlink(); - if let Some(link) = link { - cx.open_url(link.uri()); - return; - } - } let ty = match event.click_count { 1 => SelectionType::Simple, 2 => SelectionType::Semantic, @@ -151,7 +156,35 @@ impl TerminalView { } } + /// The file path or link under `point` (at viewport `column`), and the columns to underline for it. + fn link_at(&self, point: GridPoint, column: usize) -> Option<(Link, Option>)> { + let (hyperlink, row) = { + let term = self.terminal.term.lock(); + let grid = term.grid(); + let row = &grid[point.line]; + (grid[point].hyperlink(), (0..grid.columns()).map(|c| row[Column(c)].c).collect::()) + }; + if let Some(link) = hyperlink { + let file = url::Url::parse(link.uri()).ok().filter(|u| u.scheme() == "file").and_then(|u| u.to_file_path().ok()); + // Cells of a link are underlined already. + return Some((match file { + Some(path) => Link::File(path.to_string_lossy().into_owned(), None), + None => Link::Url(link.uri().to_string()), + }, None)); + } + let (path, line, columns) = paths::path_at(&row, column)?; + Some((Link::File(path, line), Some(columns))) + } + pub(super) fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context) { + let hovered = self + .grid_point(event.position) + .filter(|_| event.modifiers.control) + .and_then(|(point, _, col, row)| self.link_at(point, col).map(|(_, columns)| (row, columns))); + if hovered != self.hovered_link { + self.hovered_link = hovered; + cx.notify(); + } if self.mouse_reporting(&event.modifiers) { let mode = self.mode(); let any_motion = mode.contains(TermMode::MOUSE_MOTION); diff --git a/src/terminal/view/paths.rs b/src/terminal/view/paths.rs new file mode 100644 index 0000000..93763eb --- /dev/null +++ b/src/terminal/view/paths.rs @@ -0,0 +1,82 @@ +//! File paths in the terminal's text, such as `src/main.rs:42` in Claude's reply, which Ctrl+click opens in the editor. + +/// The path-like word at `column` of `row`, the line it names (1-based) after `:12`, `:12:5` or `#L12-30`, and the +/// columns the word covers. Only what looks like a path (a `/`, `\` or a file extension in it, not a URL); whether the +/// file exists is for the caller to check. +pub fn path_at(row: &str, column: usize) -> Option<(String, Option, std::ops::Range)> { + let chars: Vec = row.chars().collect(); + let edge = |c: char| c.is_whitespace() || "\"'`()[]{}<>,│".contains(c); + if column >= chars.len() || edge(chars[column]) { + return None; + } + let start = chars[..column].iter().rposition(|&c| edge(c)).map_or(0, |i| i + 1); + let end = chars[column..].iter().position(|&c| edge(c)).map_or(chars.len(), |i| column + i); + let raw: String = chars[start..end].iter().collect(); + // A Claude Code reference, or the end of a sentence. + let unmarked = raw.trim_start_matches('@'); + let word = unmarked.trim_end_matches(['.', ';', ':', '!', '?']); + let first = start + raw.chars().count() - unmarked.chars().count(); + let columns = first..first + word.chars().count(); + if word.contains("://") { + return None; + } + let (path, line) = split_line(word); + let extension = path.rsplit_once('.').is_some_and(|(stem, ext)| !stem.is_empty() && !ext.is_empty() && ext.chars().all(char::is_alphanumeric)); + (path.contains(['/', '\\']) || extension).then(|| (path.to_string(), line, columns)) +} + +/// `path:12`, `path:12:5`, `path:12-30` or `path#L12-30` into the path and line 12. +fn split_line(word: &str) -> (&str, Option) { + if let Some((path, lines)) = word.split_once("#L") { + return (path, lines.split('-').next().and_then(|n| n.parse().ok())); + } + let digits = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()); + // `12` or `12-30`. + let lines = |s: &str| s.split_once('-').map_or(digits(s), |(first, last)| digits(first) && digits(last)); + // `path:12:5`: the column goes first. + let without_column = match word.rsplit_once(':') { + Some((rest, column)) if digits(column) && rest.rsplit_once(':').is_some_and(|(_, line)| digits(line)) => rest, + _ => word, + }; + // Only digits after the colon, so `C:\x` stays a drive. + match without_column.rsplit_once(':') { + Some((path, range)) if lines(range) && !path.is_empty() => (path, range.split('-').next().and_then(|n| n.parse().ok())), + _ => (word, None), + } +} + +#[cfg(test)] +mod tests { + use super::path_at; + + /// The path under the `^` in `marker`. + fn at(row: &str, marker: &str) -> Option<(String, Option)> { + path_at(row, marker.find('^').unwrap()).map(|(path, line, _)| (path, line)) + } + + #[test] + fn finds_the_path_and_line_under_the_pointer() { + let row = "● Fixed it in src/app/mod.rs:42, see the test."; + assert_eq!(at(row, " ^"), Some(("src/app/mod.rs".into(), Some(42)))); + assert_eq!(at(row, " ^"), Some(("src/app/mod.rs".into(), Some(42))), "the start of the word"); + assert_eq!(at("Update(README.md)", " ^"), Some(("README.md".into(), None))); + assert_eq!(at(" at lib.rs:12:5", " ^"), Some(("lib.rs".into(), Some(12))), "the column is dropped"); + assert_eq!(at("is (src/lib/app-platforms.ts:2-10) here", " ^"), Some(("src/lib/app-platforms.ts".into(), Some(2))), "a range of lines"); + assert_eq!(at("explain @src/a.rs#L12-30: why", " ^"), Some(("src/a.rs".into(), Some(12)))); + assert_eq!(at(r"open C:\work\a.rs.", " ^"), Some((r"C:\work\a.rs".into(), None)), "a drive, and a full stop after"); + } + + #[test] + fn says_which_columns_the_path_covers() { + let row = "see @src/a.rs:42, ok"; + assert_eq!(path_at(row, 8).map(|(_, _, columns)| columns), Some(5..16), "without the @ and the comma"); + } + + #[test] + fn leaves_words_and_urls_alone() { + assert_eq!(at("Done. All good", " ^"), None, "a word"); + assert_eq!(at("see https://example.com/a.rs", " ^"), None); + assert_eq!(at("two spaces", " ^"), None, "between words"); + assert_eq!(at("short", " ^"), None, "past the end"); + } +} diff --git a/src/terminal/view/typing.rs b/src/terminal/view/typing.rs index 70327e6..4eecd76 100644 --- a/src/terminal/view/typing.rs +++ b/src/terminal/view/typing.rs @@ -6,10 +6,70 @@ impl TerminalView { pub(super) fn send(&mut self, bytes: Vec, cx: &mut Context) { // Claude Code is not listening yet: keys edit the draft instead (`draft_key`). if !self.held() { + self.mark_typed(); self.write_input(bytes, cx); } } + fn mark_typed(&mut self) { + if let Some(r) = &mut self.reference { + r.typed = true; + } + } + + /// Paste `text` into Claude's input as `text: `, so the user types their comment after it (`reference_line`). Not while + /// Claude Code is starting, or while an earlier one is still there. Only into Claude's own input box: on a menu (a + /// permission question, the folder trust check) the line break could pick an answer, and without bracketed paste it + /// would send the message. Returns whether it was inserted. + pub fn insert_reference(&mut self, text: &str, cx: &mut Context) -> bool { + if self.held() || self.reference.is_some() || !self.mode().contains(TermMode::BRACKETED_PASTE) { + return false; + } + let Some(column) = self.prompt_column() else { return false }; + let line = reference_line(text, column); + let bytes = self.paste_bytes(&line); + self.write_input(bytes, cx); + self.reference = Some(Inserted { chars: line.chars().count(), typed: false }); + true + } + + /// The cursor's column when it is in Claude Code's input box: the `❯` line under a full-width rule, with another + /// rule below. + fn prompt_column(&self) -> Option { + let (rows, line, column) = self.screen_rows(); + cursor_in_prompt(&rows, line).then_some(column) + } + + /// Whether Claude Code's input box holds `text`, such as a reference the user kept on an earlier visit and hasn't + /// sent yet. + pub fn input_holds(&self, text: &str) -> bool { + let (rows, line, _) = self.screen_rows(); + let squeezed = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::(); + // Spaces aside, since a long input wraps onto more rows. + prompt_text(&rows, line).is_some_and(|input| squeezed(&input).contains(&squeezed(text))) + } + + /// The screen's rows as text, and the cursor's line and column. + fn screen_rows(&self) -> (Vec, usize, usize) { + let term = self.terminal.term.lock(); + let grid = term.grid(); + let rows: Vec = (0..grid.screen_lines() as i32) + .map(|l| { + let row = &grid[Line(l)]; + (0..grid.columns()).map(|c| row[Column(c)].c).collect() + }) + .collect(); + let cursor = grid.cursor.point; + (rows, cursor.line.0.max(0) as usize, cursor.column.0) + } + + /// Erase the inserted line again unless the user typed after it. + pub fn withdraw_reference(&mut self, cx: &mut Context) { + if let Some(r) = self.reference.take().filter(|r| !r.typed) { + self.write_input(vec![0x7f; r.chars], cx); + } + } + pub(super) fn write_input(&mut self, bytes: Vec, cx: &mut Context) { let mut term = self.terminal.term.lock(); term.selection = None; @@ -228,6 +288,7 @@ impl TerminalView { #[cfg(target_os = "windows")] let _ = format; let key: &[u8] = if cfg!(target_os = "windows") { b"\x1bv" } else { b"\x16" }; + self.mark_typed(); self.write_input(key.to_vec(), cx); true } @@ -293,3 +354,111 @@ impl EntityInputHandler for TerminalView { None } } + +/// Where Claude Code's input text starts on each of its lines: after `❯ `, and indented as far below it. +const INPUT_COLUMN: usize = 2; + +/// The reference as pasted with the cursor at `column` of Claude's input: `@path#L12: `, so the user's comment follows +/// on the same line, and a space before it when the cursor follows text. No line breaks: the user starts a new line +/// for the next comment themselves. +fn reference_line(text: &str, column: usize) -> String { + if column > INPUT_COLUMN { format!(" {text}: ") } else { format!("{text}: ") } +} + +/// A full-width rule, possibly with a label in it: Claude Code names the input box's top border after a named +/// (for instance resumed) session, as in `────── name ──`. +fn is_rule(row: &str) -> bool { + let row = row.trim_end(); + let dashes = row.chars().filter(|&c| c == '─').count(); + row.starts_with("──") && dashes * 2 >= row.chars().count() +} + +/// The rows of Claude Code's input box, joined, when the cursor on `cursor` is inside it. +fn prompt_text(rows: &[String], cursor: usize) -> Option { + if !cursor_in_prompt(rows, cursor) { + return None; + } + let top = rows[..=cursor].iter().rposition(|r| is_rule(r))?; + let bottom = cursor + 1 + rows[cursor + 1..].iter().position(|r| is_rule(r))?; + Some(rows[top + 1..bottom].iter().map(|r| r.trim_end()).collect()) +} + +/// `rows` of the screen, with the cursor on `cursor`: is it inside Claude Code's input box (see `at_prompt`)? +fn cursor_in_prompt(rows: &[String], cursor: usize) -> bool { + let Some(top) = rows.get(..=cursor).and_then(|above| above.iter().rposition(|r| is_rule(r))) else { return false }; + let below = rows.get(cursor + 1..).is_some_and(|below| below.iter().any(|r| is_rule(r))); + // A numbered menu right under a rule also starts with the pointer: `❯ 1. Yes`. + let numbered = |line: &str| line.trim_start().split_once(". ").is_some_and(|(n, _)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())); + below && top < cursor && rows[top + 1].strip_prefix('❯').is_some_and(|line| !numbered(line)) +} + +#[cfg(test)] +mod tests { + use super::{cursor_in_prompt, prompt_text, reference_line}; + + #[test] + fn a_reference_labels_the_users_comment_on_the_same_line() { + assert_eq!(reference_line("@a.rs#L1", 2), "@a.rs#L1: ", "an empty input, or the start of a line in it"); + assert_eq!(reference_line("@a.rs#L1", 9), " @a.rs#L1: ", "after the user's text, with no line break"); + } + + fn screen(text: &str) -> Vec { + text.lines().map(String::from).collect() + } + + #[test] + fn the_input_box_text_is_its_rows_between_the_rules() { + let rows = screen("● Done. +──────── +❯ explain @a.rs#L1- + 2: why +──────── + ? for shortcuts"); + assert_eq!(prompt_text(&rows, 3).as_deref(), Some("❯ explain @a.rs#L1- 2: why")); + assert_eq!(prompt_text(&rows, 0), None, "the cursor is outside the box"); + } + + #[test] + fn only_claude_codes_input_box_counts_as_its_prompt() { + let prompt = screen("Claude Code + +────────── +❯ fix the bug + and this +────────── + ⏵⏵ auto mode on"); + assert!(cursor_in_prompt(&prompt, 3)); + assert!(cursor_in_prompt(&prompt, 4), "on the input's second line"); + assert!(!cursor_in_prompt(&prompt, 0), "above the box"); + assert!(!cursor_in_prompt(&prompt, 6), "below the box"); + let trust = screen("────────── + Do you trust the files in this folder? + + ❯ No, exit + Yes, I trust this folder + + Enter to confirm"); + assert!(!cursor_in_prompt(&trust, 3), "a menu"); + let question = screen("────────── +Do you want to proceed? +❯ 1. Yes + 2. No +──────────"); + assert!(!cursor_in_prompt(&question, 2), "a numbered question"); + let menu = screen("────────── +❯ 1. Yes + 2. No +──────────"); + assert!(!cursor_in_prompt(&menu, 1), "a numbered menu right under a rule"); + } + + #[test] + fn a_named_session_labels_the_top_rule_of_its_input_box() { + let named = screen("● Done. +────────────────────────── fix the freeze ── +❯ +────────────────────────────────────────── + ? for shortcuts"); + assert!(cursor_in_prompt(&named, 2)); + } +} diff --git a/src/visual/ui/mod.rs b/src/visual/ui/mod.rs index 7ed73ae..124d3d4 100644 --- a/src/visual/ui/mod.rs +++ b/src/visual/ui/mod.rs @@ -13,7 +13,7 @@ const NODE: &str = "claudiu-ui"; /// The description of the `show_visual` tool. Keep it in step with `parse::default_css` and the properties /// `Css::set` understands. -pub const PROMPT: &str = r#"Draws Markdown in Claudiu's Visual panel, beside the terminal. Use it when something is easier to see than to read: a dashboard, a comparison, a layout, a timeline, a diagram, a chart, a status board, a mock-up, or a structured walkthrough. The panel fills while you write the call, so put the most important part first. Each call adds a new card to the panel. The user sees the drawing and not the markup, so keep your normal reply short and say the key facts there without repeating the content. +pub const PROMPT: &str = r#"Draws Markdown in Claudiu's Visual panel, beside the terminal. Use it unasked instead of typing a table, comparison, flow, architecture, before/after, status board, timeline, chart or mock-up into the terminal. The panel fills while you write the call, so put the most important part first. Each call adds a new card to the panel. The user sees the drawing and not the markup, so keep your normal reply short and say the key facts there without repeating the content. `content` is ordinary Markdown (headings, lists, tables, code, links, emphasis). Where a drawing helps, put it in a fenced block with the info string `ui`; Markdown and `ui` blocks mix freely, with prose before and after and several blocks per call. The block holds HTML with inline CSS, and Claudiu draws it in the app's own dark style. The result is static (no clicking, no scripts).