diff --git a/Cargo.toml b/Cargo.toml index 37b5b73..752d022 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -87,7 +87,8 @@ opt-level = 2 # `TriggerCompletion` (Ctrl+Space) and has a menu opened that way follow its word as it grows # (`handle_completion_trigger` in src/input/editor/lsp/completions.rs). It also makes `has_multiple_cursors`, `select_range` # and `replace_range` public, which the line actions (src/app/line_actions.rs) edit through, and makes a drag that began -# with a double click select whole words (`snap_to_word_edge` in src/input/base/selection.rs). +# with a double click select whole words (`snap_to_word_edge` in src/input/base/selection.rs). `SelectableText::runs` lets +# a card's text keep its styling while selectable. [patch.crates-io] gpui-base = { path = "vendor/gpui-base" } diff --git a/README.md b/README.md index 5141136..3d9273e 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Claudiu is a native desktop app, written in Rust with [GPUI](https://gpui.rs), t Each session is your own `claude` process in a real pseudo-terminal, so Claude Code's keys, mouse and paste work unchanged. Claudiu has no API keys and never calls the Anthropic API. Sign-in stays with Claude Code. The first launch opens a setup window that checks for `claude` (required) and `gh` (optional), links to their install pages and installs nothing. Settings has a Check setup button to open it again. A sidebar lists your projects and sessions. Ended sessions resume through `claude --resume`, and sessions that were running come back at the next start. -Around the terminal, Claudiu adds an editor mode (Ctrl+Shift+E) with files, tabs, search, Git change marks and language-server diagnostics, definitions and completion. It also adds usage and context meters, a GitHub pane for issues and pull requests through your `gh` login, defaults for the model, effort and permission mode of new sessions, and extra Claude accounts that share one configuration. A session can move between git worktrees the way it switches branches, so several agents work on separate branches at once: the worktree button in the top bar switches the shown session into another worktree, or into a new one that Claudiu makes on a branch you name, and its conversation continues there. Its hover x removes a worktree, the branch button's x deletes a local branch after telling you which commits would be lost, and ending the last session in a worktree offers to remove it. Claudiu keeps the worktrees it makes in its own data folder, outside your repositories, so they never show up in `git status`; Settings has a Worktrees page that lists them to show in the file manager or remove. Settings lists the rest. +Around the terminal, Claudiu adds an editor mode (Ctrl+Shift+E) with files, tabs, search, Git change marks and language-server diagnostics, definitions and completion. It also adds usage and context meters, a GitHub pane for issues and pull requests through your `gh` login, defaults for the model, effort and permission mode of new sessions, and extra Claude accounts that share one configuration. When a reply needs a table, chart or diagram, Claude draws it as a card inside the terminal, under the tool call, and the card scrolls with the transcript. Cards can hold buttons that send a message for you, collapsible sections, tabs and charts, and they come back when you reopen a session. A session can move between git worktrees the way it switches branches, so several agents work on separate branches at once: the worktree button in the top bar switches the shown session into another worktree, or into a new one that Claudiu makes on a branch you name, and its conversation continues there. Its hover x removes a worktree, the branch button's x deletes a local branch after telling you which commits would be lost, and ending the last session in a worktree offers to remove it. Claudiu keeps the worktrees it makes in its own data folder, outside your repositories, so they never show up in `git status`; Settings has a Worktrees page that lists them to show in the file manager or remove. Settings lists the rest. Ctrl+Shift (Cmd+Shift on macOS) plus a letter drives the app. Everything else reaches Claude Code. Editor mode finds `rust-analyzer`, `tsc --lsp` and `gleam` on your PATH and installs nothing. diff --git a/mod/hooks/register.js b/mod/hooks/register.js index d1179fe..e39184e 100644 --- a/mod/hooks/register.js +++ b/mod/hooks/register.js @@ -13,8 +13,9 @@ // 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. +// - Cards: answers `show_visual` in-process and, while the model is still writing the call, streams its Markdown to +// `CLAUDIU_VISUAL_PREFIX.json`. Under each call it reserves rows, each with a link naming the call, and Claudiu +// paints the live card over them. Claudiu's measured height comes back in `CLAUDIU_VISUAL_PREFIX.rows`. // - One-shot completions: runs requests from `CLAUDIU_ASK_FILE` (commit messages, session titles) with // `$.model.complete`, on this session's own client, so Claudiu needs no `claude -p`. @@ -27,6 +28,7 @@ const MODELS = { opus: 'claude-opus-5-5', fable: 'claude-fable-5-1', } +const CARD_ROWS = 6 // reserved for a card until Claudiu has measured it 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'] @@ -46,6 +48,9 @@ let pendingAdvisor = null // an advisor change Claude Code refused (see setAdvis 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 +const cardRows = new Map() // show_visual call id -> rows reserved for its card +const published = new Set() // call ids whose card file this process wrote from the transcript +let rowsPoll // watches the heights Claudiu measures let visualChain = Promise.resolve() // visual writes in order, without holding up the stream let lastVisual = null // id of the show_visual call being written, or last written @@ -272,16 +277,10 @@ function partialString(json, key) { return out } -// Queues a write of the Visual panel's file. Writes run one after another, and a failed one is dropped. -function writeVisual($, file, call, title, content, done) { - const body = JSON.stringify({ - call, - title: String(title ?? '').slice(0, 80), - content: String(content ?? '').slice(0, 200_000), - done, - at: Date.now(), - }) - visualChain = visualChain.then(() => $.fs.write(file, body)).catch(() => {}) +// Queues a write of a card's file. Writes run one after another, and a failed one is dropped. +function writeVisual($, prefix, call, content) { + const body = JSON.stringify({ call, content: String(content ?? '').slice(0, 200_000) }) + visualChain = visualChain.then(() => $.fs.write(`${prefix}${call}.json`, body)).catch(() => {}) } // ---- One-shot completions ----------------------------------------------------------------------------------------- @@ -439,27 +438,27 @@ async function onSetModel($, e) { } } -// The model's show_visual call streams to the Visual panel while it is written. The call's arguments arrive as pieces -// of JSON; the Markdown read out of them so far goes to the file a few times a second at most. The tool.call hook -// writes the finished card. +// The model's show_visual call streams to its card while it is written. The call's arguments arrive as pieces of JSON; +// the Markdown read out of them so far goes to the file a few times a second at most. The tool.call hook writes the +// finished card. async function onShowVisual($, e) { - const file = await $.env.get('CLAUDIU_VISUAL_FILE') - if (!file) { - return { result: "The Visual panel isn't available in this session (Claudiu's mod has no file for it).", isError: true } + const prefix = await $.env.get('CLAUDIU_VISUAL_PREFIX') + if (!prefix) { + return { result: "Visuals aren't available in this session (Claudiu's mod has no file for them).", isError: true } } if (typeof e.content !== 'string' || !e.content.trim()) return { result: 'content must be non-empty Markdown.', isError: true } - writeVisual($, file, e.tool_use_id ?? lastVisual ?? 'v' + Date.now(), e.title, e.content, true) - return { result: "Shown in Claudiu's Visual panel. Say the key facts in a short reply; don't repeat the content." } + writeVisual($, prefix, e.tool_use_id ?? lastVisual ?? 'v' + Date.now(), e.content) + return { result: "Shown inline in the terminal. Say the key facts in a short reply; don't repeat the content." } } -// Applies the saved model and effort to this turn's steps, and streams a show_visual call to the Visual panel while -// the model writes it. Sub-agent steps are left alone. +// Applies the saved model and effort to this turn's steps, and streams a show_visual call to its card while the model +// writes it. Sub-agent steps are left alone. async function* onTurnStep($, e, next) { const step = !e.agentId && (want.model || want.effort) ? { ...e, model: want.model ?? e.model, effort: want.effort ?? e.effort } : e - const file = e.agentId ? null : await $.env.get('CLAUDIU_VISUAL_FILE') - if (!file) return yield* next(step) + const prefix = e.agentId ? null : await $.env.get('CLAUDIU_VISUAL_PREFIX') + if (!prefix) return yield* next(step) const open = new Map() // block index -> the show_visual call being written there for await (const c of next(step)) { @@ -471,13 +470,52 @@ async function* onTurnStep($, e, next) { v.json += c.json if (Date.now() - v.at >= 150) { v.at = Date.now() - writeVisual($, file, v.id, partialString(v.json, 'title'), partialString(v.json, 'content'), false) + writeVisual($, prefix, v.id, partialString(v.json, 'content')) } } yield c } } +// Draws a show_visual call as its title and the rows its card covers. Each row's link names the call and the row, which +// is how Claudiu finds them on screen, and the rows scroll and clip with the transcript. Drawing a call from an earlier +// process writes its card again from the transcript: that is what brings cards back after a restart. +async function onVisualRow($, e, next) { + if (e.props.tool !== VISUAL_TOOL || e.props.isErrored) return next(e) + const { Box, Link, Text } = $.ui.resolve(e) + const id = e.props.tool_use_id + if (!cardRows.has(id)) cardRows.set(id, CARD_ROWS) + if (!e.props.isRunning && !published.has(id) && e.props.input?.content) { + published.add(id) + const prefix = await $.env.get('CLAUDIU_VISUAL_PREFIX') + if (prefix) writeVisual($, prefix, id, e.props.input.content) + } + const links = Array.from({ length: cardRows.get(id) }, (_, i) => + h(Link, { key: String(i), href: `claudiu://visual/${id}/${i}` }, ' '.repeat(16))) + return h(Box, { flexDirection: 'column' }, h(Text, { dimColor: true }, String(e.props.input?.title ?? 'Visual')), ...links) +} + +// Claude Code folds MCP calls into one count line, which would hide a card's rows. +function onVisualGroup($, e, next) { + if (!e.props.calls.some(c => c.tool === VISUAL_TOOL)) return next(e) + return next({ ...e, props: { ...e.props, isExpanded: true } }) +} + +// Reserves the rows Claudiu measured for each card drawn in this process. +async function readCardRows($) { + const prefix = await $.env.get('CLAUDIU_VISUAL_PREFIX') + if (!prefix) return + let changed = false + for (const [id, rows] of [...cardRows]) { + const measured = parseInt(await $.fs.read(`${prefix}${id}.rows`).catch(() => ''), 10) + if (measured > 0 && measured !== rows) { + cardRows.set(id, measured) + changed = true + } + } + if (changed) $.ui.invalidate('ui.render') +} + async function onSessionStart($, e, next) { const r = await next(e) await report($) @@ -487,6 +525,8 @@ async function onSessionStart($, e, next) { ctlPoll = $.clock.every(1000, () => applyCtl($)) askPoll?.cancel() askPoll = $.clock.every(500, () => answerAsk($)) + rowsPoll?.cancel() + rowsPoll = $.clock.every(200, () => readCardRows($)) await watchSessionName($) return r } @@ -498,6 +538,8 @@ export function register(on) { on('session.compact', onSessionCompact) on('tool.call', { tool: 'mcp__claudiu__set_model' }, onSetModel) on('tool.call', { tool: VISUAL_TOOL }, onShowVisual) + on('ui.render', { component: 'ToolUse' }, onVisualRow) + on('ui.render', { component: 'ToolGroup' }, onVisualGroup) on('turn.step', onTurnStep) on('session.start', onSessionStart) } diff --git a/mod/hooks/visual.test.ts b/mod/hooks/visual.test.ts index 1b33bdd..404d77d 100644 --- a/mod/hooks/visual.test.ts +++ b/mod/hooks/visual.test.ts @@ -4,7 +4,7 @@ const TOOL = 'mcp__claudiu__show_visual' const STEP = { turnId: 't', index: 0, answer: '', toolUses: [], stopReason: 'tool_use' as const, usage: null } test('streams the Markdown of a show_visual call while it is written, then writes the finished card', async ($, on) => { - mock.env(on, { CLAUDIU_VISUAL_FILE: 'visual/s.json' }) + mock.env(on, { CLAUDIU_VISUAL_PREFIX: 'visual/s--' }) const writes: { path: string; card: any }[] = [] on('fs.write', (_$, e) => { writes.push({ path: e.path, card: JSON.parse(e.text) }) @@ -24,26 +24,23 @@ test('streams the Markdown of a show_visual call while it is written, then write expect(writes.length).toBeGreaterThanOrEqual(1) const first = writes[0]! - expect(first.path.replace(/\\/g, '/').endsWith('visual/s.json')).toBe(true) // Windows paths use backslashes + expect(first.path.replace(/\\/g, '/').endsWith('visual/s--toolu_1.json')).toBe(true) // Windows paths use backslashes expect(first.card.call).toBe('toolu_1') - expect(first.card.done).toBe(false) - expect(first.card.title).toBe('Pla') const result = await $.tool.call({ tool: TOOL, tool_use_id: 'toolu_1', title: 'Plan', content: '# Hi\n\nsome **bold** é' }) expect(result.isError).toBeFalsy() - const last = writes.at(-1)!.card - expect(last).toMatchObject({ call: 'toolu_1', title: 'Plan', content: '# Hi\n\nsome **bold** é', done: true }) + expect(writes.at(-1)!.card).toEqual({ call: 'toolu_1', content: '# Hi\n\nsome **bold** é' }) }) test('refuses an empty card and says so when Claudiu gave no file', async ($, on) => { - mock.env(on, { CLAUDIU_VISUAL_FILE: 'visual/s.json' }) + mock.env(on, { CLAUDIU_VISUAL_PREFIX: 'visual/s--' }) on('fs.write', () => ({ value: undefined })) const empty = await $.tool.call({ tool: TOOL, tool_use_id: 'x', content: ' ' }) expect(empty.isError).toBe(true) }) test('other tools and subagents are not streamed', async ($, on) => { - mock.env(on, { CLAUDIU_VISUAL_FILE: 'visual/s.json' }) + mock.env(on, { CLAUDIU_VISUAL_PREFIX: 'visual/s--' }) let writes = 0 on('fs.write', () => { writes += 1 @@ -58,3 +55,23 @@ test('other tools and subagents are not streamed', async ($, on) => { for await (const _ of $.turn.step({ turnId: 't', index: 0, model: 'm', messageCount: 1, agentId: 'sub' })) void _ expect(writes).toBe(0) }) + +const ROW = { tool: TOOL, tool_use_id: 'toolu_9', input: { title: 'Plan', content: '# Old card' }, isRunning: false, isErrored: false, isInterrupted: false } +const MOUNT = { plugin: 'Claudiu', surface: 'terminal' as const, component: 'ToolUse' as const, requestId: 'toolu_9', props: ROW } + +test('a drawn call reserves linked rows and writes its card back from the transcript', async ($, on) => { + mock.env(on, { CLAUDIU_VISUAL_PREFIX: 'visual/s--' }) + const writes: { path: string; text: string }[] = [] + on('fs.write', (_$, e) => { + writes.push({ path: e.path, text: e.text }) + return { value: undefined } + }) + const ui = await $.ui.mount(MOUNT) + const link = await ui.find({ type: 'Link' }) + expect(link?.props?.href).toBe('claudiu://visual/toolu_9/0') + expect((await ui.find({ type: 'Text', text: /Plan/ }))?.text).toBe('Plan') + await ui.unmount() + await new Promise(done => setTimeout(done, 10)) + const card = writes.find(w => w.path.includes('toolu_9')) + expect(JSON.parse(card!.text)).toEqual({ call: 'toolu_9', content: '# Old card' }) +}) diff --git a/src/app/headless.rs b/src/app/headless.rs index 2d10124..7b244a1 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -344,23 +344,15 @@ fn sessions_and_shell() { assert_eq!(ws.left_width(700.0), SIDEBAR_MIN, "keeps room for the session in a small window"); ws.left_drag = None; }); - // The Visual panel: the first card a session's model draws opens it (wide, sharing GitHub's width), the same call - // keeps filling its card without reopening it, and a card for a session that is not shown only lists it. + // A card reaches the terminal of its session, and a card for a session that is not running is dropped. let shown = ws.read_with(&cx, |ws, _| ws.active.clone().unwrap()); let stem = datadir::safe_file_stem(&shown); - let card = |content: &str, done: bool| crate::visual::Card { call: "c1".into(), title: "Plan".into(), content: content.into(), done }; - assert!(ws.read_with(&cx, |ws, _| !ws.visual_shown())); - step(&mut cx, &|ws, _w, cx| ws.apply_visuals(vec![(stem.clone(), card("# Hi", false))], cx)); - assert!(ws.read_with(&cx, |ws, _| ws.visual_shown() && ws.right_gh.is_none()), "a new card opens the panel"); - assert_eq!(ws.read_with(&cx, |ws, _| ws.right_width(1600.0)), RIGHT_GH_W); - step(&mut cx, &|ws, _w, cx| ws.hide_visual(false, cx)); - step(&mut cx, &|ws, _w, cx| ws.apply_visuals(vec![(stem.clone(), card("# Hi there", true))], cx)); - assert!(ws.read_with(&cx, |ws, _| !ws.visual_shown() && ws.visual_cards().len() == 1 && ws.visual_cards()[0].done), "the same call updates its card and leaves the panel shut"); - assert_eq!(ws.read_with(&cx, |ws, _| ws.right_width(1600.0)), RIGHT_MENU_W + 40.0); - step(&mut cx, &|ws, _w, cx| ws.show_visual(cx)); - assert!(ws.read_with(&cx, |ws, _| ws.visual_shown())); - step(&mut cx, &|ws, _w, cx| ws.hide_visual(true, cx)); - assert!(ws.read_with(&cx, |ws, _| ws.visual_cards().is_empty() && !ws.visual_shown()), "clearing forgets the cards"); + let card = |call: &str| crate::visual::Card { call: call.into(), content: "# Hi".into() }; + step(&mut cx, &|ws, _w, cx| ws.apply_visuals(vec![(stem.clone(), card("c1")), ("no-such-session".into(), card("c2"))], cx)); + assert!(ws.read_with(&cx, |ws, cx| { + let view = ws.live_view(&shown).unwrap().read(cx); + view.has_card("c1") && !view.has_card("c2") + })); step(&mut cx, &|ws, w, cx| ws.open_github(cwd.clone(), w, cx)); assert!(ws.read_with(&cx, |ws, _| ws.gh.len() == 1 && ws.right_gh.is_some()), "github shown in the right sidebar"); assert_eq!(ws.read_with(&cx, |ws, _| ws.right_width(1600.0)), RIGHT_GH_W, "GitHub keeps its own width"); diff --git a/src/app/layout.rs b/src/app/layout.rs index 148a125..6dc0db4 100644 --- a/src/app/layout.rs +++ b/src/app/layout.rs @@ -103,9 +103,9 @@ impl Workspace { cx.notify(); } - /// GitHub and the Visual panel are read and written in, so they share one wider, resizable width. + /// GitHub is read and written in, so it gets a wider, resizable width. fn right_wide(&self) -> bool { - self.right_gh.is_some() || self.visual_shown() + self.right_gh.is_some() } /// The right sidebar's current width: the remembered one for the menu or for GitHub, kept within bounds. diff --git a/src/app/mod.rs b/src/app/mod.rs index 99310e7..457e529 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -409,17 +409,12 @@ pub struct Workspace { pub gh: Vec, /// The GitHub view the right sidebar shows; `None` is its menu. pub right_gh: Option, - /// The right sidebar shows the Visual panel (when the shown session has cards and GitHub is not open). - pub right_visual: bool, - /// What each session's model drew in the Visual panel, oldest card first. - pub visuals: HashMap>, - pub visual_scroll: crate::panels::glide::Smooth, pub right_drag: Option, /// Right-sidebar rows whose × was clicked and that are shrinking away before their entry is removed. pub leaving: std::collections::HashSet, pub left_reveal: crate::panels::widgets::Reveal, pub right_reveal: crate::panels::widgets::Reveal, - /// The right sidebar's animated width, and the view it currently shows ("menu", "visual" or "gh:"): + /// The right sidebar's animated width, and the view it currently shows ("menu" or "gh:"): /// a change of view fades the old one out, slides the width, then fades the new one in. pub right_w: crate::panels::widgets::Reveal, pub right_view: String, @@ -545,9 +540,6 @@ impl Workspace { live: vec![], gh: vec![], right_gh: None, - right_visual: false, - visuals: HashMap::new(), - visual_scroll: Default::default(), right_drag: None, leaving: Default::default(), left_reveal: crate::panels::widgets::Reveal::new(store.data.layout.sidebar_visible), diff --git a/src/app/sessions.rs b/src/app/sessions.rs index b31040f..4c6c31c 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -38,13 +38,14 @@ impl Workspace { spec.env.push(("CLAUDIU_NAME_FILE".into(), mcp::name_file(claude_session_id).to_string_lossy().into_owned())); spec.env.push((usage::USAGE_DIR_ENV.into(), usage::snapshot_dir().to_string_lossy().into_owned())); spec.env.push((usage::CTL_ENV.into(), usage::ctl_file(record_id).to_string_lossy().into_owned())); - spec.env.push((crate::visual::VISUAL_ENV.into(), crate::visual::file(record_id).to_string_lossy().into_owned())); + spec.env.push((crate::visual::VISUAL_ENV.into(), crate::visual::prefix(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 chrome { spec.args.push("--chrome".into()); } spec.env.push(("CLAUDE_CODE_NO_FLICKER".into(), "1".into())); // fullscreen renderer, per process + spec.env.push(("FORCE_HYPERLINK".into(), "1".into())); // Claude Code would print links as text otherwise; cards are found by theirs spec.env.push(("CLAUDE_CODE_AUTO_CONNECT_IDE".into(), "false".into())); spec.env.push(("CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL".into(), "1".into())); self.sync_configs_now(cx); @@ -259,6 +260,7 @@ impl Workspace { 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), + TerminalEvent::SendText(text) => ws.send_to_claude(&sub_id, text, window, cx), }, ); let claude_name = spec.args.iter().position(|a| a == "--name").and_then(|i| spec.args.get(i + 1)).cloned(); @@ -405,7 +407,6 @@ impl Workspace { 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. if was_active { diff --git a/src/app/visuals.rs b/src/app/visuals.rs index 8f35062..1c05423 100644 --- a/src/app/visuals.rs +++ b/src/app/visuals.rs @@ -1,11 +1,11 @@ -//! The Visual panel's state: the cards each session's model drew (`visual/`), polled from the files its mod writes. +//! Hands the cards each session's model drew (`visual/`), polled from the files its mod writes, to its terminal. use super::*; use crate::visual::{self, Card, Stamp}; impl Workspace { /// Look at the card files a few times a second, off the UI thread. What was there at start-up belongs to an - /// earlier run and is not shown. + /// earlier run: a session that shows those cards again has its mod write them again. pub(super) fn start_visual_poll(&mut self, cx: &mut Context) { cx.spawn(async move |this, cx| { let mut seen: HashMap = HashMap::new(); @@ -28,47 +28,13 @@ impl Workspace { .detach(); } - /// Add the cards that arrived. A new one for the shown session opens the panel (the keyboard stays where it is). + /// Give each card that arrived to its session's terminal. `changes` holds the file stem of the session. pub(super) fn apply_visuals(&mut self, changes: Vec<(String, Card)>, cx: &mut Context) { - let mut open = false; for (stem, card) in changes { - let Some(id) = self.store.data.sessions.iter().find(|s| datadir::safe_file_stem(&s.id) == stem).map(|s| s.id.clone()) else { continue }; - let new = visual::upsert(self.visuals.entry(id.clone()).or_default(), card); - open |= new && self.active_id() == Some(&id); + let Some(session) = self.store.data.sessions.iter().find(|s| datadir::safe_file_stem(&s.id) == stem) else { continue }; + let Some(view) = self.live_view(&session.id) else { continue }; + let rows_file = visual::rows_file(&stem, &card.call); + view.update(cx, |view, cx| view.set_card(card, rows_file, cx)); } - if open { - self.right_visual = true; - self.right_gh = None; - self.store.data.layout.right_hidden = false; - self.store.mark_dirty(); - } - cx.notify(); - } - - /// The shown session's cards, oldest first. - pub fn visual_cards(&self) -> &[Card] { - self.active_id().and_then(|id| self.visuals.get(id)).map_or(&[], Vec::as_slice) - } - - /// Whether the right sidebar is showing the Visual panel now. - pub fn visual_shown(&self) -> bool { - self.right_gh.is_none() && self.right_visual && !self.visual_cards().is_empty() - } - - pub fn show_visual(&mut self, cx: &mut Context) { - self.right_visual = true; - self.right_gh = None; - self.store.data.layout.right_hidden = false; - self.store.mark_dirty(); - cx.notify(); - } - - /// Back to the menu (`clear` also forgets the shown session's cards). - pub fn hide_visual(&mut self, clear: bool, cx: &mut Context) { - self.right_visual = false; - if clear && let Some(id) = self.active_id().cloned() { - self.visuals.remove(&id); - } - cx.notify(); } } diff --git a/src/claude/mcp.rs b/src/claude/mcp.rs index 0503c99..56eb011 100644 --- a/src/claude/mcp.rs +++ b/src/claude/mcp.rs @@ -41,7 +41,7 @@ impl Feature { pub fn label(self) -> &'static str { match self { - Self::Visual => "Visual panel", + Self::Visual => "Inline cards", Self::Github => "GitHub sidebar", Self::Sessions => "Other sessions", Self::Model => "Model switch", @@ -110,9 +110,9 @@ Claude Code session (the user says so, or you recognise it), find it with search 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 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 VISUAL_INSTRUCTIONS: &str = " Visual: show_visual draws a card inside this terminal, under the call. Most replies need \ +none. When a reply does need a visual (a table, comparison, flow, architecture, before/after, status board or chart), prefer \ +show_visual over drawing it in text, unasked (private, no approval), and reply in a few lines."; const ARTIFACT_INSTRUCTIONS: &str = " Artifacts are for pages to share."; @@ -235,7 +235,7 @@ fn serve(input: impl BufRead, mut out: impl Write, session: &str, record: &str, Some("link_session") => link_session(&msg["params"], record, &attach_dir(data), "link"), Some("unlink_session") => link_session(&msg["params"], record, &attach_dir(data), "unlink"), Some("set_model") => reply("Model switching isn't available in this session (Claudiu's mod isn't loaded).", true), - Some("show_visual") => reply("The Visual panel isn't available in this session (Claudiu's mod isn't loaded).", true), + Some("show_visual") => reply("Visuals aren't available in this session (Claudiu's mod isn't loaded).", true), Some(tool) if BRIDGE_TOOLS.contains(&tool) => match ask(tool, &msg["params"]["arguments"]) { Ok(text) => reply(&text, false), Err(text) => reply(&text, true), diff --git a/src/panels/inspector.rs b/src/panels/inspector.rs index 9229073..33ea421 100644 --- a/src/panels/inspector.rs +++ b/src/panels/inspector.rs @@ -44,7 +44,6 @@ impl Workspace { // The view the state asks for; the one drawn changes only after the old one has faded out. let desired = match self.right_gh.as_ref().filter(|id| self.gh_pane(id).is_some()) { Some(id) => format!("gh:{id}"), - None if self.visual_shown() => "visual".to_string(), None => "menu".to_string(), }; const OUT_MS: f32 = 100.0; @@ -110,10 +109,9 @@ impl Workspace { .child(div().flex_1().min_h_0().child(view)) .into_any_element() } - None if shown_view == "visual" => self.render_visual_view(window, cx).into_any_element(), None => self.render_right_menu(window, cx).into_any_element(), }; - // A different view (menu, GitHub project, Visual) fades in. + // A different view (menu, GitHub project) fades in. let body = div().flex_none().w(px(target)).h_full().opacity(fade).child(body); // Both views can be resized by their left edge; a small grip sits in the gutter. let handle_center = theme::PANEL_GAP / 2.0 + 3.0; @@ -178,41 +176,6 @@ impl Workspace { ) } - /// What the model drew for the shown session, newest card first; a card still being written says so. - fn render_visual_view(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement + use<> { - let cards: Vec = self.visual_cards().iter().rev().cloned().collect(); - let header = div() - .flex() - .items_center() - .gap(px(6.0)) - .flex_none() - .h(px(32.0)) - .px(px(6.0)) - .border_b_1() - .border_color(hsla(theme::BORDER)) - .child(icon_button("visual-back", IconName::ArrowLeft).on_click(cx.listener(|ws, _: &ClickEvent, _w, cx| ws.hide_visual(false, cx)))) - .child(div().flex_1().text_size(crate::panels::scale::px(12.5)).font_weight(FontWeight::MEDIUM).child(format!("Visual · {}", cards.len()))) - .child(icon_button("visual-clear", IconName::X).on_click(cx.listener(|ws, _: &ClickEvent, _w, cx| ws.hide_visual(true, cx)))); - let mut list = div().flex().flex_col().w_full(); - for (n, card) in cards.iter().enumerate() { - let mut one = div().flex().flex_col().gap(px(8.0)).p(px(14.0)); - if n > 0 { - one = one.border_t_1().border_color(hsla(theme::BORDER)); - } - if !card.title.is_empty() || !card.done { - let mut head = div().flex().items_center().gap(px(8.0)).text_size(crate::panels::scale::px(12.5)); - head = head.child(div().flex_1().min_w_0().font_weight(FontWeight::MEDIUM).child(card.title.clone())); - if !card.done { - head = head.child(div().flex_none().text_color(hsla(theme::TEXT_FAINT)).child("drawing…")); - } - one = one.child(head); - } - one = one.child(div().text_size(crate::panels::scale::px(13.0)).child(crate::visual::ui::markdown(format!("visual-{}", card.call), &card.content))); - list = list.child(crate::panels::widgets::fade_in(one, format!("visual-card-{}", card.call), 220, 0.0)); - } - div().flex().flex_col().size_full().child(header).child(self.visual_scroll.wire(div().id("visual-scroll").flex_1().min_h_0(), window).child(list)) - } - fn render_right_menu(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement + use<> { let shown = self.shown(); let id = self.active_id().cloned(); @@ -224,22 +187,6 @@ impl Workspace { let linked = (!links.is_empty()).then(|| self.linked_rows(id.as_ref(), links, cx)); let away = id.as_deref().and_then(|i| self.session_away(i, cx)); let status = self.status_rows(&shown, id.as_ref(), running, cx); - let drawn = self.visual_cards().len(); - let visual = (drawn > 0).then(|| { - div().flex().flex_col().gap(px(1.0)).child(removable_row( - cx, - self.leaving.contains("visual-open"), - "visual-open".to_string(), - IconName::Eye, - format!("Visual · {drawn}"), - |ws, _window, cx| ws.show_visual(cx), - |ws| { - if let Some(id) = ws.active_id().cloned() { - ws.visuals.remove(&id); - } - }, - )) - }); self.menu_scroll .wire(div().id("right-menu").size_full(), window) .flex() @@ -261,7 +208,6 @@ impl Workspace { group("ACCOUNT", body) })) .child(group("ACTIONS", actions)) - .children(visual.map(|v| group("VISUAL", v))) .children(github.map(|g| group("GITHUB", g))) .children(linked.map(|l| group("LINKED", l))) .child(group("STATUS", status)) diff --git a/src/terminal/view/cards.rs b/src/terminal/view/cards.rs new file mode 100644 index 0000000..0893a80 --- /dev/null +++ b/src/terminal/view/cards.rs @@ -0,0 +1,211 @@ +//! The model's cards, painted live over rows Claude Code reserves in its transcript. +//! +//! The mod draws one row of a hidden link per card row, `claudiu://visual//`. Claude Code owns +//! those rows, so they scroll and clip with the transcript; each frame this finds the ones on screen and paints that +//! part of the card over them. The card's measured height goes back to the mod, which reserves that many rows. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use super::*; +use crate::visual::Card; +use crate::visual::ui::{CardUi, Scope, SendText}; + +/// What the links on reserved rows start with. +pub(super) const INLINE_LINK: &str = "claudiu://visual/"; + +/// The mod's links cover this many columns. Past them, only Claude Code's own overlays draw on a reserved row. +const LINK_COLS: usize = 16; +/// Columns between the terminal's edge and a card, where the transcript's text starts. +const MARGIN_COLS: f32 = 2.0; +const MAX_WIDTH: f32 = 720.0; + +/// The part of a card on screen: `count` grid rows from `row`, showing the card from its row `first`. +#[derive(Debug, PartialEq)] +struct Slot { + call: String, + row: usize, + first: usize, + count: usize, +} + +struct Shown { + card: Card, + rows_file: PathBuf, + /// The height last told to the mod. + rows: Option, +} + +pub(super) struct Cards { + shown: HashMap, + ui: Entity, + /// The height each card last wanted, read by the write that runs next, so a slow older write cannot leave its + /// height in the file after a newer one. + wanted_rows: Arc>>, + /// Held while a height is written, so writes to the file run one after another. + writing_rows: Arc>, +} + +impl Cards { + /// Button clicks reach the session as `TerminalEvent::SendText`. A click only counts as sent once it could go. + pub(super) fn new(cx: &mut Context) -> Self { + let ui = cx.new(|_| CardUi::default()); + cx.observe(&ui, |_, _, cx| cx.notify()).detach(); + cx.subscribe(&ui, |view, ui, e: &SendText, cx| { + if view.is_running() { + ui.update(cx, |ui, cx| ui.mark_sent(&e.key, cx)); + } + cx.emit(TerminalEvent::SendText(e.text.clone())); + }) + .detach(); + Self { shown: HashMap::new(), ui, wanted_rows: Arc::default(), writing_rows: Arc::default() } + } +} + +/// The call and card row a reserved row's link names. +fn parse_link(uri: &str) -> Option<(&str, usize)> { + let (call, row) = uri.strip_prefix(INLINE_LINK)?.rsplit_once('/')?; + Some((call, row.parse().ok()?)) +} + +/// Joins the reserved rows of the screen, top to bottom, into the part of each card they show. +fn slots(rows: impl Iterator>) -> Vec { + let mut out: Vec = vec![]; + for (y, reserved) in rows.enumerate() { + let Some((call, first)) = reserved else { continue }; + match out.last_mut() { + Some(s) if s.call == call && s.row + s.count == y => s.count += 1, + _ => out.push(Slot { call, row: y, first, count: 1 }), + } + } + out +} + +impl TerminalView { + /// A card arrived from the mod, or changed. Its height goes to `rows_file`. + pub fn set_card(&mut self, card: Card, rows_file: PathBuf, cx: &mut Context) { + let rows = self.cards.shown.get(&card.call).and_then(|s| s.rows); + self.cards.shown.insert(card.call.clone(), Shown { card, rows_file, rows }); + cx.notify(); + } + + #[cfg(test)] + pub fn has_card(&self, call: &str) -> bool { + self.cards.shown.contains_key(call) + } + + fn visible_slots(&self) -> Vec { + let term = self.terminal.term.lock(); + let grid = term.grid(); + let offset = grid.display_offset() as i32; + slots((0..grid.screen_lines()).map(|y| { + let row = &grid[Line(y as i32 - offset)]; + let link = row[Column(0)].hyperlink()?; + let (call, first) = parse_link(link.uri())?; + // Claude Code's "Jump to bottom" is drawn on top of the transcript: that row stays its own. + let covered = (LINK_COLS..grid.columns()).any(|c| !matches!(row[Column(c)].c, ' ' | '\0')); + (!covered).then(|| (call.to_string(), first)) + })) + } + + /// The cards on screen, each clipped to the rows it has there. The mouse stops at them, but the wheel still scrolls + /// the transcript. + pub(super) fn inline_cards(&self, cx: &mut Context) -> Vec { + let Some(m) = self.metrics.filter(|_| !self.cards.shown.is_empty()) else { return vec![] }; + let width = (m.cell_w * self.terminal.size().0.saturating_sub(4) as f32).min(px(MAX_WIDTH)); + let margin = m.cell_w * MARGIN_COLS; + let line_h = f32::from(m.line_h); + let view = cx.entity().downgrade(); + let mut out = vec![]; + for slot in self.visible_slots() { + let Some(Shown { card, .. }) = self.cards.shown.get(&slot.call) else { continue }; + let scope = Scope { call: card.call.clone(), ui: self.cards.ui.clone() }; + let (call, view) = (card.call.clone(), view.clone()); + let clear_view = view.clone(); + let body = div() + .absolute() + .left(margin) + .top(-(m.line_h * slot.first as f32)) + .w(width) + .text_size(crate::panels::scale::px(13.0)) + .on_children_prepainted(move |bounds, _, cx| { + let Some(height) = bounds.first().map(|b| f32::from(b.size.height)) else { return }; + let rows = (height / line_h).ceil() as usize; + view.update(cx, |view, cx| view.note_card_rows(&call, rows, cx)).ok(); + }) + .child(crate::visual::ui::markdown(format!("card-{}", card.call), &card.content, scope)); + out.push( + div() + .absolute() + .left(px(0.)) + .top(m.line_h * slot.row as f32 + m.shift) + .w(width + margin) + .h(m.line_h * slot.count as f32) + .overflow_hidden() + .block_mouse_except_scroll() + .on_mouse_down(MouseButton::Left, move |_, _, cx| { + clear_view.update(cx, |view, cx| view.clear_terminal_selection(cx)).ok(); + }) + .child(body) + .into_any_element(), + ); + } + out + } + + /// A click on a card never reaches the terminal behind it, so its older selection is dropped here: Ctrl+C copies + /// the terminal's selection first, and would otherwise copy that instead of the card text now being selected. + fn clear_terminal_selection(&mut self, cx: &mut Context) { + if self.terminal.term.lock().selection.take().is_some() { + cx.notify(); + } + } + + /// Tell the mod a card's height when it changes. Runs in a frame, so the file is written off the UI thread. + fn note_card_rows(&mut self, call: &str, rows: usize, cx: &mut Context) { + let Some(shown) = self.cards.shown.get_mut(call).filter(|s| s.rows != Some(rows) && rows > 0) else { return }; + shown.rows = Some(rows); + let file = shown.rows_file.clone(); + let call = call.to_string(); + let wanted = self.cards.wanted_rows.clone(); + let writing = self.cards.writing_rows.clone(); + wanted.lock().unwrap_or_else(|e| e.into_inner()).insert(call.clone(), rows); + cx.background_spawn(async move { + let _one_at_a_time = writing.lock().unwrap_or_else(|e| e.into_inner()); + let latest = wanted.lock().unwrap_or_else(|e| e.into_inner()).get(&call).copied(); + if let Some(latest) = latest { + let _ = crate::datadir::write_atomic(&file, &latest.to_string()); + } + }) + .detach(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_link_names_its_call_and_row() { + assert_eq!(parse_link("claudiu://visual/toolu_1/12"), Some(("toolu_1", 12))); + assert_eq!(parse_link("claudiu://visual/toolu_1"), None); + assert_eq!(parse_link("claudiu://visual/toolu_1/x"), None); + assert_eq!(parse_link("https://example.com/1/2"), None); + } + + #[test] + fn rows_join_into_the_visible_part_of_each_card() { + let row = |call: &str, n| Some((call.to_string(), n)); + // Card a is clipped at the top, its row 4 is covered by an overlay, and card b follows without a gap. + let screen = vec![None, row("a", 2), row("a", 3), None, row("a", 5), row("b", 0), row("b", 1)]; + assert_eq!( + slots(screen.into_iter()), + [ + Slot { call: "a".into(), row: 1, first: 2, count: 2 }, + Slot { call: "a".into(), row: 4, first: 5, count: 1 }, + Slot { call: "b".into(), row: 5, first: 0, count: 2 }, + ] + ); + } +} diff --git a/src/terminal/view/element.rs b/src/terminal/view/element.rs index 38e70a3..9655595 100644 --- a/src/terminal/view/element.rs +++ b/src/terminal/view/element.rs @@ -208,8 +208,10 @@ 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() || hovered_link; + let link = cell.hyperlink(); + // Claude Code underlines a link it sees hovered; a row reserved for a card shows nothing of its own. + let reserved = link.as_ref().is_some_and(|l| l.uri().starts_with(INLINE_LINK)); + let underline = !reserved && (cell.flags.intersects(Flags::ALL_UNDERLINES) || link.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 ce39222..fd91968 100644 --- a/src/terminal/view/mod.rs +++ b/src/terminal/view/mod.rs @@ -1,11 +1,14 @@ //! GPUI view over a `Terminal`: paints the grid, turns GPUI input into VT input. -//! Children: `typing` (keys, paste, IME), `mouse` (selection, reporting, scrolling), `element` (the paint pass). +//! Children: `typing` (keys, paste, IME), `mouse` (selection, reporting, scrolling), `element` (the paint pass), +//! `cards` (the model's cards over the transcript). +mod cards; mod element; mod mouse; mod paths; mod typing; +use cards::INLINE_LINK; use element::TerminalElement; use std::ops::Range; @@ -28,6 +31,7 @@ use gpui::{ TextRun, UTF16Selection, UnderlineStyle, Window, div, fill, outline, point, prelude::*, px, relative, size, }; +use gpui_kit::base::TextSelection; use gpui_kit::component::input; use crate::terminal::glyphs; @@ -42,6 +46,8 @@ pub enum TerminalEvent { /// 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), + /// A card's button: text to send as the user's next message. + SendText(String), } #[derive(Clone, Copy)] @@ -109,6 +115,7 @@ pub struct TerminalView { 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>)>, + cards: cards::Cards, } /// What Ctrl+click opens. @@ -224,6 +231,7 @@ impl TerminalView { redraw_task: None, reference: None, hovered_link: None, + cards: cards::Cards::new(cx), } } @@ -470,8 +478,8 @@ impl Render for TerminalView { .track_focus(&self.focus) .on_key_down(cx.listener(Self::on_key_down)) // The Edit menu dispatches the text input's actions; a focused terminal answers them too. - .on_action(cx.listener(|this, _: &input::Copy, _, cx| { - this.copy(cx); + .on_action(cx.listener(|this, _: &input::Copy, window, cx| { + this.copy(window, cx); })) .on_action(cx.listener(|this, _: &input::Paste, _, cx| this.paste(cx))) .on_action(cx.listener(|this, _: &input::SelectAll, _, cx| this.select_all(cx))) @@ -486,6 +494,7 @@ impl Render for TerminalView { .when(self.hovered_link.is_some(), |d| d.cursor_pointer()) .on_scroll_wheel(cx.listener(Self::on_scroll)) .child(TerminalElement { view: cx.entity() }) + .children(self.inline_cards(cx)) .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))); diff --git a/src/terminal/view/mouse.rs b/src/terminal/view/mouse.rs index 3e82389..48ba1b6 100644 --- a/src/terminal/view/mouse.rs +++ b/src/terminal/view/mouse.rs @@ -5,6 +5,8 @@ use super::*; /// A wheel notch scrolls the terminal's scrollback this many times what the system reports for it. Lower than the /// panels' `glide::NOTCH`, because terminal lines are dense and 1.6 raced through the history. const TERMINAL_NOTCH: f32 = 0.8; +/// The lines Windows reports for a wheel notch at its default setting. +const NOTCH_LINES: f32 = 3.0; impl TerminalView { pub(super) fn grid_point(&self, position: Point) -> Option<(GridPoint, Side, usize, usize)> { @@ -128,7 +130,7 @@ impl TerminalView { } // Windows Terminal convention: right click copies when there is a selection, else pastes. MouseButton::Right => { - if !self.copy(cx) { + if !self.copy(window, cx) { self.paste(cx); } } @@ -169,6 +171,9 @@ impl TerminalView { (grid[point].hyperlink(), (0..grid.columns()).map(|c| row[Column(c)].c).collect::()) }; if let Some(link) = hyperlink { + if link.uri().starts_with(INLINE_LINK) { + return None; + } 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 { @@ -269,7 +274,10 @@ impl TerminalView { cx.notify(); return; } - self.scroll_px += lines; + // A mouse report means one notch, as in other terminals. Claude Code reads several in a row as fast spinning and + // speeds up: three per notch moved its view 25 lines, one moves it 3. + let per_notch = if notch && self.mouse_reporting(&event.modifiers) { NOTCH_LINES } else { 1.0 }; + self.scroll_px += lines / per_notch; let whole = self.scroll_px.trunc() as i32; if whole == 0 { return; diff --git a/src/terminal/view/typing.rs b/src/terminal/view/typing.rs index 4eecd76..88bdba2 100644 --- a/src/terminal/view/typing.rs +++ b/src/terminal/view/typing.rs @@ -168,7 +168,7 @@ impl TerminalView { } /// Copies the selection; returns whether there was one. - pub fn copy(&mut self, cx: &mut Context) -> bool { + pub fn copy(&mut self, window: &mut Window, cx: &mut Context) -> bool { let mut term = self.terminal.term.lock(); let text = term.selection_to_string().filter(|t| !t.is_empty()); if text.is_some() { @@ -181,6 +181,13 @@ impl TerminalView { cx.notify(); true } + // Text selected in a card: Ctrl+C copies it rather than interrupting Claude Code. + None if TextSelection::has_selection(window, cx) => { + let text = TextSelection::selected_text(window, cx); + cx.write_to_clipboard(ClipboardItem::new_string(text)); + TextSelection::clear(window, cx); + true + } None => false, } } @@ -195,7 +202,7 @@ impl TerminalView { cx.notify(); } - pub(super) fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context) { + pub(super) fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { let ks = &event.keystroke; let m = &ks.modifiers; let key = ks.key.as_str(); @@ -211,7 +218,7 @@ impl TerminalView { let mac_paste = m.platform && !m.shift && !m.control && !m.alt && key == "v"; // Every key handled here stops propagation, so the platform doesn't also deliver it as text. if mac_copy || copy_chord { - self.copy(cx); + self.copy(window, cx); cx.stop_propagation(); return; } @@ -221,7 +228,7 @@ impl TerminalView { return; } // Ctrl+C with a selection copies (like Windows Terminal); otherwise it is SIGINT as usual. - if m.control && !m.shift && !m.alt && key == "c" && self.copy(cx) { + if m.control && !m.shift && !m.alt && key == "c" && self.copy(window, cx) { cx.stop_propagation(); return; } diff --git a/src/visual/mod.rs b/src/visual/mod.rs index aa5eead..1b5d578 100644 --- a/src/visual/mod.rs +++ b/src/visual/mod.rs @@ -1,50 +1,55 @@ -//! The Visual panel: Markdown (and the `ui` dialect, `ui/`) the model draws beside the terminal. +//! Cards: Markdown (and the `ui` dialect, `ui/`) the model draws inside the terminal. //! //! The model calls Claudiu's `show_visual` tool; the per-process mod answers it in-process and, while the model is -//! still writing the call, streams what it has so far into `/visual/.json` (`mod/hooks/register.js`). -//! Claudiu polls that folder and keeps a stack of cards per session. Nothing goes through the PTY. +//! still writing the call, streams what it has so far into `/visual/--.json` +//! (`mod/hooks/register.js`). Claudiu polls that folder and hands each card to its session's terminal, which paints it +//! over rows the mod reserves in the transcript (`terminal/view/cards.rs`). Nothing goes through the PTY. +//! +//! The transcript keeps every call's input, so the mod writes a card again when it next draws the call's row. That is +//! what brings cards back after a restart: these files are a mailbox, not the record. pub mod ui; use std::collections::HashMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::time::SystemTime; use serde::Deserialize; -/// Env var holding the file the mod writes the card being drawn into. -pub const VISUAL_ENV: &str = "CLAUDIU_VISUAL_FILE"; +/// Env var holding the start of the path of every card file of a session: the mod adds `.json`. +pub const VISUAL_ENV: &str = "CLAUDIU_VISUAL_PREFIX"; -/// Most cards kept per session; the oldest go first. -pub const MAX_CARDS: usize = 20; +/// Between a session's record id and a call's id in a file name. Neither contains it. +const SEPARATOR: &str = "--"; pub fn dir() -> PathBuf { crate::datadir::data_dir().join("visual") } -/// The card file of one session, named by Claudiu's own record id (which survives `/clear`). -pub fn file(record_id: &str) -> PathBuf { - dir().join(format!("{}.json", crate::datadir::safe_file_stem(record_id))) +/// What the mod puts a call's id after: named by Claudiu's own record id, which survives `/clear`. +pub fn prefix(record_id: &str) -> PathBuf { + dir().join(format!("{}{SEPARATOR}", crate::datadir::safe_file_stem(record_id))) +} + +/// The file telling the mod how many terminal rows a card needs. +pub fn rows_file(record_stem: &str, call: &str) -> PathBuf { + dir().join(format!("{record_stem}{SEPARATOR}{}.rows", crate::datadir::safe_file_stem(call))) } -/// One `show_visual` call as the mod writes it: the same `call` until it is finished, `done` once it is. +/// One `show_visual` call as the mod writes it. #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct Card { pub call: String, #[serde(default)] - pub title: String, - #[serde(default)] pub content: String, - #[serde(default)] - pub done: bool, } /// What a file looked like when it was last read. pub type Stamp = (SystemTime, u64); -/// The cards that changed since `seen` (file stem and card), updating `seen`. Half-written or unreadable files are -/// left for the next look. -pub fn read_changed(dir: &std::path::Path, seen: &mut HashMap) -> Vec<(String, Card)> { +/// The cards that changed since `seen` (their session's file stem and the card), updating `seen`. Half-written or +/// unreadable files are left for the next look. +pub fn read_changed(dir: &Path, seen: &mut HashMap) -> Vec<(String, Card)> { let Ok(entries) = std::fs::read_dir(dir) else { return vec![] }; let mut out = vec![]; for e in entries.flatten() { @@ -53,69 +58,55 @@ pub fn read_changed(dir: &std::path::Path, seen: &mut HashMap) -> continue; } let Some(stem) = path.file_stem().and_then(|s| s.to_str()).map(str::to_string) else { continue }; + let Some((record, _)) = stem.split_once(SEPARATOR) else { continue }; + let record = record.to_string(); let Ok(meta) = e.metadata() else { continue }; let stamp = (meta.modified().unwrap_or(SystemTime::UNIX_EPOCH), meta.len()); if seen.get(&stem) == Some(&stamp) { continue; } let Some(card) = std::fs::read_to_string(&path).ok().and_then(|t| serde_json::from_str::(&t).ok()) else { continue }; - seen.insert(stem.clone(), stamp); - out.push((stem, card)); + seen.insert(stem, stamp); + out.push((record, card)); } out } -/// Add a card, or replace the one with the same `call` (the stream of one tool call), keeping at most `MAX_CARDS`. -/// Returns whether the call is new to the stack. -pub fn upsert(cards: &mut Vec, card: Card) -> bool { - if let Some(slot) = cards.iter_mut().find(|c| c.call == card.call) { - *slot = card; - return false; - } - cards.push(card); - let extra = cards.len().saturating_sub(MAX_CARDS); - cards.drain(..extra); - true -} - #[cfg(test)] mod tests { use super::*; - fn card(call: &str, content: &str, done: bool) -> Card { - Card { call: call.into(), title: String::new(), content: content.into(), done } - } - #[test] - fn a_call_replaces_its_own_card_and_the_stack_is_capped() { - let mut cards = vec![]; - assert!(upsert(&mut cards, card("a", "# Hi", false))); - assert!(!upsert(&mut cards, card("a", "# Hi there", true))); - assert_eq!(cards, vec![card("a", "# Hi there", true)]); - for i in 0..30 { - upsert(&mut cards, card(&format!("c{i}"), "x", true)); - } - assert_eq!(cards.len(), MAX_CARDS); - assert_eq!(cards.last().unwrap().call, "c29"); - assert!(cards.iter().all(|c| c.call != "a")); + fn each_call_of_a_session_is_read_and_only_changed_files_again() { + let dir = tempfile::tempdir().unwrap(); + let (one, two) = (dir.path().join("rec--c1.json"), dir.path().join("rec--c2.json")); + std::fs::write(&one, r##"{"call":"c1","content":"# One"}"##).unwrap(); + std::fs::write(&two, r##"{"call":"c2","content":"# Two"}"##).unwrap(); + let mut seen = HashMap::new(); + + let mut first = read_changed(dir.path(), &mut seen); + first.sort_by(|a, b| a.1.call.cmp(&b.1.call)); + assert_eq!(first.len(), 2, "two calls of one session are two cards"); + assert_eq!((first[0].0.as_str(), first[0].1.content.as_str()), ("rec", "# One")); + assert!(read_changed(dir.path(), &mut seen).is_empty(), "nothing changed"); + + std::fs::write(&one, r##"{"call":"c1","content":"# One, longer"}"##).unwrap(); + let again = read_changed(dir.path(), &mut seen); + assert_eq!(again.len(), 1); + assert_eq!(again[0].1.content, "# One, longer"); } #[test] - fn only_changed_files_are_read_again_and_garbage_is_left_for_later() { - let tmp = tempfile::tempdir().unwrap(); - std::fs::write(tmp.path().join("one.json"), r##"{"call":"t1","title":"T","content":"# A","done":false}"##).unwrap(); - std::fs::write(tmp.path().join("bad.json"), r#"{"call":"#).unwrap(); - std::fs::write(tmp.path().join("note.txt"), "x").unwrap(); + fn half_written_files_wait_and_other_files_are_ignored() { + let dir = tempfile::tempdir().unwrap(); + let card = dir.path().join("rec--c1.json"); + std::fs::write(&card, "{\"call\":\"c1\",\"cont").unwrap(); + std::fs::write(dir.path().join("rec--c1.rows"), "12").unwrap(); + std::fs::write(dir.path().join("old-format.json"), r#"{"call":"c0"}"#).unwrap(); let mut seen = HashMap::new(); - let got = read_changed(tmp.path(), &mut seen); - assert_eq!(got.len(), 1); - assert_eq!((got[0].0.as_str(), got[0].1.title.as_str(), got[0].1.done), ("one", "T", false)); - assert!(read_changed(tmp.path(), &mut seen).is_empty(), "unchanged"); - - std::fs::write(tmp.path().join("one.json"), r##"{"call":"t1","title":"T","content":"# A longer one","done":true}"##).unwrap(); - std::fs::write(tmp.path().join("bad.json"), r#"{"call":"t2","content":"ok","done":true}"#).unwrap(); - let mut got = read_changed(tmp.path(), &mut seen); - got.sort_by(|a, b| a.0.cmp(&b.0)); - assert_eq!(got.iter().map(|(s, c)| (s.as_str(), c.done)).collect::>(), [("bad", true), ("one", true)]); + assert!(read_changed(dir.path(), &mut seen).is_empty()); + + std::fs::write(&card, r#"{"call":"c1","content":"done"}"#).unwrap(); + assert_eq!(read_changed(dir.path(), &mut seen).len(), 1); } } diff --git a/src/visual/ui/mod.rs b/src/visual/ui/mod.rs index 124d3d4..5a1f490 100644 --- a/src/visual/ui/mod.rs +++ b/src/visual/ui/mod.rs @@ -1,21 +1,26 @@ -//! Generative UI in the Visual panel: Markdown that may contain fenced blocks with the info string `ui`, written as -//! HTML with inline CSS, drawn natively in Claudiu's theme instead of shown as code (`parse` reads it, `render` draws -//! it). The model is taught the dialect by `PROMPT`, which is the description of the `show_visual` tool. +//! Generative UI in a card: Markdown that may contain fenced blocks with the info string `ui`, written as HTML with +//! inline CSS, drawn natively in Claudiu's theme instead of shown as code (`parse` reads it, `render` draws it). The +//! model is taught the dialect by `PROMPT`, which is the description of the `show_visual` tool. mod parse; mod render; -use gpui_kit::component::text::{MarkdownNode, TextView, markdown_ast}; +use std::collections::{HashMap, HashSet}; + +use gpui::{Context, Entity, EventEmitter}; +use gpui_kit::component::text::{MarkdownNode, MarkdownParseContext, TextView, markdown_ast}; use parse::Tree; const NODE: &str = "claudiu-ui"; +const UI_TAGS: [&str; 4] = ["button", "chart", "details", "tabs"]; + /// 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 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. +pub const PROMPT: &str = r#"Draws Markdown as a card inside the terminal, under this call. Use it when a reply needs a table, comparison, flow, architecture, before/after, status board, timeline, chart or mock-up, instead of typing that into the terminal. Each call adds a new card. 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). +`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. There are no scripts; the interactive tags are listed below. ```` ```ui @@ -30,26 +35,104 @@ pub const PROMPT: &str = r#"Draws Markdown in Claudiu's Visual panel, beside the Tags: any HTML you like (div, span, p, h1-h6, ul/ol/li, table/thead/tbody/tr/th/td, pre, code, a, strong, em, hr, br, svg). Unknown tags are plain blocks. Extra shortcuts with the app's look built in: ``, ``, ``, ``, `` (flex row), `` (flex column), ``. Their style can be overridden with `style`. +Interactive tags, which go inside a `ui` block like everything else on this list: +- ``: a click sends its `send` text as the user's next message, once, and the button shows that text. It does nothing else, so use it to offer next steps or choices. +- `
Title...
`: a section that opens and closes; leave out `open` to start closed. Use it to keep long detail out of the way. +- `......`: one tab shown at a time. + +Charts from data, instead of plotting SVG by hand, also inside a `ui` block: ``, or `type="line"`. For several series, replace `values` with `` children (`color` is optional). `width` and, for line charts, `height` are optional. + Layout is flexbox: a block stacks its children vertically; `display:flex` lays them in a row (use `flex-direction:column` for a column) and `display:grid` with `grid-template-columns` (equal-width columns) or `` makes a grid. Supported CSS in `style="..."`: display, flex-direction, flex-wrap, flex, gap, align-items, justify-content, align-self, width, height, min/max-width, min/max-height (px, %, rem), padding, margin, background (a colour; gradients are ignored), color, border and border-left/right/top/bottom, border-radius, opacity, overflow:hidden, font-size, font-weight, font-style, font-family:monospace, text-align, line-height, text-decoration, white-space, grid-column:span N. There are no classes, `