From 5ef35e3a7423e5c98afe605e7522fb68f080844e Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 20:43:21 +0100 Subject: [PATCH 01/35] README: add tabs + multi-window to feature highlights The at-a-glance highlights list omitted the two headline 0.4.0 features (tabs and multi-window pane transfer); body sections already covered them. Co-Authored-By: Claude Opus 4.8 (1M context) --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index c3038c5..58eaa5a 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ A Windows desktop app for running and arranging many WSL terminals at once. Built primarily for managing multiple `claude` sessions across projects in parallel; works for any multi-shell workflow. - Tiling layout — recursive splits, draggable dividers, drag-to-swap pane headers, preset layouts (single / 2-col / 3-col / 2-row / 2×2) +- Tabs — each tab is an independent tile layout (one per project); PTYs in inactive tabs keep running +- Multi-window — pop a pane into its own window (right-click its toolbar, or drag it past the window edge); the PTY survives the move and scrollback replays - Three shell kinds per pane: WSL distros, PowerShell, saved SSH hosts (with optional Windows Credential Manager–stored passwords for auto-typing at the prompt) - Per-pane distro + cwd + label + font-size + broadcast state, persisted across restarts - Broadcast input to a group of panes (per-pane 📡 chip, or global toggle in the titlebar) From df159056a1d41d4f0713b879a6cb3fd7077c268a Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 20:44:58 +0100 Subject: [PATCH 02/35] memory: log v0.4.0 release wrap-up Co-Authored-By: Claude Opus 4.8 (1M context) --- memory.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/memory.md b/memory.md index 97c730c..f25f6f5 100644 --- a/memory.md +++ b/memory.md @@ -52,6 +52,14 @@ Durable memory for this project. Read at session start, update before session en ## Session log +### 2026-05-28 — **v0.4.0 shipped** (tabs + multi-window made actually working) + +Resume session that took the 2026-05-28 tabs/multi-window feature from "authored, unverified, buggy" to a shipped release. User built the NSIS `.exe` on Windows and ran `scripts/release.sh v0.4.0` (which also attaches `tiletopia.mcpb` now — the script was updated since the earlier session log note claimed it didn't). Version bumped 0.3.0 → 0.4.0 across package.json + Cargo.toml + tauri.conf.json + Cargo.lock atomically (commit `2a1f1d4`). README highlights list got tabs + multi-window bullets (`5ef35e3`); body sections + shortcut tables were already current, hard-deny count already 14, `gen:readme --check` clean. + +Commits this session: `bea6cf2` (capability + StrictMode adopt fix), `e6d0040` (accumulation + tab-close + scrollbars + drag ghost), `309b602` (XtermPane listener leak), `2a1f1d4` (version), `5ef35e3` (README). **Full technical detail for all fixes is in the "RESOLVED 2026-05-28 (resume session)" block under the original feature's session log below** — capability glob, destructive-read×StrictMode session loss, drag ghost (B1), drag-out registration wait, workspace-accumulation aggregator fix + corrupted-file reset, tab-close popover portal, global scrollbars, and the pre-release 3-agent audit (1 medium fixed, 1 high deferred). + +**Known deferred follow-up (carried):** the HIGH-severity transfer-refcount/PTY leak if a detached window closes mid-adopt — low-probability, ship-now decision. Proper fix sketched in the audit notes below (label→paneId adopting registry + close-handler force-kill). + ### 2026-05-28 — Tabs + multi-window pane transfer (3 phases, pushed) Two big features the user asked for in one session. Three commits on `main`: `1a035ad` (Phase 1 tabs), `8ad5178` (Phase 2 transfer), `6faf7e5` (Phase 3 drag-out). **Rust side authored in WSL — cargo build still needs verification on Windows host before this is runnable.** From 07bba99eb5e3e8a71db8e8d723bf2aea1089bd4e Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 21:31:59 +0100 Subject: [PATCH 03/35] Use canvas renderer to fix stuck/ghost cursor in panes The DOM renderer draws the cursor as a separate layered element; under the Claude TUI's rapid cursor hide/show plus cursorBlink it leaves a stale white block frozen where the cursor used to be. Load @xterm/addon-canvas (composites the cursor into the text surface) with a try/catch that falls back to the DOM renderer on init failure. Canvas over WebGL because tiletopia runs many panes and WebView2 caps live WebGL contexts (~16). Co-Authored-By: Claude Opus 4.8 (1M context) --- package.json | 1 + src/components/XtermPane.tsx | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/package.json b/package.json index 26121e1..393ccb7 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "@tauri-apps/api": "^2.0.0", "@tauri-apps/plugin-clipboard-manager": "^2.0.0", "@tauri-apps/plugin-opener": "^2.0.0", + "@xterm/addon-canvas": "^0.7.0", "@xterm/addon-fit": "^0.10.0", "@xterm/addon-web-links": "^0.12.0", "@xterm/xterm": "^5.5.0", diff --git a/src/components/XtermPane.tsx b/src/components/XtermPane.tsx index de4309a..1e76493 100644 --- a/src/components/XtermPane.tsx +++ b/src/components/XtermPane.tsx @@ -2,6 +2,7 @@ import { useRef, useEffect } from "react"; import { Terminal } from "@xterm/xterm"; import { FitAddon } from "@xterm/addon-fit"; import { WebLinksAddon } from "@xterm/addon-web-links"; +import { CanvasAddon } from "@xterm/addon-canvas"; import type { UnlistenFn } from "@tauri-apps/api/event"; import { readText as clipboardReadText, @@ -149,6 +150,23 @@ export default function XtermPane({ ); term.open(container); + // Use the canvas renderer instead of xterm's default DOM renderer. + // The DOM renderer draws the cursor as a separate layered element and, + // under the Claude TUI's rapid hide/show (\x1b[?25l/h) + cursorBlink, + // leaves a stale cursor block frozen where the cursor used to be (the + // "stuck white marker"). The canvas renderer composites the cursor into + // the same surface as the text, so hide/show transitions clear cleanly. + // Chosen over the WebGL addon because tiletopia runs many panes at once + // and Chromium/WebView2 caps live WebGL contexts (~16) — canvas has no + // such hard limit. Loaded after open() so the core renderer exists. + try { + term.loadAddon(new CanvasAddon()); + } catch (e) { + // If canvas init fails for any reason, xterm falls back to the DOM + // renderer on its own — degrade gracefully rather than blank the pane. + console.warn("CanvasAddon load failed; using DOM renderer:", e); + } + // Initial size — fit before asking the PTY for its dimensions. fit.fit(); From b5db68da8b8f97c463922be02e2358028038bb72 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 21:32:05 +0100 Subject: [PATCH 04/35] memory: log in-app code-markup/editor-pane idea Co-Authored-By: Claude Opus 4.8 (1M context) --- memory.md | 1 + 1 file changed, 1 insertion(+) diff --git a/memory.md b/memory.md index f25f6f5..c1af1ed 100644 --- a/memory.md +++ b/memory.md @@ -38,6 +38,7 @@ Durable memory for this project. Read at session start, update before session en - [x] ~~**M5 — Ship infrastructure.**~~ Custom icon, version bumped to 0.1.0, `scripts/release.sh` for one-shot tag+upload, README install section. Done 2026-05-22. **Next step (user action):** run `pnpm tauri build` on Windows then `scripts/release.sh v0.1.0` from WSL to cut the actual release. - [ ] **Native Windows shells (cmd / pwsh)?** `portable-pty` supports them for free; keep the option open. Decide whether to expose in UI at M3. - [ ] **Persistent scrollback across app restarts.** Would need an out-of-process mux daemon. Big scope creep; explicitly deferred past v1. +- [ ] **Code markup / syntax highlighting in-app (VSCode-style).** User idea 2026-05-28 — "would be kind of neat." Two readings, different feasibility: (a) **highlight code in terminal output** — not really doable in xterm.js; it renders raw bytes/ANSI and has no concept of "this region is Python." Would need to detect code blocks and re-emit ANSI color, which is fragile and fights TUIs like claude that already color their own output. (b) **a dedicated editor/viewer pane type** alongside terminal panes — embed Monaco or CodeMirror as a new LeafNode kind, open a file from the pane's cwd, get real VSCode-grade highlighting + read/scroll (maybe edit). This is the tractable version: the layout tree already supports heterogeneous leaves, so it's "add a non-xterm pane kind" rather than reworking the renderer. Scope: pick editor lib (CodeMirror 6 is lighter than Monaco for an embed), file-open IPC over WSL paths, decide read-only vs editable. Defer — nice-to-have, not core to the multi-terminal purpose. - [ ] **Keybinding philosophy.** Copy tmux, copy WezTerm, or invent? Decide at M3. - [ ] **Help (?) overlay.** Small `?` icon in the titlebar, opens a modal listing all keyboard shortcuts (split / close / promote / broadcast / palette / font size / nav) and quick tips on shell-picker dropdown + SSH host manager + saved-password autotype. Same modal style as `Palette` / `HostManager`. Source of truth lives in one place — refactor the README shortcuts table to be generated from it (or vice versa) so they can't drift. - [ ] **MCP server: Claude controls tiletopia.** Expose a Model Context Protocol server (stdio transport, runs inside the Tauri app or a sidecar) so a Claude session — running anywhere, including inside one of tiletopia's own panes — can drive the workspace. Capabilities to expose as MCP tools / resources: From 8bb080345e1e27e721af33237bbc3656ec917511 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 21:39:23 +0100 Subject: [PATCH 05/35] memory: log fan-out feature research backlog (5 prioritized + parked) Co-Authored-By: Claude Opus 4.8 (1M context) --- memory.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/memory.md b/memory.md index c1af1ed..57b28b6 100644 --- a/memory.md +++ b/memory.md @@ -51,6 +51,51 @@ Durable memory for this project. Read at session start, update before session en - Tauri integration: Rust-side MCP server using a published crate (or hand-rolled JSON-RPC); reuses the existing `PtyManager` + `hosts.json` + workspace state. Frontend gets read-only events when the MCP causes a layout change so the UI reflects it without races. Big — milestone-scale work; needs a design doc before code. - **Status:** v1 (read-only, 2026-05-25) + v2 (write surface, 2026-05-26 across PRs 1–4) shipped. All 11 originally-planned write tools are live: set_label, close_pane, swap_panes, promote_pane, apply_preset, spawn_pane, connect_host, write_pane, add_host, delete_host. Open polish items live in the per-session-log "follow-ups" sections. +## Feature backlog — 2026-05-28 fan-out research + +Four-agent research pass (terminal-landscape, AI-orchestration, xterm/Tauri ecosystem, codebase gap-analysis) into things to add. **Headline finding:** tiletopia already owns the hard primitives (tiling, multi-window, broadcast, MCP control surface); the real gap vs Conductor/Crystal/claude-squad/Vibe-Kanban is *git-worktree isolation + per-session status/cost/diff visibility*. Full agent deliverables are in this session's conversation; condensed here. + +**→ Exploring first (user-selected 2026-05-28):** +- [ ] **Per-session cost / token tracking.** Parse `~/.claude/projects//.jsonl` (`message.usage`: input/output/cache_read/cache_write + model per assistant line) → tokens + estimated $ per pane and per workspace. Easy parsing; the fiddly bit is mapping a tiletopia pane → its session file (capture session id / cwd at spawn). Difficulty: easy–medium. +- [ ] **Find in scrollback.** `@xterm/addon-search` — per-pane search box, `findNext`/`findPrevious`, regex + case opts, `searchOptions.decorations` for match highlight. Difficulty: easy. +- [ ] **Smart link providers.** `terminal.registerLinkProvider()` to make file paths (`src/foo.ts:12:3`), `localhost:PORT`, and error locations clickable — more flexible than the regex-only web-links addon already loaded. Open file in editor / browser. Difficulty: medium. +- [ ] **Unicode 11 + grapheme width.** `@xterm/addon-unicode11` (+ `@xterm/addon-unicode-graphemes`), set `terminal.unicode.activeVersion = '11'`. Fixes emoji/CJK/box-drawing width misalignment + cursor drift in TUIs. Difficulty: easy. +- [ ] **Pane navigation key handler.** `attachCustomKeyEventHandler()` to intercept tiling-WM chords (Ctrl+hjkl move focus, Alt+number select pane) before the PTY sees them, so shortcuts don't leak into the shell. Difficulty: easy. + +**Parked — circle back (saved, not yet prioritized):** + +*Tier 1 — core "many claudes" mission (highest leverage):* +- [ ] **Git worktree per session.** Spawn each claude pane into its own auto-created worktree+branch so parallel sessions on one repo can't clobber each other. The defining feature of every dedicated tool in the space (Crystal, Conductor, claude-squad, Vibe Kanban); Claude Code itself has `--worktree`. Unlocks best-of-N variants side-by-side. Fiddly part is worktree lifecycle/cleanup-on-close. Difficulty: medium. +- [ ] **Session status: working / waiting-for-input / done.** Existing idle detection conflates "blocked on a permission prompt" with "finished." Pattern-match claude's prompt strings (`Do you want to proceed?`, `❯`, y/n) to distinguish *needs-me* vs *done*. This is what lets one human supervise 8 agents; makes native notifications 10× more useful. Difficulty: medium. +- [ ] **Cross-session diff review.** Per-pane side tab rendering `git diff` in that session's worktree, with accept/reject. With worktrees, reviewing N branches is the bottleneck. Difficulty: medium. +- [ ] **Prompt queueing per pane.** Queue follow-up prompts that auto-send when claude returns to idle. Builds on existing idle detection + broadcast plumbing. Difficulty: easy. +- [ ] **Session templates / "spawn N".** Named launch presets (cwd, worktree scheme, initial prompt, env) + "spawn 3 copies, each a different approach." Difficulty: easy. +- [ ] **Auto-restart / resume on crash or context-limit.** Watch PTY exit codes, distinguish clean vs crash, re-spawn with `claude --resume`/`--continue` to keep long unattended runs alive. Difficulty: medium. +- [ ] **Per-session budget caps w/ auto-pause.** Token/$ ceiling per session/workspace; auto-pause or notify at ~85%, flag sessions stuck retrying. Layers on cost tracking. Difficulty: medium. +- [ ] **Kanban/task-board view over sessions.** Card = task = worktree = agent, moving queued → running → needs-review → merged (à la Vibe Kanban). MCP server makes Claude-driven task decomposition feasible. Substantial 2nd UI paradigm — defer until the Tier-1 cluster lands. Difficulty: hard. + +*Tier 2 — terminal power-user:* +- [ ] **Layout restore across restarts (lighter version).** `@xterm/addon-serialize` snapshots screen+scrollback so reopening restores live-looking terminals. The 80% version of the already-deferred "persistent scrollback" (which needs an out-of-process mux daemon). Difficulty: medium. +- [ ] **Output triggers (regex → action).** iTerm2-style: watch each PTY stream for user regex, fire notify/highlight/auto-keystroke/mark. Reuses the idle-detection data tap; more precise than generic idle. Difficulty: medium. +- [ ] **Quick-select / hints mode.** Overlay short labels on URLs/paths/hashes in the visible buffer; type label to copy/open (WezTerm quick-select / Kitty hints). Difficulty: medium. +- [ ] **Activity markers / decorations.** `registerMarker()` + `registerDecoration()` to mark prompt boundaries / errors / command-finished in the gutter + jump between them. Difficulty: medium. +- [ ] **Stacked / floating panes.** Zellij-style: collapse 10+ panes into stacks (thin title bars, expand on focus), or float a scratch terminal over the grid. Scales past where pure tiling breaks (~8 panes). Difficulty: medium. +- [ ] **Capture / pipe pane output.** tmux capture-pane / pipe-pane: dump scrollback to file or tee live output to a log/command. Auto-logging each claude session → searchable transcripts. Difficulty: easy. +- [ ] **Pane fuzzy switcher.** Extend the Ctrl+K palette with a pane-target source: fuzzy-find any pane across tabs/windows by title/cwd/project/command. Difficulty: easy. +- [ ] **Saved command/prompt snippet library.** Reusable parameterized commands/prompts inserted into any pane (or broadcast) via the palette (Warp Workflows). Difficulty: easy. +- [ ] **System clipboard addon (OSC 52).** `@xterm/addon-clipboard` so a claude session inside WSL can set the host clipboard. Difficulty: easy. +- [ ] **Inline images (sixel / iTerm IIP).** `@xterm/addon-image` to render images CLIs emit (charts, previews, imgcat). Niche; needs memory tuning. Difficulty: medium. +- [ ] **Inline file/markdown/diff preview.** Click a path in output → side-panel preview (markdown render, image, diff) without leaving the app (Wave Terminal). Difficulty: hard. + +*Tier 3 — platform & polish (some overlap existing backlog):* +- [ ] **System tray + minimize-to-tray.** `TrayIcon` (`@tauri-apps/api/tray`) — keep tiletopia resident, restore/jump-to-workspace from tray. Difficulty: easy–medium. +- [ ] **Single-instance + window-state persistence.** `tauri-plugin-single-instance` + `tauri-plugin-window-state` — no duplicate launches, restore window geometry (the per-window-geometry gap noted elsewhere in this file). Difficulty: easy. +- [ ] **Global summon hotkey.** `tauri-plugin-global-shortcut` — system-wide hotkey to raise tiletopia from any app. Difficulty: easy. +- [ ] **Settings panel.** A home for the already-deferred configurable idle threshold + MCP port + theme toggle, all currently hardcoded. Difficulty: easy–medium. +- [ ] **Small UX wins (codebase agent):** auto-save MCP policy rules (debounce like workspace save); `Ctrl+Shift+N` for new pane; 5s undo-toast on pane close (toast infra exists); narrow-window titlebar overflow menu; stronger broadcast-group visual tint; change-cwd-without-respawn (needs `/proc//cwd` probe). + +(Native OS notifications, configurable idle threshold, and persistent scrollback already appear in the top checklist — not duplicated here; the research reinforces their priority and the status-detection item above multiplies the notification payoff.) + ## Session log ### 2026-05-28 — **v0.4.0 shipped** (tabs + multi-window made actually working) From baa00dfc5cfa49101e4439bc72691ad044f9e218 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 21:51:29 +0100 Subject: [PATCH 06/35] Add find-in-scrollback, unicode11, and keyboard pane navigation Three xterm.js features, implemented together because they share the XtermPane mount + the single attachCustomKeyEventHandler: - Unicode 11: load @xterm/addon-unicode11, set activeVersion='11' after the canvas renderer so emoji/CJK/box-drawing widths stop drifting. - Find in scrollback: @xterm/addon-search + a new per-pane SearchBar overlay (Ctrl+Shift+F to open, Enter/Shift+Enter next/prev, regex + case toggles, Esc to close & refocus). Overlay is an absolutely- positioned sibling in a position:relative wrapper so fit() is unaffected. - Pane navigation: Ctrl+Alt+Arrow / Ctrl+Alt+HJKL (spatial neighbour via findNeighborInDirection) and Alt+1..9 (Nth leaf in walkLeaves order). XtermPane emits a NavigateIntent; App resolves the target leaf and sets it active, reusing the existing isActive->focusTrigger refocus chain. All chords live in one attachCustomKeyEventHandler (xterm replaces the handler on each call). Shortcuts added to shortcuts.ts (SoT for README + Help), including the Alt+digit shell-conflict caveat. tsc clean apart from the three not-yet-installed addon modules. Needs pnpm install on the Windows host + runtime verification. Co-Authored-By: Claude Opus 4.8 (1M context) --- package.json | 2 + src/App.tsx | 34 +++++- src/components/SearchBar.css | 105 ++++++++++++++++++ src/components/SearchBar.tsx | 177 ++++++++++++++++++++++++++++++ src/components/XtermPane.tsx | 179 ++++++++++++++++++++++++++----- src/lib/layout/LeafPane.tsx | 9 ++ src/lib/layout/orchestration.tsx | 19 +++- src/lib/shortcuts.ts | 30 +++++- 8 files changed, 526 insertions(+), 29 deletions(-) create mode 100644 src/components/SearchBar.css create mode 100644 src/components/SearchBar.tsx diff --git a/package.json b/package.json index 393ccb7..102c58e 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,8 @@ "@tauri-apps/plugin-opener": "^2.0.0", "@xterm/addon-canvas": "^0.7.0", "@xterm/addon-fit": "^0.10.0", + "@xterm/addon-search": "^0.15.0", + "@xterm/addon-unicode11": "^0.8.0", "@xterm/addon-web-links": "^0.12.0", "@xterm/xterm": "^5.5.0", "react": "^18.3.0", diff --git a/src/App.tsx b/src/App.tsx index 07fefe2..ffceee2 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -98,7 +98,7 @@ import { presetTwoRows, presetTwoByTwo, } from "./lib/layout/tree"; -import { OrchestrationProvider, type Orchestration } from "./lib/layout/orchestration"; +import { OrchestrationProvider, type Orchestration, type NavigateIntent } from "./lib/layout/orchestration"; import LeafPane from "./lib/layout/LeafPane"; import Gutter from "./lib/layout/Gutter"; import Notifications, { type Toast } from "./components/Notifications"; @@ -717,6 +717,36 @@ export default function App() { setActiveLeafId(leafId); }, []); + // navigateTo — called from XtermPane's attachCustomKeyEventHandler via + // LeafPane's onNavigate prop. Resolves the target leaf from the current + // layout tree and sets it active; the LeafPane isActive→focusTrigger + // effect then refocuses the xterm textarea automatically. + const navigateTo = useCallback((intent: NavigateIntent) => { + const currentTree = treeRef.current; + const currentActiveId = activeLeafId; + + if (intent.kind === "direction") { + const layout = flattenLayout(currentTree); + if (!currentActiveId) { + const first = layout.leaves[0]?.leaf.id; + if (first) setActiveLeafId(first); + return; + } + const nextId = findNeighborInDirection( + layout.leaves, + currentActiveId, + intent.dir, + ); + if (nextId) setActiveLeafId(nextId); + } else { + // intent.kind === "index" + const leaves = Array.from(walkLeaves(currentTree)); + // Clamp: Alt+9 with 3 panes picks the 3rd pane. + const target = leaves[Math.min(intent.n, leaves.length) - 1]; + if (target) setActiveLeafId(target.id); + } + }, [activeLeafId]); // treeRef is a ref — stable, intentionally not listed + const openHostManager = useCallback(() => setHostManagerOpen(true), []); const closeHostManager = useCallback(() => setHostManagerOpen(false), []); @@ -1242,6 +1272,7 @@ export default function App() { toggleMcpAllow, openHostManager, setActive, + navigateTo, registerPaneId, broadcastFrom, notify, @@ -1266,6 +1297,7 @@ export default function App() { toggleMcpAllow, openHostManager, setActive, + navigateTo, registerPaneId, broadcastFrom, notify, diff --git a/src/components/SearchBar.css b/src/components/SearchBar.css new file mode 100644 index 0000000..0f389bd --- /dev/null +++ b/src/components/SearchBar.css @@ -0,0 +1,105 @@ +/* --------------------------------------------------------------------------- + SearchBar — find-in-scrollback overlay. + + Positioned absolutely inside XtermPane's container div (which must be + position: relative). Sits at the top-right of the pane, z-index 10 so it + floats above the xterm canvas but below any app-level modals (z-index 100). + Colour palette matches Palette.css / Help.css: #181818 surface, #2a2a2a + borders, #e6e6e6 text, #1a3a5c accent. +--------------------------------------------------------------------------- */ + +.search-bar { + position: absolute; + top: 4px; + right: 4px; + z-index: 10; + display: flex; + align-items: center; + gap: 3px; + background: #181818; + border: 1px solid #2a2a2a; + border-radius: 5px; + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.55); + padding: 3px 4px; + font-family: "Cascadia Mono", "JetBrains Mono", "Consolas", monospace; + font-size: 12px; + color: #e6e6e6; +} + +.search-input { + font: inherit; + font-size: 12px; + color: #e6e6e6; + background: #1f1f1f; + border: 1px solid #2a2a2a; + border-radius: 3px; + padding: 3px 7px; + outline: none; + width: 180px; + caret-color: #e6e6e6; +} + +.search-input:focus { + border-color: #1a3a5c; + box-shadow: 0 0 0 1px #1a3a5c; +} + +.search-input::placeholder { + color: #555; +} + +/* Toggle buttons (Aa / .*) */ +.search-toggle { + font: inherit; + font-size: 11px; + background: transparent; + border: 1px solid #2a2a2a; + border-radius: 3px; + color: #888; + padding: 2px 5px; + cursor: pointer; + line-height: 1; + transition: background 0.1s, color 0.1s; +} + +.search-toggle:hover, +.search-toggle[aria-pressed="true"] { + background: #1a3a5c; + border-color: #1a5c8a; + color: #cce6ff; +} + +/* Prev / Next navigation arrows */ +.search-nav { + font: inherit; + font-size: 13px; + background: transparent; + border: 1px solid #2a2a2a; + border-radius: 3px; + color: #aaa; + padding: 1px 6px; + cursor: pointer; + line-height: 1; +} + +.search-nav:hover { + background: #2a2a2a; + color: #e6e6e6; +} + +/* Close button */ +.search-close { + background: transparent; + border: none; + color: #666; + font-size: 16px; + line-height: 1; + padding: 1px 5px; + cursor: pointer; + border-radius: 3px; +} + +.search-close:hover { + background: #2a2a2a; + color: #ddd; +} diff --git a/src/components/SearchBar.tsx b/src/components/SearchBar.tsx new file mode 100644 index 0000000..1d41a99 --- /dev/null +++ b/src/components/SearchBar.tsx @@ -0,0 +1,177 @@ +import { useRef, useEffect, useState } from "react"; +import type { SearchAddon } from "@xterm/addon-search"; +import "./SearchBar.css"; + +// --------------------------------------------------------------------------- +// SearchBar — per-pane find-in-scrollback overlay. +// +// Rendered as an absolutely-positioned sibling of the xterm canvas inside +// XtermPane's container div (position: relative). The SearchAddon instance +// is owned by XtermPane and passed down as a prop; no IPC or Context needed. +// +// Toggle state (caseSensitive, regex) uses useState so aria-pressed reflects +// the live value on every render — refs alone don't trigger re-renders. +// --------------------------------------------------------------------------- + +interface SearchBarProps { + searchAddon: SearchAddon; + onClose: () => void; +} + +export default function SearchBar({ searchAddon, onClose }: SearchBarProps) { + const inputRef = useRef(null); + const queryRef = useRef(""); + const [caseSensitive, setCaseSensitive] = useState(false); + const [useRegex, setUseRegex] = useState(false); + + // Keep stable refs to toggle values so findNext/findPrev closures always + // see the current value without needing to be recreated on each state change. + const caseSensitiveRef = useRef(caseSensitive); + const useRegexRef = useRef(useRegex); + useEffect(() => { caseSensitiveRef.current = caseSensitive; }, [caseSensitive]); + useEffect(() => { useRegexRef.current = useRegex; }, [useRegex]); + + // Autofocus the input when the bar mounts. + useEffect(() => { + queueMicrotask(() => inputRef.current?.focus()); + }, []); + + function getOptions() { + return { + caseSensitive: caseSensitiveRef.current, + regex: useRegexRef.current, + // Highlight all matches and mark the active one distinctly. + decorations: { + matchBackground: "#3a3a00", + matchBorder: "#888800", + matchOverviewRuler: "#888800", + activeMatchBackground: "#b5890080", + activeMatchBorder: "#e6c000", + activeMatchColorOverviewRuler: "#e6c000", + }, + }; + } + + function findNext() { + if (!queryRef.current) return; + searchAddon.findNext(queryRef.current, getOptions()); + } + + function findPrev() { + if (!queryRef.current) return; + searchAddon.findPrevious(queryRef.current, getOptions()); + } + + function handleInput(e: React.ChangeEvent) { + queryRef.current = e.target.value; + // Live-search: jump to next match as you type. + if (queryRef.current) { + searchAddon.findNext(queryRef.current, getOptions()); + } + } + + function handleKeyDown(e: React.KeyboardEvent) { + if (e.key === "Escape") { + e.preventDefault(); + onClose(); + } else if (e.key === "Enter") { + e.preventDefault(); + if (e.shiftKey) { + findPrev(); + } else { + findNext(); + } + } + } + + function toggleCase() { + setCaseSensitive((v) => { + const next = !v; + caseSensitiveRef.current = next; + // Re-run with the new option so decorations update immediately. + if (queryRef.current) { + searchAddon.findNext(queryRef.current, { + ...getOptions(), + caseSensitive: next, + }); + } + return next; + }); + } + + function toggleRegex() { + setUseRegex((v) => { + const next = !v; + useRegexRef.current = next; + if (queryRef.current) { + searchAddon.findNext(queryRef.current, { + ...getOptions(), + regex: next, + }); + } + return next; + }); + } + + return ( +
+ + + + + + + + + + + +
+ ); +} diff --git a/src/components/XtermPane.tsx b/src/components/XtermPane.tsx index 1e76493..a993c11 100644 --- a/src/components/XtermPane.tsx +++ b/src/components/XtermPane.tsx @@ -1,8 +1,11 @@ -import { useRef, useEffect } from "react"; +import { useRef, useEffect, useState } from "react"; import { Terminal } from "@xterm/xterm"; import { FitAddon } from "@xterm/addon-fit"; import { WebLinksAddon } from "@xterm/addon-web-links"; import { CanvasAddon } from "@xterm/addon-canvas"; +import { SearchAddon } from "@xterm/addon-search"; +import { Unicode11Addon } from "@xterm/addon-unicode11"; +import SearchBar from "./SearchBar"; import type { UnlistenFn } from "@tauri-apps/api/event"; import { readText as clipboardReadText, @@ -21,6 +24,7 @@ import { type PaneId, type SpawnSpec, } from "../ipc"; +import type { NavigateIntent } from "../lib/layout/orchestration"; // --------------------------------------------------------------------------- // base64 helpers (private to this module) @@ -72,6 +76,12 @@ interface XtermPaneProps { focusTrigger?: number; /** Absolute font size in px. Changes are applied live (fit + PTY resize). */ fontSize?: number; + /** Called when the user presses a tiling-WM navigation chord inside the + * terminal. XtermPane only emits the intent; the parent (LeafPane/App) + * resolves the target leaf from the current layout and sets it active. + * Defined as an optional callback so single-pane windows don't require + * wiring it up. */ + onNavigate?: (intent: NavigateIntent) => void; } const DEFAULT_XTERM_FONT_SIZE = 13; @@ -90,11 +100,14 @@ export default function XtermPane({ onFocus, focusTrigger = 0, fontSize, + onNavigate, }: XtermPaneProps) { const containerRef = useRef(null); const termRef = useRef(null); const fitRef = useRef(null); const paneIdRef = useRef(null); + const searchAddonRef = useRef(null); + const [searchOpen, setSearchOpen] = useState(false); // Stash the most recent `fontSize` prop so the mount effect can pick // up the initial value without re-running when it changes (the secondary // effect below handles dynamic updates). @@ -107,12 +120,18 @@ export default function XtermPane({ const onInputRef = useRef(onInput); const onDataReceivedRef = useRef(onDataReceived); const onFocusRef = useRef(onFocus); + const onNavigateRef = useRef(onNavigate); + // Stable ref for setSearchOpen so it can be called from inside the + // attachCustomKeyEventHandler closure without the closure going stale. + const setSearchOpenRef = useRef<(v: boolean) => void>(setSearchOpen); useEffect(() => { onStatusRef.current = onStatus; }, [onStatus]); useEffect(() => { onSpawnRef.current = onSpawn; }, [onSpawn]); useEffect(() => { onInputRef.current = onInput; }, [onInput]); useEffect(() => { onDataReceivedRef.current = onDataReceived; }, [onDataReceived]); useEffect(() => { onFocusRef.current = onFocus; }, [onFocus]); + useEffect(() => { onNavigateRef.current = onNavigate; }, [onNavigate]); + useEffect(() => { setSearchOpenRef.current = setSearchOpen; }, [setSearchOpen]); // ------------------------------------------------------------------------- // Mount / unmount: create terminal, spawn PTY, wire listeners @@ -167,6 +186,24 @@ export default function XtermPane({ console.warn("CanvasAddon load failed; using DOM renderer:", e); } + // Load Unicode 11 addon for correct width handling of emoji, CJK, and + // box-drawing characters. This prevents cursor drift in TUIs that rely on + // Unicode 11 character widths. Loaded after CanvasAddon so the renderer + // surface is set before width calculations begin. + try { + term.loadAddon(new Unicode11Addon()); + term.unicode.activeVersion = "11"; + } catch (e) { + console.warn("Unicode11Addon load failed:", e); + } + + // Load the search addon so find-in-scrollback works. Must be loaded + // after open() so the terminal viewport exists for decoration rendering, + // and after CanvasAddon since it decorates the same canvas surface. + const search = new SearchAddon(); + searchAddonRef.current = search; + term.loadAddon(search); + // Initial size — fit before asking the PTY for its dimensions. fit.fit(); @@ -279,36 +316,100 @@ export default function XtermPane({ onInputRef.current?.(b64); }); - // Ctrl+Shift+C / Ctrl+Shift+V — copy selection / paste from clipboard. - // Runs before xterm consumes the key, so the textarea never sees a raw - // Ctrl+V (which would otherwise inject ^V into the PTY). term.paste() - // routes through onData → writeToPane, so broadcasting and bracketed - // paste both keep working for free. + // Intercept tiling-WM chords before the PTY sees them. All families + // share ONE attachCustomKeyEventHandler call — xterm.js replaces the + // previous handler on every call, so a second call anywhere would + // silently discard all earlier interceptions. // - // Uses tauri-plugin-clipboard-manager instead of navigator.clipboard so - // WebView2 doesn't surface its native "Allow clipboard access?" prompt. + // Family 1: Ctrl+Shift+C / Ctrl+Shift+V — copy selection / paste. + // Uses tauri-plugin-clipboard-manager so WebView2 never shows its + // native "Allow clipboard access?" prompt. term.paste() routes + // through onData → writeToPane so broadcasting + bracketed paste + // keep working for free. + // + // Family 2: Ctrl+Shift+F — open/focus the find-in-scrollback bar. + // Swallowed before xterm or the PTY sees the raw keypress. Uses the + // stable setSearchOpenRef so the closure never goes stale. + // + // Family 3: Ctrl+Alt+Arrow / Ctrl+Alt+H/J/K/L — spatial pane focus. + // XtermPane emits onNavigate({ kind: "direction", dir }) and returns + // false so the chord is swallowed before it reaches the PTY. The + // parent (LeafPane → App) resolves the neighbour and bumps + // focusTrigger on the new active pane. + // + // Family 4: Alt+1..9 — index-based pane focus. + // Emits onNavigate({ kind: "index", n }) and swallows. Note: bare + // Alt+digit is used by some shells (readline digit-argument, vim/nvim) + // — this interception is an accepted v1 trade-off (see shortcuts.ts). term?.attachCustomKeyEventHandler((e) => { if (e.type !== "keydown") return true; - if (!e.ctrlKey || !e.shiftKey || e.altKey) return true; - if (e.code === "KeyC") { - const sel = term?.getSelection(); - if (sel) { - void clipboardWriteText(sel).catch((err) => - console.warn("clipboard write failed:", err), - ); + + // --- Family 1 & 2: Ctrl+Shift+* (no Alt) --------------------------- + if (e.ctrlKey && e.shiftKey && !e.altKey) { + if (e.code === "KeyF") { + // Ctrl+Shift+F — open find-in-scrollback bar. + e.preventDefault(); + setSearchOpenRef.current(true); + return false; + } + if (e.code === "KeyC") { + // Ctrl+Shift+C — copy selection to clipboard. + const sel = term?.getSelection(); + if (sel) { + void clipboardWriteText(sel).catch((err) => + console.warn("clipboard write failed:", err), + ); + } + e.preventDefault(); + return false; + } + if (e.code === "KeyV") { + // Ctrl+Shift+V — paste from clipboard via term.paste() so + // broadcasting and bracketed paste work for free. + e.preventDefault(); + clipboardReadText() + .then((text) => { + if (text && term) term.paste(text); + }) + .catch((err) => console.warn("clipboard read failed:", err)); + return false; } - e.preventDefault(); - return false; } - if (e.code === "KeyV") { - e.preventDefault(); - clipboardReadText() - .then((text) => { - if (text && term) term.paste(text); - }) - .catch((err) => console.warn("clipboard read failed:", err)); - return false; + + // --- Family 3: Ctrl+Alt+Arrow / Ctrl+Alt+H/J/K/L (spatial nav) ----- + if (e.ctrlKey && e.altKey && !e.shiftKey && onNavigateRef.current) { + // Arrow keys + const ARROW_DIR: Record = { + ArrowLeft: "left", + ArrowRight: "right", + ArrowUp: "up", + ArrowDown: "down", + }; + // Vim-style HJKL + const VIM_DIR: Record = { + KeyH: "left", + KeyJ: "down", + KeyK: "up", + KeyL: "right", + }; + const dir = ARROW_DIR[e.code] ?? VIM_DIR[e.code]; + if (dir) { + e.preventDefault(); + onNavigateRef.current({ kind: "direction", dir }); + return false; + } } + + // --- Family 4: Alt+1..9 (index-based pane focus) ------------------- + if (e.altKey && !e.ctrlKey && !e.shiftKey && onNavigateRef.current) { + const digit = e.code.match(/^Digit([1-9])$/); + if (digit) { + e.preventDefault(); + onNavigateRef.current({ kind: "index", n: parseInt(digit[1], 10) }); + return false; + } + } + return true; }); @@ -389,6 +490,7 @@ export default function XtermPane({ term = null; termRef.current = null; fitRef.current = null; + searchAddonRef.current = null; paneIdRef.current = null; }; // spec is read once at mount; intentionally omitted from deps so we @@ -435,5 +537,30 @@ export default function XtermPane({ } }, [fontSize]); - return
; + // Close the search bar and return focus to the xterm textarea so the user + // can resume typing immediately. Queries the well-known xterm helper + // textarea selector — the same pattern used in the focusTrigger effect. + function closeSearch() { + setSearchOpen(false); + const ta = containerRef.current?.querySelector( + ".xterm-helper-textarea", + ); + ta?.focus(); + } + + // The outer wrapper is position:relative so the absolutely-positioned + // SearchBar anchors inside the pane without escaping to a positioned + // ancestor further up the tree. The FitAddon measures containerRef's div + // (the inner one), which still fills 100% of the wrapper — no sizing break. + return ( +
+
+ {searchOpen && searchAddonRef.current && ( + + )} +
+ ); } diff --git a/src/lib/layout/LeafPane.tsx b/src/lib/layout/LeafPane.tsx index 75ad84c..cbd53af 100644 --- a/src/lib/layout/LeafPane.tsx +++ b/src/lib/layout/LeafPane.tsx @@ -194,6 +194,14 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) { [orch.setActive, leaf.id], ); + // Delegate keyboard navigation intents from XtermPane up to App via + // orch.navigateTo. XtermPane stays dumb (emits intent only); App resolves + // the target leaf from the current layout and bumps focusTrigger. + const onPaneNavigate = useCallback( + (intent: Parameters[0]) => orch.navigateTo(intent), + [orch.navigateTo], + ); + const onStatus = useCallback((msg: string, ok: boolean) => { setStatus(msg); setStatusOk(ok); @@ -575,6 +583,7 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) { onInput={onTerminalInput} onDataReceived={onDataReceived} onFocus={onXtermFocus} + onNavigate={onPaneNavigate} focusTrigger={focusTrigger} fontSize={resolveFontSize(leaf.fontSizeOffset)} /> diff --git a/src/lib/layout/orchestration.tsx b/src/lib/layout/orchestration.tsx index cd381ff..46effad 100644 --- a/src/lib/layout/orchestration.tsx +++ b/src/lib/layout/orchestration.tsx @@ -1,5 +1,5 @@ import { createContext, useContext, type ReactNode } from "react"; -import type { Orientation, NodeId, LeafShellSpec } from "./tree"; +import type { Orientation, NodeId, LeafShellSpec, Direction } from "./tree"; import type { PaneId, SshHost } from "../../ipc"; /** @@ -62,6 +62,16 @@ export interface Orchestration { * The PTY stays alive across the move (the new window's XtermPane * adopts the existing PaneId; scrollback ring is replayed). */ moveToNewWindow: (leafId: NodeId) => void; + /** + * Navigate focus from within a pane's key-handler. XtermPane emits the + * intent; LeafPane/App resolve the target leaf and set it active. + * + * `{ kind: "direction", dir }` — move to the spatial neighbour in that + * direction using the same flattenLayout geometry as Ctrl+Shift+Arrow. + * `{ kind: "index", n }` — focus the Nth leaf in DFS (walkLeaves) order, + * 1-indexed, clamped to the leaf count (so Alt+9 with 3 panes picks pane 3). + */ + navigateTo: (intent: NavigateIntent) => void; /** Returns a PaneId only for leaves that just arrived via a window * transfer (so LeafPane can pass `existingPaneId` to XtermPane to skip * the spawn). One-shot — App clears the entry once the pane has @@ -69,6 +79,13 @@ export interface Orchestration { getInitialPaneIdFor: (leafId: NodeId) => PaneId | undefined; } +/** Discriminated intent emitted by XtermPane's key handler. App resolves + * the actual target leaf from the current tree without XtermPane needing + * to know anything about layout geometry or leaf ordering. */ +export type NavigateIntent = + | { kind: "direction"; dir: Direction } + | { kind: "index"; n: number }; + const OrchestrationContext = createContext(null); export function OrchestrationProvider({ diff --git a/src/lib/shortcuts.ts b/src/lib/shortcuts.ts index 5b1b789..a72cddb 100644 --- a/src/lib/shortcuts.ts +++ b/src/lib/shortcuts.ts @@ -66,7 +66,23 @@ export const SHORTCUT_SECTIONS: ShortcutSection[] = [ { keys: "Ctrl+K", description: "Open jump-to-pane palette" }, { keys: "Ctrl+Shift+← / → / ↑ / ↓", - description: "Focus neighbour pane in that direction", + description: + "Focus neighbour pane in that direction (window-level — works even when no terminal is focused)", + }, + { + keys: "Ctrl+Alt+← / → / ↑ / ↓", + description: + "Focus neighbour pane in that direction (from inside the terminal — intercepted before the PTY sees it)", + }, + { + keys: "Ctrl+Alt+H / J / K / L", + description: + "Same as Ctrl+Alt+Arrow but in Vim-style HJKL order (left / down / up / right)", + }, + { + keys: "Alt+1 … Alt+9", + description: + "Focus the Nth pane in layout order (DFS: left-to-right, top-to-bottom); clamped to pane count. Note: swallows bare Alt+digit — shells using readline digit-argument or vim buffer-jump may conflict.", }, ], }, @@ -100,6 +116,18 @@ export const SHORTCUT_SECTIONS: ShortcutSection[] = [ keys: "Ctrl+Shift+C / Ctrl+Shift+V", description: "Copy selection / paste in terminal", }, + { + keys: "Ctrl+Shift+F", + description: "Open find-in-scrollback bar for the focused pane", + }, + { + keys: "Enter / Shift+Enter", + description: "Next / previous match (while search bar is focused)", + }, + { + keys: "Escape", + description: "Close find bar and return focus to terminal", + }, ], }, { From 1bbc6a578339b9212f2af76dfb7eae31d6538cdc Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 21:52:07 +0100 Subject: [PATCH 07/35] memory: mark find-in-scrollback, unicode11, pane-nav implemented (pending Windows verify) Co-Authored-By: Claude Opus 4.8 (1M context) --- memory.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/memory.md b/memory.md index 57b28b6..523448e 100644 --- a/memory.md +++ b/memory.md @@ -57,10 +57,12 @@ Four-agent research pass (terminal-landscape, AI-orchestration, xterm/Tauri ecos **→ Exploring first (user-selected 2026-05-28):** - [ ] **Per-session cost / token tracking.** Parse `~/.claude/projects//.jsonl` (`message.usage`: input/output/cache_read/cache_write + model per assistant line) → tokens + estimated $ per pane and per workspace. Easy parsing; the fiddly bit is mapping a tiletopia pane → its session file (capture session id / cwd at spawn). Difficulty: easy–medium. -- [ ] **Find in scrollback.** `@xterm/addon-search` — per-pane search box, `findNext`/`findPrevious`, regex + case opts, `searchOptions.decorations` for match highlight. Difficulty: easy. - [ ] **Smart link providers.** `terminal.registerLinkProvider()` to make file paths (`src/foo.ts:12:3`), `localhost:PORT`, and error locations clickable — more flexible than the regex-only web-links addon already loaded. Open file in editor / browser. Difficulty: medium. -- [ ] **Unicode 11 + grapheme width.** `@xterm/addon-unicode11` (+ `@xterm/addon-unicode-graphemes`), set `terminal.unicode.activeVersion = '11'`. Fixes emoji/CJK/box-drawing width misalignment + cursor drift in TUIs. Difficulty: easy. -- [ ] **Pane navigation key handler.** `attachCustomKeyEventHandler()` to intercept tiling-WM chords (Ctrl+hjkl move focus, Alt+number select pane) before the PTY sees them, so shortcuts don't leak into the shell. Difficulty: easy. +- [x] ~~**Find in scrollback.**~~ Done (code) 2026-05-28, commit on `main` — `@xterm/addon-search` + new `src/components/SearchBar.tsx`/`.css` overlay, Ctrl+Shift+F open / Enter / Shift+Enter / Esc, regex + case toggles, decoration highlight. **Pending: `pnpm install` on Windows host + runtime verify** (addon not in WSL node_modules; tsc clean otherwise). +- [x] ~~**Unicode 11 + grapheme width.**~~ Done (code) 2026-05-28 — `@xterm/addon-unicode11` loaded after CanvasAddon, `term.unicode.activeVersion = '11'`. Same pending-install caveat. (Skipped the separate `addon-unicode-graphemes` for now.) +- [x] ~~**Pane navigation key handler.**~~ Done (code) 2026-05-28 — Ctrl+Alt+Arrow / Ctrl+Alt+HJKL (spatial via `findNeighborInDirection`) + Alt+1..9 (Nth `walkLeaves` leaf). New `NavigateIntent` union in orchestration.tsx; XtermPane emits intent via new `onNavigate` prop → LeafPane → App `navigateTo` sets active leaf (reuses isActive→focusTrigger refocus). All chords share the one `attachCustomKeyEventHandler`. **Caveats:** Alt+1..9 swallows bare Alt+digit (breaks readline digit-arg / vim buffer-jump); Ctrl+Alt+Arrow may collide with Windows virtual-desktop switching — both noted in shortcuts.ts, v2 mitigation = opt-out toggle or Ctrl+Alt+Shift+Arrow. + +**Implementation note:** the three above were built in one fan-out workflow (parallel design on haiku/sonnet → single sonnet implementer applying to shared files), since all three touch `XtermPane`'s mount + its single `attachCustomKeyEventHandler` (xterm replaces the handler on each call, so they MUST coexist in one registration — don't add a second `attachCustomKeyEventHandler` anywhere). **Parked — circle back (saved, not yet prioritized):** From a6d3f8a9f9d3fb0e586246c3c3dc33c442dd3c78 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 21:57:32 +0100 Subject: [PATCH 08/35] memory: mark cursor fix + 3 xterm features verified on Windows Co-Authored-By: Claude Opus 4.8 (1M context) --- memory.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/memory.md b/memory.md index 523448e..e3dde1f 100644 --- a/memory.md +++ b/memory.md @@ -58,9 +58,11 @@ Four-agent research pass (terminal-landscape, AI-orchestration, xterm/Tauri ecos **→ Exploring first (user-selected 2026-05-28):** - [ ] **Per-session cost / token tracking.** Parse `~/.claude/projects//.jsonl` (`message.usage`: input/output/cache_read/cache_write + model per assistant line) → tokens + estimated $ per pane and per workspace. Easy parsing; the fiddly bit is mapping a tiletopia pane → its session file (capture session id / cwd at spawn). Difficulty: easy–medium. - [ ] **Smart link providers.** `terminal.registerLinkProvider()` to make file paths (`src/foo.ts:12:3`), `localhost:PORT`, and error locations clickable — more flexible than the regex-only web-links addon already loaded. Open file in editor / browser. Difficulty: medium. -- [x] ~~**Find in scrollback.**~~ Done (code) 2026-05-28, commit on `main` — `@xterm/addon-search` + new `src/components/SearchBar.tsx`/`.css` overlay, Ctrl+Shift+F open / Enter / Shift+Enter / Esc, regex + case toggles, decoration highlight. **Pending: `pnpm install` on Windows host + runtime verify** (addon not in WSL node_modules; tsc clean otherwise). -- [x] ~~**Unicode 11 + grapheme width.**~~ Done (code) 2026-05-28 — `@xterm/addon-unicode11` loaded after CanvasAddon, `term.unicode.activeVersion = '11'`. Same pending-install caveat. (Skipped the separate `addon-unicode-graphemes` for now.) -- [x] ~~**Pane navigation key handler.**~~ Done (code) 2026-05-28 — Ctrl+Alt+Arrow / Ctrl+Alt+HJKL (spatial via `findNeighborInDirection`) + Alt+1..9 (Nth `walkLeaves` leaf). New `NavigateIntent` union in orchestration.tsx; XtermPane emits intent via new `onNavigate` prop → LeafPane → App `navigateTo` sets active leaf (reuses isActive→focusTrigger refocus). All chords share the one `attachCustomKeyEventHandler`. **Caveats:** Alt+1..9 swallows bare Alt+digit (breaks readline digit-arg / vim buffer-jump); Ctrl+Alt+Arrow may collide with Windows virtual-desktop switching — both noted in shortcuts.ts, v2 mitigation = opt-out toggle or Ctrl+Alt+Shift+Arrow. +- [x] ~~**Find in scrollback.**~~ Done + **verified on Windows 2026-05-28** — `@xterm/addon-search` + new `src/components/SearchBar.tsx`/`.css` overlay, Ctrl+Shift+F open / Enter / Shift+Enter / Esc, regex + case toggles, decoration highlight. +- [x] ~~**Unicode 11 + grapheme width.**~~ Done + **verified on Windows 2026-05-28** — `@xterm/addon-unicode11` loaded after CanvasAddon, `term.unicode.activeVersion = '11'`. (Skipped the separate `addon-unicode-graphemes` for now.) +- [x] ~~**Pane navigation key handler.**~~ Done + **verified on Windows 2026-05-28** — Ctrl+Alt+Arrow / Ctrl+Alt+HJKL (spatial via `findNeighborInDirection`) + Alt+1..9 (Nth `walkLeaves` leaf). New `NavigateIntent` union in orchestration.tsx; XtermPane emits intent via new `onNavigate` prop → LeafPane → App `navigateTo` sets active leaf (reuses isActive→focusTrigger refocus). All chords share the one `attachCustomKeyEventHandler`. **Caveats:** Alt+1..9 swallows bare Alt+digit (breaks readline digit-arg / vim buffer-jump); Ctrl+Alt+Arrow may collide with Windows virtual-desktop switching — both noted in shortcuts.ts, v2 mitigation = opt-out toggle or Ctrl+Alt+Shift+Arrow. + +**Stuck/ghost cursor bug — FIXED + verified on Windows 2026-05-28.** The DOM renderer (xterm default) draws the cursor as a separate layered DOM element; under the Claude TUI's rapid cursor hide/show (`\x1b[?25l/h`) + `cursorBlink` it left a stale white block frozen at the old cursor position. Fix: load `@xterm/addon-canvas` in XtermPane after `term.open()` (composites the cursor into the text surface), wrapped in try/catch that falls back to the DOM renderer on init failure. Chose canvas over WebGL because tiletopia runs many panes and WebView2 caps live WebGL contexts at ~16. User confirmed the marker no longer sticks. **Implementation note:** the three above were built in one fan-out workflow (parallel design on haiku/sonnet → single sonnet implementer applying to shared files), since all three touch `XtermPane`'s mount + its single `attachCustomKeyEventHandler` (xterm replaces the handler on each call, so they MUST coexist in one registration — don't add a second `attachCustomKeyEventHandler` anywhere). From 1df8c3181bffb09d7da66841d78feaacdf653967 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 22:15:51 +0100 Subject: [PATCH 09/35] Add per-session claude token/cost usage panel (WSL, v1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reads ~/.claude/projects/*.jsonl transcripts from the open WSL panes' distros and shows per-session token counts + estimated USD cost, with a running total in the titlebar. Backend (src-tauri/src/usage.rs): new get_claude_usage command. For each distro it probes $HOME once via wsl.exe, reaches the transcripts over the \\wsl.localhost UNC share, and tallies message.usage per model per session (summed by each line's model, since a session can switch models). Results cached by (path,size,mtime) so polling only re-parses the file that grew; recency-capped (30d / 50 sessions) to bound scan cost. Windows-only; returns [] elsewhere. quiet_command made pub(crate). Frontend: src/lib/usage.ts holds the pricing table (per-MTok rates, matched by model-family substring) + cost/format helpers, so rates are editable without recompiling Rust. UsagePanel.tsx mirrors the MCP panel modal; rows whose transcript cwd matches an open pane are highlighted with a [pane: label] tag. App polls every 20s (visible windows) for the titlebar 💰 total and every 5s while the panel is open. Ctrl+Shift+U opens it; added to shortcuts.ts + regenerated README. tsc clean. Rust builds on the Windows host; needs runtime verification. Co-Authored-By: Claude Opus 4.8 (1M context) --- README.md | 14 +- src-tauri/src/lib.rs | 3 + src-tauri/src/pty.rs | 2 +- src-tauri/src/usage.rs | 278 ++++++++++++++++++++++++++++++++++ src/App.tsx | 80 ++++++++++ src/components/UsagePanel.css | 167 ++++++++++++++++++++ src/components/UsagePanel.tsx | 136 +++++++++++++++++ src/ipc.ts | 28 ++++ src/lib/shortcuts.ts | 10 ++ src/lib/usage.ts | 97 ++++++++++++ 10 files changed, 813 insertions(+), 2 deletions(-) create mode 100644 src-tauri/src/usage.rs create mode 100644 src/components/UsagePanel.css create mode 100644 src/components/UsagePanel.tsx create mode 100644 src/lib/usage.ts diff --git a/README.md b/README.md index 58eaa5a..aecdca1 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,10 @@ A Windows desktop app for running and arranging many WSL terminals at once. Buil | Key | Action | |---|---| | `Ctrl+K` | Open jump-to-pane palette | -| `Ctrl+Shift+← / → / ↑ / ↓` | Focus neighbour pane in that direction | +| `Ctrl+Shift+← / → / ↑ / ↓` | Focus neighbour pane in that direction (window-level — works even when no terminal is focused) | +| `Ctrl+Alt+← / → / ↑ / ↓` | Focus neighbour pane in that direction (from inside the terminal — intercepted before the PTY sees it) | +| `Ctrl+Alt+H / J / K / L` | Same as Ctrl+Alt+Arrow but in Vim-style HJKL order (left / down / up / right) | +| `Alt+1 … Alt+9` | Focus the Nth pane in layout order (DFS: left-to-right, top-to-bottom); clamped to pane count. Note: swallows bare Alt+digit — shells using readline digit-argument or vim buffer-jump may conflict. | **Broadcast** @@ -82,6 +85,15 @@ A Windows desktop app for running and arranging many WSL terminals at once. Buil | Key | Action | |---|---| | `Ctrl+Shift+C / Ctrl+Shift+V` | Copy selection / paste in terminal | +| `Ctrl+Shift+F` | Open find-in-scrollback bar for the focused pane | +| `Enter / Shift+Enter` | Next / previous match (while search bar is focused) | +| `Escape` | Close find bar and return focus to terminal | + +**Panels** + +| Key | Action | +|---|---| +| `Ctrl+Shift+U` | Open the usage panel — per-session claude token counts + estimated cost for the open WSL panes | **Help** diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 3a88bac..1e0aac9 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -6,6 +6,7 @@ mod hosts; mod mcp; mod mcp_policy; mod pty; +mod usage; mod window_state; use std::sync::Arc; @@ -66,6 +67,7 @@ pub fn run() { .manage(pending_actions) .manage(windows_state) .manage(pending_inits) + .manage(usage::UsageCache::default()) .on_window_event(move |window, event| { // When a non-main window closes, drop its workspaces from the // aggregator AND any unconsumed pending-init payload so neither @@ -108,6 +110,7 @@ pub fn run() { commands::mcp_policy_load, commands::mcp_policy_save, commands::mcp_hard_deny_labels, + usage::get_claude_usage, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/src-tauri/src/pty.rs b/src-tauri/src/pty.rs index c404fdf..d4d78e5 100644 --- a/src-tauri/src/pty.rs +++ b/src-tauri/src/pty.rs @@ -495,7 +495,7 @@ fn looks_like_password_prompt(buf: &[u8]) -> bool { // ---- distro enumeration ----------------------------------------------------- /// Run a process without flashing a console window on Windows. -fn quiet_command(program: &str) -> std::process::Command { +pub(crate) fn quiet_command(program: &str) -> std::process::Command { let mut c = std::process::Command::new(program); #[cfg(windows)] { diff --git a/src-tauri/src/usage.rs b/src-tauri/src/usage.rs new file mode 100644 index 0000000..e79ab02 --- /dev/null +++ b/src-tauri/src/usage.rs @@ -0,0 +1,278 @@ +//! Reads claude-code session transcripts and tallies token usage per session +//! for the usage panel. +//! +//! claude writes one JSONL transcript per session at +//! `~/.claude/projects//.jsonl`. Every assistant line +//! carries `cwd`, `sessionId`, `message.model`, and `message.usage` +//! (input/output/cache tokens). We read those straight out of the file, so the +//! reported cwd/model are accurate regardless of where the pane was spawned. +//! +//! Windows-only: the transcripts live inside each WSL distro, reached via the +//! `\\wsl.localhost\\…` 9p share. Returns empty on non-Windows. +//! +//! Cost is computed on the frontend (see src/lib/usage.ts) so the rate table is +//! easy to tweak; this module only returns raw per-model token tallies. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use parking_lot::Mutex; +use serde::Serialize; + +use crate::pty::quiet_command; + +/// Ignore sessions older than this, and cap the number returned — bounds the +/// scan cost on machines with a large transcript history. +const MAX_AGE_MS: i64 = 30 * 24 * 60 * 60 * 1000; +const MAX_SESSIONS: usize = 50; + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelUsage { + pub model: String, + pub input_tokens: u64, + pub output_tokens: u64, + pub cache_creation_tokens: u64, + pub cache_read_tokens: u64, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionUsage { + pub session_id: String, + pub cwd: String, + pub project_dir: String, + pub distro: String, + pub last_active_ms: i64, + pub models: Vec, +} + +/// Parsed-file cache entry, validated by (size, mtime) so we only re-parse the +/// one transcript that actually grew between polls. +struct CachedFile { + size: u64, + mtime_ms: i64, + cwd: String, + models: Vec, +} + +#[derive(Default)] +pub struct UsageCache { + files: Mutex>, + /// distro -> resolved `$HOME` (one wsl.exe probe per distro per process). + homes: Mutex>, +} + +/// Read + tally claude usage across the given WSL distros (the distinct distros +/// of currently-open WSL panes). Newest sessions first, capped to MAX_SESSIONS. +#[tauri::command] +pub async fn get_claude_usage( + distros: Vec, + cache: tauri::State<'_, UsageCache>, +) -> Result, String> { + if !cfg!(windows) { + return Ok(Vec::new()); + } + let cache = cache.inner(); + let mut out: Vec = Vec::new(); + let mut seen = HashSet::new(); + for distro in distros.into_iter().filter(|d| !d.is_empty() && seen.insert(d.clone())) { + match collect_distro(&distro, cache) { + Ok(mut v) => out.append(&mut v), + Err(e) => tracing::warn!("usage scan for distro {distro} failed: {e}"), + } + } + out.sort_by(|a, b| b.last_active_ms.cmp(&a.last_active_ms)); + out.truncate(MAX_SESSIONS); + Ok(out) +} + +fn collect_distro(distro: &str, cache: &UsageCache) -> Result, String> { + let home = resolve_home(distro, cache)?; + let projects = projects_dir(distro, &home) + .ok_or_else(|| format!("no ~/.claude/projects reachable for {distro}"))?; + + // Gather candidate transcripts (path, project-dir name, mtime), newest first. + let now = now_ms(); + let mut candidates: Vec<(PathBuf, String, i64)> = Vec::new(); + for proj in std::fs::read_dir(&projects).map_err(|e| e.to_string())?.flatten() { + let proj_path = proj.path(); + if !proj_path.is_dir() { + continue; + } + let proj_name = proj.file_name().to_string_lossy().into_owned(); + let inner = match std::fs::read_dir(&proj_path) { + Ok(it) => it, + Err(_) => continue, + }; + for f in inner.flatten() { + let p = f.path(); + if p.extension().and_then(|e| e.to_str()) != Some("jsonl") { + continue; + } + let mtime = std::fs::metadata(&p) + .ok() + .and_then(|m| m.modified().ok()) + .and_then(sys_to_ms) + .unwrap_or(0); + if now - mtime > MAX_AGE_MS { + continue; + } + candidates.push((p, proj_name.clone(), mtime)); + } + } + candidates.sort_by(|a, b| b.2.cmp(&a.2)); + candidates.truncate(MAX_SESSIONS); + + let mut out = Vec::new(); + for (path, proj_name, mtime) in candidates { + let (cwd, models) = match parse_or_cache(&path, cache) { + Ok(v) => v, + Err(e) => { + tracing::debug!("skip transcript {}: {e}", path.display()); + continue; + } + }; + let session_id = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + out.push(SessionUsage { + session_id, + cwd, + project_dir: proj_name, + distro: distro.to_string(), + last_active_ms: mtime, + models, + }); + } + Ok(out) +} + +/// Probe `$HOME` inside the distro once and cache it. `sh -c` (not a login +/// shell) so rc-file output can't contaminate stdout. +fn resolve_home(distro: &str, cache: &UsageCache) -> Result { + if let Some(h) = cache.homes.lock().get(distro) { + return Ok(h.clone()); + } + let out = quiet_command("wsl.exe") + .args(["-d", distro, "--", "sh", "-c", "printf %s \"$HOME\""]) + .output() + .map_err(|e| format!("wsl.exe $HOME probe: {e}"))?; + if !out.status.success() { + return Err(format!("wsl.exe $HOME probe exited {:?}", out.status.code())); + } + let home = String::from_utf8_lossy(&out.stdout).trim().to_string(); + if home.is_empty() { + return Err("empty $HOME".into()); + } + cache.homes.lock().insert(distro.to_string(), home.clone()); + Ok(home) +} + +/// `~/.claude/projects` as a Windows UNC path into the distro. Tries the newer +/// `\\wsl.localhost\` share first, then the legacy `\\wsl$\` alias. +fn projects_dir(distro: &str, home: &str) -> Option { + let home_rel = home.trim_start_matches('/'); + for prefix in [ + format!(r"\\wsl.localhost\{distro}"), + format!(r"\\wsl$\{distro}"), + ] { + let p = PathBuf::from(prefix) + .join(home_rel) + .join(".claude") + .join("projects"); + if p.is_dir() { + return Some(p); + } + } + None +} + +fn parse_or_cache(path: &Path, cache: &UsageCache) -> Result<(String, Vec), String> { + let meta = std::fs::metadata(path).map_err(|e| e.to_string())?; + let size = meta.len(); + let mtime = meta.modified().ok().and_then(sys_to_ms).unwrap_or(0); + if let Some(c) = cache.files.lock().get(path) { + if c.size == size && c.mtime_ms == mtime { + return Ok((c.cwd.clone(), c.models.clone())); + } + } + let (cwd, models) = parse_file(path)?; + cache.files.lock().insert( + path.to_path_buf(), + CachedFile { + size, + mtime_ms: mtime, + cwd: cwd.clone(), + models: models.clone(), + }, + ); + Ok((cwd, models)) +} + +fn parse_file(path: &Path) -> Result<(String, Vec), String> { + let content = std::fs::read_to_string(path).map_err(|e| e.to_string())?; + let mut cwd = String::new(); + let mut by_model: HashMap = HashMap::new(); + + for line in content.lines() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let v: serde_json::Value = match serde_json::from_str(line) { + Ok(v) => v, + Err(_) => continue, // tolerate a truncated final line / stray text + }; + if cwd.is_empty() { + if let Some(c) = v.get("cwd").and_then(|x| x.as_str()) { + cwd = c.to_string(); + } + } + if v.get("type").and_then(|x| x.as_str()) != Some("assistant") { + continue; + } + let msg = match v.get("message") { + Some(m) => m, + None => continue, + }; + let usage = match msg.get("usage") { + Some(u) => u, + None => continue, + }; + let model = msg + .get("model") + .and_then(|x| x.as_str()) + .unwrap_or("unknown") + .to_string(); + let tok = |k: &str| usage.get(k).and_then(|x| x.as_u64()).unwrap_or(0); + let entry = by_model.entry(model.clone()).or_insert_with(|| ModelUsage { + model, + input_tokens: 0, + output_tokens: 0, + cache_creation_tokens: 0, + cache_read_tokens: 0, + }); + entry.input_tokens += tok("input_tokens"); + entry.output_tokens += tok("output_tokens"); + entry.cache_creation_tokens += tok("cache_creation_input_tokens"); + entry.cache_read_tokens += tok("cache_read_input_tokens"); + } + + let mut models: Vec = by_model.into_values().collect(); + models.sort_by(|a, b| b.output_tokens.cmp(&a.output_tokens)); + Ok((cwd, models)) +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +fn sys_to_ms(t: SystemTime) -> Option { + t.duration_since(UNIX_EPOCH).ok().map(|d| d.as_millis() as i64) +} diff --git a/src/App.tsx b/src/App.tsx index ffceee2..c0a9858 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -23,8 +23,10 @@ import { createPaneWindow, takePendingWindowInit, pushWindowWorkspaces, + getClaudeUsage, type PaneId, type SpawnSpec, + type SessionUsage, type SshHost, type McpStatus, type McpMirror, @@ -106,6 +108,8 @@ import Palette from "./components/Palette"; import HostManager from "./components/HostManager"; import Help from "./components/Help"; import McpPanel from "./components/McpPanel"; +import UsagePanel from "./components/UsagePanel"; +import { totalCost, formatUsd } from "./lib/usage"; import McpConfirm, { type McpConfirmSpec } from "./components/McpConfirm"; import TabStrip from "./components/TabStrip"; import "./App.css"; @@ -239,6 +243,9 @@ export default function App() { token: null, }); const [mcpPanelOpen, setMcpPanelOpen] = useState(false); + const [usagePanelOpen, setUsagePanelOpen] = useState(false); + const [usageSessions, setUsageSessions] = useState([]); + const [usageLoading, setUsageLoading] = useState(false); const [ready, setReady] = useState(false); const [notifications, setNotifications] = useState([]); const [paletteOpen, setPaletteOpen] = useState(false); @@ -750,6 +757,53 @@ export default function App() { const openHostManager = useCallback(() => setHostManagerOpen(true), []); const closeHostManager = useCallback(() => setHostManagerOpen(false), []); + // ---- claude usage tracking ---------------------------------------------- + // Reads ~/.claude transcripts in the open WSL panes' distros (backend). The + // fetch guard collapses overlapping calls (the open panel polls every 5s and + // the background heartbeat every 20s both call this). + const usageFetchingRef = useRef(false); + const refreshUsage = useCallback(async () => { + if (usageFetchingRef.current) return; + const distros = new Set(); + for (const leaf of walkLeaves(treeRef.current)) { + if (leaf.shellKind === "wsl" && leaf.distro) distros.add(leaf.distro); + } + if (distros.size === 0) { + setUsageSessions([]); + return; + } + usageFetchingRef.current = true; + setUsageLoading(true); + try { + setUsageSessions(await getClaudeUsage(Array.from(distros))); + } catch (e) { + console.warn("getClaudeUsage failed:", e); + } finally { + usageFetchingRef.current = false; + setUsageLoading(false); + } + }, []); + + // Background heartbeat so the titlebar total stays roughly current without + // the panel open. Gated on visibility so a hidden/minimized window stays quiet. + useEffect(() => { + const tick = () => { + if (document.visibilityState === "visible") void refreshUsage(); + }; + tick(); + const id = window.setInterval(tick, 20000); + return () => clearInterval(id); + }, [refreshUsage]); + + // cwd + label of open WSL panes, for highlighting matching sessions. + const openPanes = useMemo( + () => + Array.from(walkLeaves(tree)) + .filter((l) => l.shellKind === "wsl") + .map((l) => ({ cwd: l.cwd ?? "", label: l.label ?? l.distro ?? "pane" })), + [tree], + ); + // Outside-click dismissal for the titlebar dropdowns. Mirrors the // per-pane shell-picker pattern in LeafPane.tsx. useEffect(() => { @@ -852,6 +906,14 @@ export default function App() { return; } + // Ctrl+Shift+U — usage panel + if (ctrl && shift && !alt && key === "u") { + e.preventDefault(); + e.stopPropagation(); + setUsagePanelOpen((v) => !v); + return; + } + // Ctrl+Shift+Alt+B — global broadcast all/none if (ctrl && shift && alt && key === "b") { e.preventDefault(); @@ -2085,6 +2147,14 @@ export default function App() { > 🤖 + + + + +
+ {sessions.length === 0 ? ( +

+ {loading + ? "Reading transcripts…" + : "No recent claude sessions found in the open panes' WSL distros."} +

+ ) : ( +
    + {sessions.map((s) => { + const paneLabel = paneByCwd.get(s.cwd); + const open = paneLabel !== undefined; + return ( +
  • + + {open ? "●" : "○"} + +
    +
    + + {projectName(s.cwd) || s.projectDir} + + {dominantModel(s)} + + {formatTokens(sessionTokens(s))} tok + + {formatUsd(sessionCost(s))} +
    +
    + + {s.cwd} + + {open && ( + [pane: {paneLabel}] + )} + {relativeTime(s.lastActiveMs, nowMs)} +
    +
    +
  • + ); + })} +
+ )} +
+ +
+ ● = open pane  ·  estimate (rates may drift)  ·  recent + sessions only +
+
+ + ); +} + +/** Last path segment of a cwd for a compact project label. */ +function projectName(cwd: string): string { + const parts = cwd.split("/").filter(Boolean); + return parts.length ? parts[parts.length - 1] : cwd; +} diff --git a/src/ipc.ts b/src/ipc.ts index 6660ed8..4600a5e 100644 --- a/src/ipc.ts +++ b/src/ipc.ts @@ -39,6 +39,34 @@ export interface SshHost { export const listDistros = (): Promise => invoke("list_distros"); +// ---- claude usage tracking ------------------------------------------------ + +/** Per-model token tally within one claude session. Mirrors Rust ModelUsage. */ +export interface ModelUsage { + model: string; + inputTokens: number; + outputTokens: number; + cacheCreationTokens: number; + cacheReadTokens: number; +} + +/** One claude session's usage, read from its transcript. Mirrors Rust + * SessionUsage. Cost is computed frontend-side (see src/lib/usage.ts). */ +export interface SessionUsage { + sessionId: string; + cwd: string; + projectDir: string; + distro: string; + lastActiveMs: number; + models: ModelUsage[]; +} + +/** Scan ~/.claude/projects in the given WSL distros (distinct distros of + * open WSL panes) and return recent sessions' token tallies. WSL/Windows + * only — returns [] otherwise. */ +export const getClaudeUsage = (distros: string[]): Promise => + invoke("get_claude_usage", { distros }); + export const spawnPane = (args: { spec: SpawnSpec; cols: number; diff --git a/src/lib/shortcuts.ts b/src/lib/shortcuts.ts index a72cddb..8e71108 100644 --- a/src/lib/shortcuts.ts +++ b/src/lib/shortcuts.ts @@ -130,6 +130,16 @@ export const SHORTCUT_SECTIONS: ShortcutSection[] = [ }, ], }, + { + title: "Panels", + items: [ + { + keys: "Ctrl+Shift+U", + description: + "Open the usage panel — per-session claude token counts + estimated cost for the open WSL panes", + }, + ], + }, { title: "Help", items: [{ keys: "F1", description: "Show this help overlay" }], diff --git a/src/lib/usage.ts b/src/lib/usage.ts new file mode 100644 index 0000000..a42ea27 --- /dev/null +++ b/src/lib/usage.ts @@ -0,0 +1,97 @@ +// Pricing + formatting helpers for the claude usage panel. Token tallies come +// from the backend (src-tauri/src/usage.rs); cost is applied here so the rate +// table is easy to edit without recompiling Rust. + +import type { SessionUsage } from "../ipc"; + +interface Rate { + /** USD per million tokens. */ + input: number; + output: number; + cacheWrite: number; + cacheRead: number; +} + +// Published Anthropic API rates, USD per million tokens, as of 2026-05. +// UPDATE if pricing changes. Matched against the model id by substring. +// cacheWrite uses the 5-minute-TTL rate (1.25× input); 1-hour cache writes +// (2× input) are billed slightly higher than this estimate shows. +const RATES: { match: string; rate: Rate }[] = [ + { match: "opus", rate: { input: 15, output: 75, cacheWrite: 18.75, cacheRead: 1.5 } }, + { match: "sonnet", rate: { input: 3, output: 15, cacheWrite: 3.75, cacheRead: 0.3 } }, + { match: "haiku", rate: { input: 1, output: 5, cacheWrite: 1.25, cacheRead: 0.1 } }, +]; +// Unknown model → assume sonnet-tier rates (a middle-ground estimate). +const FALLBACK_RATE = RATES[1].rate; + +function rateFor(model: string): Rate { + const m = model.toLowerCase(); + return RATES.find((r) => m.includes(r.match))?.rate ?? FALLBACK_RATE; +} + +/** Estimated USD cost for one session, summed per-model. */ +export function sessionCost(s: SessionUsage): number { + let usd = 0; + for (const mu of s.models) { + const r = rateFor(mu.model); + usd += + (mu.inputTokens * r.input + + mu.outputTokens * r.output + + mu.cacheCreationTokens * r.cacheWrite + + mu.cacheReadTokens * r.cacheRead) / + 1_000_000; + } + return usd; +} + +/** Total tokens (all kinds) for one session. */ +export function sessionTokens(s: SessionUsage): number { + let t = 0; + for (const mu of s.models) { + t += mu.inputTokens + mu.outputTokens + mu.cacheCreationTokens + mu.cacheReadTokens; + } + return t; +} + +/** Short family name of the model that produced the most output in a session. */ +export function dominantModel(s: SessionUsage): string { + let best: SessionUsage["models"][number] | undefined; + for (const mu of s.models) { + if (!best || mu.outputTokens > best.outputTokens) best = mu; + } + return best ? shortModel(best.model) : "—"; +} + +export function shortModel(model: string): string { + const m = model.toLowerCase(); + if (m.includes("opus")) return "opus"; + if (m.includes("sonnet")) return "sonnet"; + if (m.includes("haiku")) return "haiku"; + return model; +} + +export function totalCost(sessions: SessionUsage[]): number { + return sessions.reduce((acc, s) => acc + sessionCost(s), 0); +} + +export function formatUsd(n: number): string { + return "$" + n.toFixed(2); +} + +export function formatTokens(n: number): string { + if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + "M"; + if (n >= 1_000) return Math.round(n / 1_000) + "k"; + return String(n); +} + +/** `nowMs` is passed in so callers can avoid Date.now() churn in render. */ +export function relativeTime(ms: number, nowMs: number): string { + const dt = Math.max(0, nowMs - ms); + const s = Math.floor(dt / 1000); + if (s < 60) return `${s}s ago`; + const m = Math.floor(s / 60); + if (m < 60) return `${m}m ago`; + const h = Math.floor(m / 60); + if (h < 24) return `${h}h ago`; + return `${Math.floor(h / 24)}d ago`; +} From e30ac461afa4b4eb773195c1b72595741e868311 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 22:16:03 +0100 Subject: [PATCH 10/35] Commit pnpm-lock for the three new xterm addons Pins @xterm/addon-canvas 0.7.0, addon-search 0.15.0, addon-unicode11 0.8.0 (installed on the Windows host) so the deps are reproducible. Co-Authored-By: Claude Opus 4.8 (1M context) --- pnpm-lock.yaml | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3eb8b88..21bfa82 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,9 +17,18 @@ importers: '@tauri-apps/plugin-opener': specifier: ^2.0.0 version: 2.5.4 + '@xterm/addon-canvas': + specifier: ^0.7.0 + version: 0.7.0(@xterm/xterm@5.5.0) '@xterm/addon-fit': specifier: ^0.10.0 version: 0.10.0(@xterm/xterm@5.5.0) + '@xterm/addon-search': + specifier: ^0.15.0 + version: 0.15.0(@xterm/xterm@5.5.0) + '@xterm/addon-unicode11': + specifier: ^0.8.0 + version: 0.8.0(@xterm/xterm@5.5.0) '@xterm/addon-web-links': specifier: ^0.12.0 version: 0.12.0 @@ -584,11 +593,26 @@ packages: '@vitest/utils@2.1.9': resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==} + '@xterm/addon-canvas@0.7.0': + resolution: {integrity: sha512-LF5LYcfvefJuJ7QotNRdRSPc9YASAVDeoT5uyXS/nZshZXjYplGXRECBGiznwvhNL2I8bq1Lf5MzRwstsYQ2Iw==} + peerDependencies: + '@xterm/xterm': ^5.0.0 + '@xterm/addon-fit@0.10.0': resolution: {integrity: sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==} peerDependencies: '@xterm/xterm': ^5.0.0 + '@xterm/addon-search@0.15.0': + resolution: {integrity: sha512-ZBZKLQ+EuKE83CqCmSSz5y1tx+aNOCUaA7dm6emgOX+8J9H1FWXZyrKfzjwzV+V14TV3xToz1goIeRhXBS5qjg==} + peerDependencies: + '@xterm/xterm': ^5.0.0 + + '@xterm/addon-unicode11@0.8.0': + resolution: {integrity: sha512-LxinXu8SC4OmVa6FhgwsVCBZbr8WoSGzBl2+vqe8WcQ6hb1r6Gj9P99qTNdPiFPh4Ceiu2pC8xukZ6+2nnh49Q==} + peerDependencies: + '@xterm/xterm': ^5.0.0 + '@xterm/addon-web-links@0.12.0': resolution: {integrity: sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==} @@ -1286,10 +1310,22 @@ snapshots: loupe: 3.2.1 tinyrainbow: 1.2.0 + '@xterm/addon-canvas@0.7.0(@xterm/xterm@5.5.0)': + dependencies: + '@xterm/xterm': 5.5.0 + '@xterm/addon-fit@0.10.0(@xterm/xterm@5.5.0)': dependencies: '@xterm/xterm': 5.5.0 + '@xterm/addon-search@0.15.0(@xterm/xterm@5.5.0)': + dependencies: + '@xterm/xterm': 5.5.0 + + '@xterm/addon-unicode11@0.8.0(@xterm/xterm@5.5.0)': + dependencies: + '@xterm/xterm': 5.5.0 + '@xterm/addon-web-links@0.12.0': {} '@xterm/xterm@5.5.0': {} From e3c3810ba065a3cb950807799328aae5c7af4506 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 22:16:20 +0100 Subject: [PATCH 11/35] memory: log per-session token tracking (done, pending Windows verify) Co-Authored-By: Claude Opus 4.8 (1M context) --- memory.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/memory.md b/memory.md index e3dde1f..f5efa26 100644 --- a/memory.md +++ b/memory.md @@ -56,7 +56,7 @@ Durable memory for this project. Read at session start, update before session en Four-agent research pass (terminal-landscape, AI-orchestration, xterm/Tauri ecosystem, codebase gap-analysis) into things to add. **Headline finding:** tiletopia already owns the hard primitives (tiling, multi-window, broadcast, MCP control surface); the real gap vs Conductor/Crystal/claude-squad/Vibe-Kanban is *git-worktree isolation + per-session status/cost/diff visibility*. Full agent deliverables are in this session's conversation; condensed here. **→ Exploring first (user-selected 2026-05-28):** -- [ ] **Per-session cost / token tracking.** Parse `~/.claude/projects//.jsonl` (`message.usage`: input/output/cache_read/cache_write + model per assistant line) → tokens + estimated $ per pane and per workspace. Easy parsing; the fiddly bit is mapping a tiletopia pane → its session file (capture session id / cwd at spawn). Difficulty: easy–medium. +- [x] ~~**Per-session cost / token tracking.**~~ Done (code) 2026-05-28 — **WSL-only v1, pending Windows runtime verify.** Backend `src-tauri/src/usage.rs` (`get_claude_usage(distros)` command): probes `$HOME` per distro via `wsl.exe`, reads `~/.claude/projects/*/*.jsonl` over the `\\wsl.localhost\` UNC share, tallies `message.usage` **per model per assistant line** (sessions can switch models). Cached by `(path,size,mtime)`; recency-capped 30d/50 sessions. Frontend: `src/lib/usage.ts` holds the editable pricing table (per-MTok, matched by opus/sonnet/haiku substring) + cost/format helpers; `UsagePanel.tsx` (MCP-panel modal pattern) lists sessions, highlights those whose transcript `cwd` matches an open pane (`[pane: label]`); titlebar 💰 total chip; App polls 20s (visible) / 5s (panel open); **Ctrl+Shift+U** opens it. **Design choice:** session-list attribution (not 1:1 pane binding) — avoids the unsolvable "2 claudes in one cwd" ambiguity. **Caveats:** cost is an estimate (cache-creation priced at 5m rate; rates hardcoded, may drift); panes with no explicit cwd (`~`) won't highlight; PowerShell/SSH show nothing. Plan: `~/.claude/plans/greedy-cooking-flask.md`. - [ ] **Smart link providers.** `terminal.registerLinkProvider()` to make file paths (`src/foo.ts:12:3`), `localhost:PORT`, and error locations clickable — more flexible than the regex-only web-links addon already loaded. Open file in editor / browser. Difficulty: medium. - [x] ~~**Find in scrollback.**~~ Done + **verified on Windows 2026-05-28** — `@xterm/addon-search` + new `src/components/SearchBar.tsx`/`.css` overlay, Ctrl+Shift+F open / Enter / Shift+Enter / Esc, regex + case toggles, decoration highlight. - [x] ~~**Unicode 11 + grapheme width.**~~ Done + **verified on Windows 2026-05-28** — `@xterm/addon-unicode11` loaded after CanvasAddon, `term.unicode.activeVersion = '11'`. (Skipped the separate `addon-unicode-graphemes` for now.) From ebbf8db407171e29a37027c71273b8cc250defe1 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 22:26:15 +0100 Subject: [PATCH 12/35] Usage panel: scope to open panes, lead with tokens, label $ as API estimate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses feedback on the usage panel: - It was summing every recent session on the distro (all projects, mounted + home dirs), not the open panes' work — which read as inflated/double- counted. (Verified there's no literal double count: every transcript is read once and no two project dirs share a cwd, since claude resolves symlinks/mounts to the real path before mangling.) Now the panel + the titlebar chip default to sessions whose cwd matches an open pane, with an 'open panes / all recent' toggle to see the full per-distro list. - Token volume is now the headline figure; the API-cost estimate is shown as a clearly-labeled '~$' secondary, with a footer note that it's n/a on a Pro/Max subscription and can't reflect /usage quota. Kept visible (not hidden) so it can be validated against real API billing. Frontend-only; backend still returns the full recent set for the toggle. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/App.tsx | 9 +++++- src/components/UsagePanel.css | 29 ++++++++++++++++++- src/components/UsagePanel.tsx | 53 +++++++++++++++++++++++++++++------ 3 files changed, 80 insertions(+), 11 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index c0a9858..2299eea 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -804,6 +804,13 @@ export default function App() { [tree], ); + // Titlebar chip total — scoped to the open panes ("this workspace"), matching + // the usage panel's default view, so it isn't inflated by unrelated projects. + const workspaceUsageTotal = useMemo(() => { + const cwds = new Set(openPanes.map((p) => p.cwd).filter(Boolean)); + return totalCost(usageSessions.filter((s) => cwds.has(s.cwd))); + }, [openPanes, usageSessions]); + // Outside-click dismissal for the titlebar dropdowns. Mirrors the // per-pane shell-picker pattern in LeafPane.tsx. useEffect(() => { @@ -2153,7 +2160,7 @@ export default function App() { title="claude token usage & estimated cost (Ctrl+Shift+U)" aria-label="Usage" > - 💰{usageSessions.length > 0 ? ` ${formatUsd(totalCost(usageSessions))}` : ""} + 💰{workspaceUsageTotal > 0 ? ` ~${formatUsd(workspaceUsageTotal)}` : ""} + + {formatTokens(shown.reduce((a, s) => a + sessionTokens(s), 0))} tok + + {" · ~"} + {formatUsd(total)} + + + )}

) : (
    - {sessions.map((s) => { + {shown.map((s) => { const paneLabel = paneByCwd.get(s.cwd); const open = paneLabel !== undefined; return ( @@ -121,8 +156,8 @@ export default function UsagePanel({
- ● = open pane  ·  estimate (rates may drift)  ·  recent - sessions only + ● = open pane  ·  ~$ is an API-pricing estimate (n/a on Pro/Max; + can't reflect /usage quota)  ·  recent sessions only
From b23f3d1ecbd305873c4ebee6a54fdfa9f5afaf04 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 22:26:33 +0100 Subject: [PATCH 13/35] memory: log usage-panel scope/metric refinements + double-count investigation Co-Authored-By: Claude Opus 4.8 (1M context) --- memory.md | 1 + 1 file changed, 1 insertion(+) diff --git a/memory.md b/memory.md index f5efa26..92d7b3e 100644 --- a/memory.md +++ b/memory.md @@ -57,6 +57,7 @@ Four-agent research pass (terminal-landscape, AI-orchestration, xterm/Tauri ecos **→ Exploring first (user-selected 2026-05-28):** - [x] ~~**Per-session cost / token tracking.**~~ Done (code) 2026-05-28 — **WSL-only v1, pending Windows runtime verify.** Backend `src-tauri/src/usage.rs` (`get_claude_usage(distros)` command): probes `$HOME` per distro via `wsl.exe`, reads `~/.claude/projects/*/*.jsonl` over the `\\wsl.localhost\` UNC share, tallies `message.usage` **per model per assistant line** (sessions can switch models). Cached by `(path,size,mtime)`; recency-capped 30d/50 sessions. Frontend: `src/lib/usage.ts` holds the editable pricing table (per-MTok, matched by opus/sonnet/haiku substring) + cost/format helpers; `UsagePanel.tsx` (MCP-panel modal pattern) lists sessions, highlights those whose transcript `cwd` matches an open pane (`[pane: label]`); titlebar 💰 total chip; App polls 20s (visible) / 5s (panel open); **Ctrl+Shift+U** opens it. **Design choice:** session-list attribution (not 1:1 pane binding) — avoids the unsolvable "2 claudes in one cwd" ambiguity. **Caveats:** cost is an estimate (cache-creation priced at 5m rate; rates hardcoded, may drift); panes with no explicit cwd (`~`) won't highlight; PowerShell/SSH show nothing. Plan: `~/.claude/plans/greedy-cooking-flask.md`. + - **Refined same day after user feedback:** (1) **Scope** — panel + titlebar chip now default to sessions matching open panes ("this workspace"), with an "open panes / all recent" toggle. The first cut summed *every* recent session on the distro (all projects, `/mnt` + home), which read as inflated. **Investigated the "double counting mounted folders + projects" report: NOT a real double count** — every transcript file is read exactly once, and no two project dirs share a cwd because claude resolves symlinks/mounts to the real path before mangling the project-dir name (e.g. the `~/claude/projects/tiletopia → /mnt/d/dev/tiletopia` symlink yields only `-mnt-d-dev-tiletopia`). The inflation was purely the global scope. (2) **Metric framing** — user is on a Pro/Max subscription where $ is meaningless (and `/usage` rate-limit quota can't be derived from transcripts); **tokens are now the headline**, the API-cost estimate is a labeled secondary `~$` kept visible so the user can validate it against real API billing at work. **Open question:** accuracy of the $ estimate vs actual API billing — user will check at work. - [ ] **Smart link providers.** `terminal.registerLinkProvider()` to make file paths (`src/foo.ts:12:3`), `localhost:PORT`, and error locations clickable — more flexible than the regex-only web-links addon already loaded. Open file in editor / browser. Difficulty: medium. - [x] ~~**Find in scrollback.**~~ Done + **verified on Windows 2026-05-28** — `@xterm/addon-search` + new `src/components/SearchBar.tsx`/`.css` overlay, Ctrl+Shift+F open / Enter / Shift+Enter / Esc, regex + case toggles, decoration highlight. - [x] ~~**Unicode 11 + grapheme width.**~~ Done + **verified on Windows 2026-05-28** — `@xterm/addon-unicode11` loaded after CanvasAddon, `term.unicode.activeVersion = '11'`. (Skipped the separate `addon-unicode-graphemes` for now.) From d951c360ae8eaeaf796b03144f1dfdff75ea8a31 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 28 May 2026 22:43:06 +0100 Subject: [PATCH 14/35] Replace token-usage panel with per-pane context-fill indicator MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For a subscription user, lifetime token totals + a $ estimate aren't actionable; how full each session's context window is right now is. So: - Removed the UsagePanel, the titlebar 💰 chip, and Ctrl+Shift+U. - Repurposed the transcript reader (src-tauri/src/usage.rs): get_pane_context returns each recent session's CURRENT context occupancy = the last assistant turn's input + cache_read + cache_creation tokens (the prompt size), instead of lifetime sums. Same UNC/$HOME/cache/recency machinery. - src/lib/usage.ts now holds context helpers (window inference 200k vs 1M by whether occupancy already exceeds 200k, % , green→amber→red ramp, label). - App polls get_pane_context (15s, visibility-gated) into a cwd→context map exposed via orchestration; each LeafPane looks itself up by leaf.cwd and renders a slim fill bar + % in its header (hidden for non-claude/unmatched panes). Also fixes the narrow-pane toolbar: a ResizeObserver sets leaf--narrow / leaf--xnarrow width tiers; the label shrinks first, split buttons / status / secondary chips drop out by tier, and the close × + context indicator stay pinned right and visible down to the 180px min width. tsc clean (apart from the not-yet-installed xterm addons). Rust builds on the Windows host; needs runtime verification. Co-Authored-By: Claude Opus 4.8 (1M context) --- README.md | 6 - src-tauri/src/lib.rs | 2 +- src-tauri/src/usage.rs | 113 ++++++++---------- src/App.tsx | 98 +++++----------- src/components/UsagePanel.css | 194 ------------------------------- src/components/UsagePanel.tsx | 171 --------------------------- src/ipc.ts | 32 ++--- src/lib/layout/LeafPane.css | 56 +++++++++ src/lib/layout/LeafPane.tsx | 47 +++++++- src/lib/layout/orchestration.tsx | 6 +- src/lib/shortcuts.ts | 10 -- src/lib/usage.ts | 112 +++++------------- 12 files changed, 235 insertions(+), 612 deletions(-) delete mode 100644 src/components/UsagePanel.css delete mode 100644 src/components/UsagePanel.tsx diff --git a/README.md b/README.md index aecdca1..23ec0cb 100644 --- a/README.md +++ b/README.md @@ -89,12 +89,6 @@ A Windows desktop app for running and arranging many WSL terminals at once. Buil | `Enter / Shift+Enter` | Next / previous match (while search bar is focused) | | `Escape` | Close find bar and return focus to terminal | -**Panels** - -| Key | Action | -|---|---| -| `Ctrl+Shift+U` | Open the usage panel — per-session claude token counts + estimated cost for the open WSL panes | - **Help** | Key | Action | diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 1e0aac9..5279e1c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -110,7 +110,7 @@ pub fn run() { commands::mcp_policy_load, commands::mcp_policy_save, commands::mcp_hard_deny_labels, - usage::get_claude_usage, + usage::get_pane_context, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/src-tauri/src/usage.rs b/src-tauri/src/usage.rs index e79ab02..e718dc8 100644 --- a/src-tauri/src/usage.rs +++ b/src-tauri/src/usage.rs @@ -1,17 +1,15 @@ -//! Reads claude-code session transcripts and tallies token usage per session -//! for the usage panel. +//! Reads claude-code session transcripts to report each session's **current +//! context-window occupancy** for the per-pane context indicator. //! //! claude writes one JSONL transcript per session at //! `~/.claude/projects//.jsonl`. Every assistant line -//! carries `cwd`, `sessionId`, `message.model`, and `message.usage` -//! (input/output/cache tokens). We read those straight out of the file, so the -//! reported cwd/model are accurate regardless of where the pane was spawned. +//! carries `cwd`, `message.model`, and `message.usage`. The size of the prompt +//! sent on the most recent turn — `input_tokens + cache_read_input_tokens + +//! cache_creation_input_tokens` of the LAST assistant line — is a good proxy +//! for "how full is this session's context window right now". //! //! Windows-only: the transcripts live inside each WSL distro, reached via the //! `\\wsl.localhost\\…` 9p share. Returns empty on non-Windows. -//! -//! Cost is computed on the frontend (see src/lib/usage.ts) so the rate table is -//! easy to tweak; this module only returns raw per-model token tallies. use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; @@ -29,23 +27,15 @@ const MAX_SESSIONS: usize = 50; #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] -pub struct ModelUsage { - pub model: String, - pub input_tokens: u64, - pub output_tokens: u64, - pub cache_creation_tokens: u64, - pub cache_read_tokens: u64, -} - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionUsage { +pub struct SessionContext { pub session_id: String, pub cwd: String, - pub project_dir: String, pub distro: String, pub last_active_ms: i64, - pub models: Vec, + /// Prompt size of the last assistant turn (input + both cache buckets) — + /// the current context-window occupancy. + pub context_tokens: u64, + pub model: String, } /// Parsed-file cache entry, validated by (size, mtime) so we only re-parse the @@ -54,7 +44,8 @@ struct CachedFile { size: u64, mtime_ms: i64, cwd: String, - models: Vec, + context_tokens: u64, + model: String, } #[derive(Default)] @@ -64,23 +55,24 @@ pub struct UsageCache { homes: Mutex>, } -/// Read + tally claude usage across the given WSL distros (the distinct distros -/// of currently-open WSL panes). Newest sessions first, capped to MAX_SESSIONS. +/// Read each recent session's current context occupancy across the given WSL +/// distros (the distinct distros of currently-open WSL panes). Newest first, +/// capped to MAX_SESSIONS. #[tauri::command] -pub async fn get_claude_usage( +pub async fn get_pane_context( distros: Vec, cache: tauri::State<'_, UsageCache>, -) -> Result, String> { +) -> Result, String> { if !cfg!(windows) { return Ok(Vec::new()); } let cache = cache.inner(); - let mut out: Vec = Vec::new(); + let mut out: Vec = Vec::new(); let mut seen = HashSet::new(); for distro in distros.into_iter().filter(|d| !d.is_empty() && seen.insert(d.clone())) { match collect_distro(&distro, cache) { Ok(mut v) => out.append(&mut v), - Err(e) => tracing::warn!("usage scan for distro {distro} failed: {e}"), + Err(e) => tracing::warn!("context scan for distro {distro} failed: {e}"), } } out.sort_by(|a, b| b.last_active_ms.cmp(&a.last_active_ms)); @@ -88,20 +80,19 @@ pub async fn get_claude_usage( Ok(out) } -fn collect_distro(distro: &str, cache: &UsageCache) -> Result, String> { +fn collect_distro(distro: &str, cache: &UsageCache) -> Result, String> { let home = resolve_home(distro, cache)?; let projects = projects_dir(distro, &home) .ok_or_else(|| format!("no ~/.claude/projects reachable for {distro}"))?; - // Gather candidate transcripts (path, project-dir name, mtime), newest first. + // Gather candidate transcripts (path, mtime), newest first. let now = now_ms(); - let mut candidates: Vec<(PathBuf, String, i64)> = Vec::new(); + let mut candidates: Vec<(PathBuf, i64)> = Vec::new(); for proj in std::fs::read_dir(&projects).map_err(|e| e.to_string())?.flatten() { let proj_path = proj.path(); if !proj_path.is_dir() { continue; } - let proj_name = proj.file_name().to_string_lossy().into_owned(); let inner = match std::fs::read_dir(&proj_path) { Ok(it) => it, Err(_) => continue, @@ -119,15 +110,15 @@ fn collect_distro(distro: &str, cache: &UsageCache) -> Result, if now - mtime > MAX_AGE_MS { continue; } - candidates.push((p, proj_name.clone(), mtime)); + candidates.push((p, mtime)); } } - candidates.sort_by(|a, b| b.2.cmp(&a.2)); + candidates.sort_by(|a, b| b.1.cmp(&a.1)); candidates.truncate(MAX_SESSIONS); let mut out = Vec::new(); - for (path, proj_name, mtime) in candidates { - let (cwd, models) = match parse_or_cache(&path, cache) { + for (path, mtime) in candidates { + let (cwd, context_tokens, model) = match parse_or_cache(&path, cache) { Ok(v) => v, Err(e) => { tracing::debug!("skip transcript {}: {e}", path.display()); @@ -138,13 +129,13 @@ fn collect_distro(distro: &str, cache: &UsageCache) -> Result, .file_stem() .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_default(); - out.push(SessionUsage { + out.push(SessionContext { session_id, cwd, - project_dir: proj_name, distro: distro.to_string(), last_active_ms: mtime, - models, + context_tokens, + model, }); } Ok(out) @@ -190,32 +181,39 @@ fn projects_dir(distro: &str, home: &str) -> Option { None } -fn parse_or_cache(path: &Path, cache: &UsageCache) -> Result<(String, Vec), String> { +fn parse_or_cache( + path: &Path, + cache: &UsageCache, +) -> Result<(String, u64, String), String> { let meta = std::fs::metadata(path).map_err(|e| e.to_string())?; let size = meta.len(); let mtime = meta.modified().ok().and_then(sys_to_ms).unwrap_or(0); if let Some(c) = cache.files.lock().get(path) { if c.size == size && c.mtime_ms == mtime { - return Ok((c.cwd.clone(), c.models.clone())); + return Ok((c.cwd.clone(), c.context_tokens, c.model.clone())); } } - let (cwd, models) = parse_file(path)?; + let (cwd, context_tokens, model) = parse_file(path)?; cache.files.lock().insert( path.to_path_buf(), CachedFile { size, mtime_ms: mtime, cwd: cwd.clone(), - models: models.clone(), + context_tokens, + model: model.clone(), }, ); - Ok((cwd, models)) + Ok((cwd, context_tokens, model)) } -fn parse_file(path: &Path) -> Result<(String, Vec), String> { +/// Returns (cwd, context_tokens, model) where context_tokens is the prompt size +/// of the LAST assistant turn — the current context-window occupancy. +fn parse_file(path: &Path) -> Result<(String, u64, String), String> { let content = std::fs::read_to_string(path).map_err(|e| e.to_string())?; let mut cwd = String::new(); - let mut by_model: HashMap = HashMap::new(); + let mut context_tokens = 0u64; + let mut model = String::new(); for line in content.lines() { let line = line.trim(); @@ -242,28 +240,19 @@ fn parse_file(path: &Path) -> Result<(String, Vec), String> { Some(u) => u, None => continue, }; - let model = msg + let tok = |k: &str| usage.get(k).and_then(|x| x.as_u64()).unwrap_or(0); + // Overwrite each turn so we end up with the LAST assistant line's values. + context_tokens = tok("input_tokens") + + tok("cache_read_input_tokens") + + tok("cache_creation_input_tokens"); + model = msg .get("model") .and_then(|x| x.as_str()) .unwrap_or("unknown") .to_string(); - let tok = |k: &str| usage.get(k).and_then(|x| x.as_u64()).unwrap_or(0); - let entry = by_model.entry(model.clone()).or_insert_with(|| ModelUsage { - model, - input_tokens: 0, - output_tokens: 0, - cache_creation_tokens: 0, - cache_read_tokens: 0, - }); - entry.input_tokens += tok("input_tokens"); - entry.output_tokens += tok("output_tokens"); - entry.cache_creation_tokens += tok("cache_creation_input_tokens"); - entry.cache_read_tokens += tok("cache_read_input_tokens"); } - let mut models: Vec = by_model.into_values().collect(); - models.sort_by(|a, b| b.output_tokens.cmp(&a.output_tokens)); - Ok((cwd, models)) + Ok((cwd, context_tokens, model)) } fn now_ms() -> i64 { diff --git a/src/App.tsx b/src/App.tsx index 2299eea..8f214a6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -23,10 +23,10 @@ import { createPaneWindow, takePendingWindowInit, pushWindowWorkspaces, - getClaudeUsage, + getPaneContext, type PaneId, type SpawnSpec, - type SessionUsage, + type SessionContext, type SshHost, type McpStatus, type McpMirror, @@ -108,8 +108,6 @@ import Palette from "./components/Palette"; import HostManager from "./components/HostManager"; import Help from "./components/Help"; import McpPanel from "./components/McpPanel"; -import UsagePanel from "./components/UsagePanel"; -import { totalCost, formatUsd } from "./lib/usage"; import McpConfirm, { type McpConfirmSpec } from "./components/McpConfirm"; import TabStrip from "./components/TabStrip"; import "./App.css"; @@ -243,9 +241,7 @@ export default function App() { token: null, }); const [mcpPanelOpen, setMcpPanelOpen] = useState(false); - const [usagePanelOpen, setUsagePanelOpen] = useState(false); - const [usageSessions, setUsageSessions] = useState([]); - const [usageLoading, setUsageLoading] = useState(false); + const [contextSessions, setContextSessions] = useState([]); const [ready, setReady] = useState(false); const [notifications, setNotifications] = useState([]); const [paletteOpen, setPaletteOpen] = useState(false); @@ -757,59 +753,52 @@ export default function App() { const openHostManager = useCallback(() => setHostManagerOpen(true), []); const closeHostManager = useCallback(() => setHostManagerOpen(false), []); - // ---- claude usage tracking ---------------------------------------------- - // Reads ~/.claude transcripts in the open WSL panes' distros (backend). The - // fetch guard collapses overlapping calls (the open panel polls every 5s and - // the background heartbeat every 20s both call this). - const usageFetchingRef = useRef(false); - const refreshUsage = useCallback(async () => { - if (usageFetchingRef.current) return; + // ---- claude context tracking -------------------------------------------- + // Reads each recent session's current context occupancy from ~/.claude + // transcripts (backend), for the per-pane context-fill indicator. The fetch + // guard collapses overlapping ticks. + const contextFetchingRef = useRef(false); + const refreshContext = useCallback(async () => { + if (contextFetchingRef.current) return; const distros = new Set(); for (const leaf of walkLeaves(treeRef.current)) { if (leaf.shellKind === "wsl" && leaf.distro) distros.add(leaf.distro); } if (distros.size === 0) { - setUsageSessions([]); + setContextSessions([]); return; } - usageFetchingRef.current = true; - setUsageLoading(true); + contextFetchingRef.current = true; try { - setUsageSessions(await getClaudeUsage(Array.from(distros))); + setContextSessions(await getPaneContext(Array.from(distros))); } catch (e) { - console.warn("getClaudeUsage failed:", e); + console.warn("getPaneContext failed:", e); } finally { - usageFetchingRef.current = false; - setUsageLoading(false); + contextFetchingRef.current = false; } }, []); - // Background heartbeat so the titlebar total stays roughly current without - // the panel open. Gated on visibility so a hidden/minimized window stays quiet. + // Poll on a light interval, gated on visibility so a hidden/minimized window + // stays quiet. useEffect(() => { const tick = () => { - if (document.visibilityState === "visible") void refreshUsage(); + if (document.visibilityState === "visible") void refreshContext(); }; tick(); - const id = window.setInterval(tick, 20000); + const id = window.setInterval(tick, 15000); return () => clearInterval(id); - }, [refreshUsage]); + }, [refreshContext]); - // cwd + label of open WSL panes, for highlighting matching sessions. - const openPanes = useMemo( - () => - Array.from(walkLeaves(tree)) - .filter((l) => l.shellKind === "wsl") - .map((l) => ({ cwd: l.cwd ?? "", label: l.label ?? l.distro ?? "pane" })), - [tree], - ); - - // Titlebar chip total — scoped to the open panes ("this workspace"), matching - // the usage panel's default view, so it isn't inflated by unrelated projects. - const workspaceUsageTotal = useMemo(() => { - const cwds = new Set(openPanes.map((p) => p.cwd).filter(Boolean)); - return totalCost(usageSessions.filter((s) => cwds.has(s.cwd))); - }, [openPanes, usageSessions]); + // cwd -> newest session's context, consumed by each LeafPane via orchestration. + const paneContext = useMemo(() => { + const m = new Map(); + for (const s of contextSessions) { + if (!s.cwd) continue; + const prev = m.get(s.cwd); + if (!prev || s.lastActiveMs > prev.lastActiveMs) m.set(s.cwd, s); + } + return m; + }, [contextSessions]); // Outside-click dismissal for the titlebar dropdowns. Mirrors the // per-pane shell-picker pattern in LeafPane.tsx. @@ -913,13 +902,6 @@ export default function App() { return; } - // Ctrl+Shift+U — usage panel - if (ctrl && shift && !alt && key === "u") { - e.preventDefault(); - e.stopPropagation(); - setUsagePanelOpen((v) => !v); - return; - } // Ctrl+Shift+Alt+B — global broadcast all/none if (ctrl && shift && alt && key === "b") { @@ -1353,6 +1335,7 @@ export default function App() { reportLeafIdle, moveToNewWindow, getInitialPaneIdFor, + paneContext, }), [ activeLeafId, @@ -1378,6 +1361,7 @@ export default function App() { reportLeafIdle, moveToNewWindow, getInitialPaneIdFor, + paneContext, ], ); @@ -2154,14 +2138,6 @@ export default function App() { > 🤖 - - - {formatTokens(shown.reduce((a, s) => a + sessionTokens(s), 0))} tok - - {" · ~"} - {formatUsd(total)} - - - - - - -
- {shown.length === 0 ? ( -

- {loading - ? "Reading transcripts…" - : sessions.length > 0 && !showAll - ? "No open pane has a matching claude session yet." - : "No recent claude sessions found in the open panes' WSL distros."} - {sessions.length > 0 && !showAll && ( - <> - {" "} - - - )} -

- ) : ( -
    - {shown.map((s) => { - const paneLabel = paneByCwd.get(s.cwd); - const open = paneLabel !== undefined; - return ( -
  • - - {open ? "●" : "○"} - -
    -
    - - {projectName(s.cwd) || s.projectDir} - - {dominantModel(s)} - - {formatTokens(sessionTokens(s))} tok - - {formatUsd(sessionCost(s))} -
    -
    - - {s.cwd} - - {open && ( - [pane: {paneLabel}] - )} - {relativeTime(s.lastActiveMs, nowMs)} -
    -
    -
  • - ); - })} -
- )} -
- -
- ● = open pane  ·  ~$ is an API-pricing estimate (n/a on Pro/Max; - can't reflect /usage quota)  ·  recent sessions only -
- - - ); -} - -/** Last path segment of a cwd for a compact project label. */ -function projectName(cwd: string): string { - const parts = cwd.split("/").filter(Boolean); - return parts.length ? parts[parts.length - 1] : cwd; -} diff --git a/src/ipc.ts b/src/ipc.ts index 4600a5e..5eb0829 100644 --- a/src/ipc.ts +++ b/src/ipc.ts @@ -39,33 +39,25 @@ export interface SshHost { export const listDistros = (): Promise => invoke("list_distros"); -// ---- claude usage tracking ------------------------------------------------ +// ---- claude context tracking ---------------------------------------------- -/** Per-model token tally within one claude session. Mirrors Rust ModelUsage. */ -export interface ModelUsage { - model: string; - inputTokens: number; - outputTokens: number; - cacheCreationTokens: number; - cacheReadTokens: number; -} - -/** One claude session's usage, read from its transcript. Mirrors Rust - * SessionUsage. Cost is computed frontend-side (see src/lib/usage.ts). */ -export interface SessionUsage { +/** One claude session's current context-window occupancy, read from its + * transcript. Mirrors Rust SessionContext. `contextTokens` is the prompt + * size of the last assistant turn (input + both cache buckets). */ +export interface SessionContext { sessionId: string; cwd: string; - projectDir: string; distro: string; lastActiveMs: number; - models: ModelUsage[]; + contextTokens: number; + model: string; } -/** Scan ~/.claude/projects in the given WSL distros (distinct distros of - * open WSL panes) and return recent sessions' token tallies. WSL/Windows - * only — returns [] otherwise. */ -export const getClaudeUsage = (distros: string[]): Promise => - invoke("get_claude_usage", { distros }); +/** Scan ~/.claude/projects in the given WSL distros (distinct distros of open + * WSL panes) and return each recent session's current context occupancy. + * WSL/Windows only — returns [] otherwise. */ +export const getPaneContext = (distros: string[]): Promise => + invoke("get_pane_context", { distros }); export const spawnPane = (args: { spec: SpawnSpec; diff --git a/src/lib/layout/LeafPane.css b/src/lib/layout/LeafPane.css index 785e5f2..bccac05 100644 --- a/src/lib/layout/LeafPane.css +++ b/src/lib/layout/LeafPane.css @@ -84,6 +84,10 @@ overflow: hidden; text-overflow: ellipsis; max-width: 200px; + /* Give up width first when the pane is narrow, so the chips, context + indicator, and close button stay visible (overrides .pane-toolbar > *). */ + flex-shrink: 1; + min-width: 0; } .pane-label:hover { background: #222; @@ -242,6 +246,9 @@ .pane-status.idle { color: #d96060; } .pane-actions { + /* Final fallback right-anchor (non-claude pane has no .pane-ctx, and at + narrow tiers .pane-status is hidden) so the close button stays pinned right. */ + margin-left: auto; display: flex; gap: 2px; } @@ -264,6 +271,55 @@ background: #5a1a1a; color: #fcc; } + +/* ---- per-pane context-fill indicator ----------------------------------- */ +.pane-ctx { + /* Fallback right-anchor: when .pane-status is hidden (narrow tiers) its + margin-left:auto is gone, so carry it here too. First auto in DOM order + (status → ctx → actions) consumes the free space; the rest no-op. */ + margin-left: auto; + display: flex; + align-items: center; + gap: 5px; + font-size: 10px; + color: #9aa0a6; +} +.pane-ctx-bar { + width: 42px; + height: 6px; + background: #2a2a2a; + border-radius: 3px; + overflow: hidden; +} +.pane-ctx-fill { + display: block; + height: 100%; + border-radius: 3px; + transition: width 0.3s, background 0.3s; +} +.pane-ctx-pct { + font-variant-numeric: tabular-nums; + min-width: 26px; + text-align: right; +} + +/* ---- narrow-pane reflow ------------------------------------------------- + The close button + context indicator stay visible at every width; lower- + priority toolbar items drop out by tier so a 180px pane keeps its close ×. */ +.leaf--narrow .pane-status, +.leaf--narrow .pane-actions .pane-btn:not(.close) { + display: none; +} +.leaf--xnarrow .pane-status, +.leaf--xnarrow .pane-actions .pane-btn:not(.close), +.leaf--xnarrow .distro-wrap, +.leaf--xnarrow .bcast-chip { + display: none; +} +/* Keep just the % (drop the bar) at the tightest width. */ +.leaf--xnarrow .pane-ctx-bar { + display: none; +} .xterm-wrap { flex: 1 1 auto; min-height: 0; diff --git a/src/lib/layout/LeafPane.tsx b/src/lib/layout/LeafPane.tsx index cbd53af..a158396 100644 --- a/src/lib/layout/LeafPane.tsx +++ b/src/lib/layout/LeafPane.tsx @@ -10,6 +10,12 @@ import { import { createPortal } from "react-dom"; import { type LeafNode, resolveFontSize, type LeafShellSpec } from "./tree"; import { useOrchestration } from "./orchestration"; +import { + contextLabel, + contextPercent, + contextColor, + contextFraction, +} from "../../lib/usage"; import XtermPane from "../../components/XtermPane"; import type { SpawnSpec } from "../../ipc"; import "./LeafPane.css"; @@ -42,6 +48,7 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) { const [editingLabel, setEditingLabel] = useState(false); const [labelDraft, setLabelDraft] = useState(""); const labelInputRef = useRef(null); + const rootRef = useRef(null); const startEditLabel = useCallback( (e: MouseEvent) => { @@ -156,6 +163,22 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) { return () => orch.reportLeafIdle(leaf.id, false); }, [leaf.id, orch.reportLeafIdle]); + // ---- width tier --------------------------------------------------------- + // Drives which toolbar items collapse on a narrow pane (CSS does the hiding). + // The close button + context indicator stay visible at every tier; min pane + // width is 180px (MIN_PANE_PX), so "xnarrow" must keep those reachable. + const [widthTier, setWidthTier] = useState<"" | "narrow" | "xnarrow">(""); + useEffect(() => { + const el = rootRef.current; + if (!el) return; + const ro = new ResizeObserver(() => { + const w = el.clientWidth; + setWidthTier(w < 230 ? "xnarrow" : w < 320 ? "narrow" : ""); + }); + ro.observe(el); + return () => ro.disconnect(); + }, []); + // ---- broadcast --------------------------------------------------------- const onTerminalInput = useCallback( (b64: string) => { @@ -386,9 +409,13 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) { }; })(); + const ctx = + leaf.shellKind === "wsl" && leaf.cwd ? orch.paneContext.get(leaf.cwd) : undefined; + return (
{status} )} + {ctx && ( + + + + + {contextPercent(ctx)}% + + )} + + + + + {/* Target toggle: edit the global default or just the active pane. */} +
+ + +
+ +
+

+ {paneMode + ? "These colours override the global theme for the active pane only. Unset rows inherit the global default." + : "These colours apply to every pane that doesn't have its own override. Saved across restarts and shared with new windows."} +

+ + {/* Editable colour rows */} +
+ {FIELDS.map(({ key, label }) => { + const value = resolved[key]!; + const inherited = paneMode && !isSet(key); + return ( +
+ {label} + setField(key, e.target.value)} + aria-label={label} + /> + { + const v = e.target.value.trim(); + if (HEX_RE.test(v)) setField(key, v); + }} + /> + {paneMode && + (inherited ? ( + + inherited + + ) : ( + + ))} +
+ ); + })} +
+ + {/* Live preview */} + + + {/* Presets */} +
+ Presets +
+ {COLOR_PRESETS.map((p) => ( + + ))} +
+
+ +
+ +
+
+
+ + ); +} diff --git a/src/components/XtermPane.tsx b/src/components/XtermPane.tsx index a993c11..402b729 100644 --- a/src/components/XtermPane.tsx +++ b/src/components/XtermPane.tsx @@ -25,6 +25,11 @@ import { type SpawnSpec, } from "../ipc"; import type { NavigateIntent } from "../lib/layout/orchestration"; +import { + type PaneColors, + DEFAULT_PANE_COLORS, + toXtermTheme, +} from "../lib/theme"; // --------------------------------------------------------------------------- // base64 helpers (private to this module) @@ -76,6 +81,9 @@ interface XtermPaneProps { focusTrigger?: number; /** Absolute font size in px. Changes are applied live (fit + PTY resize). */ fontSize?: number; + /** Fully-resolved terminal colours (global theme merged with any per-pane + * override). Changes are applied live to the running terminal. */ + colors?: Required; /** Called when the user presses a tiling-WM navigation chord inside the * terminal. XtermPane only emits the intent; the parent (LeafPane/App) * resolves the target leaf from the current layout and sets it active. @@ -100,6 +108,7 @@ export default function XtermPane({ onFocus, focusTrigger = 0, fontSize, + colors, onNavigate, }: XtermPaneProps) { const containerRef = useRef(null); @@ -112,6 +121,9 @@ export default function XtermPane({ // up the initial value without re-running when it changes (the secondary // effect below handles dynamic updates). const initialFontSizeRef = useRef(fontSize); + // Same trick for the initial theme — the mount effect reads this once; the + // secondary effect below applies later changes live. + const initialColorsRef = useRef(colors); // Stable refs for callbacks so the mount effect doesn't need to re-run when // parents pass new inline functions, while still always calling the latest version. @@ -144,10 +156,12 @@ export default function XtermPane({ fontFamily: '"Cascadia Mono", "JetBrains Mono", "Consolas", monospace', fontSize: initialFontSizeRef.current ?? DEFAULT_XTERM_FONT_SIZE, cursorBlink: true, - theme: { - background: "#0c0c0c", - foreground: "#e6e6e6", - }, + // Theme is resolved by the parent (global default merged with any + // per-pane override) and applied live by the effect below. The fixed + // slice — softened white/brightWhite that tame the Claude TUI's + // emphasis slots so nothing hits glaring pure white — lives in + // toXtermTheme / BASE_XTERM_THEME (see lib/theme.ts). + theme: toXtermTheme(initialColorsRef.current ?? DEFAULT_PANE_COLORS), scrollback: 5000, convertEol: false, allowProposedApi: true, @@ -537,6 +551,27 @@ export default function XtermPane({ } }, [fontSize]); + // ------------------------------------------------------------------------- + // Live colour-theme changes (global theme edit, per-pane override, preset). + // + // Setting term.options.theme re-tints the renderer immediately; a refresh + // forces the canvas surface to repaint already-drawn cells with the new + // palette (xterm only re-tints on the next write otherwise). Cell geometry + // is unaffected, so no fit()/resize is needed — unlike the font-size path. + // ------------------------------------------------------------------------- + useEffect(() => { + const term = termRef.current; + if (!term || !colors) return; + try { + term.options.theme = toXtermTheme(colors); + term.refresh(0, term.rows - 1); + } catch (e) { + console.warn("theme apply failed", e); + } + // Depend on the individual fields rather than the object identity so a + // parent that rebuilds an equal colours object each render doesn't churn. + }, [colors?.background, colors?.foreground, colors?.cursor, colors?.selection]); + // Close the search bar and return focus to the xterm textarea so the user // can resume typing immediately. Queries the well-known xterm helper // textarea selector — the same pattern used in the focusTrigger effect. diff --git a/src/lib/layout/LeafPane.tsx b/src/lib/layout/LeafPane.tsx index e087694..35b1c7e 100644 --- a/src/lib/layout/LeafPane.tsx +++ b/src/lib/layout/LeafPane.tsx @@ -9,6 +9,7 @@ import { } from "react"; import { createPortal } from "react-dom"; import { type LeafNode, resolveFontSize, type LeafShellSpec } from "./tree"; +import { resolvePaneColors } from "../theme"; import { useOrchestration } from "./orchestration"; import XtermPane from "../../components/XtermPane"; import type { SpawnSpec } from "../../ipc"; @@ -547,6 +548,22 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) { 🤖 + + {isIdle && statusOk ? ( idle @@ -604,6 +621,7 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) { onNavigate={onPaneNavigate} focusTrigger={focusTrigger} fontSize={resolveFontSize(leaf.fontSizeOffset)} + colors={resolvePaneColors(orch.globalColors, leaf.colorOverride)} /> ) : (
diff --git a/src/lib/layout/orchestration.tsx b/src/lib/layout/orchestration.tsx index 46effad..10d90d5 100644 --- a/src/lib/layout/orchestration.tsx +++ b/src/lib/layout/orchestration.tsx @@ -1,6 +1,7 @@ import { createContext, useContext, type ReactNode } from "react"; import type { Orientation, NodeId, LeafShellSpec, Direction } from "./tree"; import type { PaneId, SshHost } from "../../ipc"; +import type { PaneColors } from "../theme"; /** * Orchestration context — every piece of shared state and every operation @@ -21,6 +22,10 @@ export interface Orchestration { /** Saved SSH hosts loaded from `hosts.json`. Reactive — changes when the * user edits hosts via {@link openHostManager}. */ hosts: SshHost[]; + /** App-wide default terminal colours. Reactive — edited via the colour + * panel. Each leaf resolves its effective theme from this plus its own + * {@link LeafNode.colorOverride}. */ + globalColors: PaneColors; // Tree mutations split: (leafId: NodeId, orientation: Orientation) => void; @@ -34,9 +39,15 @@ export interface Orchestration { /** Flip the per-pane mcpAllow flag. Default-deny; chip in the pane * toolbar drives this. */ toggleMcpAllow: (leafId: NodeId) => void; + /** Set or clear a leaf's per-pane colour override (undefined → fall back + * to the global theme). */ + setLeafColors: (leafId: NodeId, colors: PaneColors | undefined) => void; // SSH host management openHostManager: () => void; + /** Open the colour panel. When `leafId` is given the panel starts in + * per-pane mode targeting that leaf; otherwise it edits the global theme. */ + openColorPanel: (leafId?: NodeId) => void; // Per-pane orchestration setActive: (leafId: NodeId) => void; diff --git a/src/lib/layout/tree.test.ts b/src/lib/layout/tree.test.ts index 41f9d08..2d14c60 100644 --- a/src/lib/layout/tree.test.ts +++ b/src/lib/layout/tree.test.ts @@ -13,6 +13,7 @@ import { changeLabel, toggleBroadcast, toggleMcpAllow, + setLeafColors, adjustFontSize, adjustAllFontSizes, resolveFontSize, @@ -302,12 +303,13 @@ describe("setLeafShell", () => { expect(next.id).not.toBe(leaf.id); }); - it("preserves label / broadcast / fontSizeOffset across the shell change", () => { + it("preserves label / broadcast / fontSizeOffset / colorOverride across the shell change", () => { const leaf = newLeaf({ distro: "Ubuntu", label: "my pane", broadcast: true, fontSizeOffset: 2, + colorOverride: { background: "#101010" }, }); const next = setLeafShell(leaf, leaf.id, { shellKind: "powershell", @@ -315,6 +317,7 @@ describe("setLeafShell", () => { expect(next.label).toBe("my pane"); expect(next.broadcast).toBe(true); expect(next.fontSizeOffset).toBe(2); + expect(next.colorOverride).toEqual({ background: "#101010" }); }); }); @@ -389,6 +392,58 @@ describe("toggleMcpAllow", () => { }); }); +describe("setLeafColors", () => { + it("sets an override on a leaf with none", () => { + const leaf = newLeaf(); + expect(leaf.colorOverride).toBeUndefined(); + const next = setLeafColors(leaf, leaf.id, { + background: "#001122", + foreground: "#ddeeff", + }) as LeafNode; + expect(next.colorOverride).toEqual({ + background: "#001122", + foreground: "#ddeeff", + }); + }); + + it("replaces an existing override wholesale", () => { + const leaf = newLeaf({ colorOverride: { background: "#000000" } }); + const next = setLeafColors(leaf, leaf.id, { cursor: "#ff0000" }) as LeafNode; + expect(next.colorOverride).toEqual({ cursor: "#ff0000" }); + }); + + it("clears the override when passed undefined", () => { + const leaf = newLeaf({ colorOverride: { background: "#000000" } }); + const next = setLeafColors(leaf, leaf.id, undefined) as LeafNode; + expect(next.colorOverride).toBeUndefined(); + expect("colorOverride" in next).toBe(false); + }); + + it("clears the override when passed an all-undefined object", () => { + const leaf = newLeaf({ colorOverride: { background: "#000000" } }); + const next = setLeafColors(leaf, leaf.id, { + background: undefined, + foreground: undefined, + cursor: undefined, + selection: undefined, + }) as LeafNode; + expect(next.colorOverride).toBeUndefined(); + expect("colorOverride" in next).toBe(false); + }); + + it("returns the same reference when clearing an already-unset override", () => { + const leaf = newLeaf(); + const next = setLeafColors(leaf, leaf.id, undefined); + expect(next).toBe(leaf); + }); + + it("MUST NOT swap the leaf id (metadata-only, no PTY respawn)", () => { + const leaf = newLeaf(); + const next = setLeafColors(leaf, leaf.id, { background: "#123456" }) as LeafNode; + expect(next.id).toBe(leaf.id); + }); +}); + describe("resolveFontSize", () => { it("returns the default when offset is undefined or 0", () => { expect(resolveFontSize(undefined)).toBe(DEFAULT_FONT_SIZE); diff --git a/src/lib/layout/tree.ts b/src/lib/layout/tree.ts index 352dbec..e02904b 100644 --- a/src/lib/layout/tree.ts +++ b/src/lib/layout/tree.ts @@ -5,6 +5,8 @@ //! tmux / i3 / Zellij use — dragging a gutter mutates one parent ratio, //! both sibling subtrees reflow automatically. +import type { PaneColors } from "../theme"; + export type NodeId = string; /** 'h' = side-by-side (a on left, b on right). 'v' = stacked (a on top, b below). */ @@ -44,6 +46,13 @@ export interface LeafNode { * later doesn't require migrating saved workspaces. */ fontSizeOffset?: number; + /** + * Per-pane colour override. Any field set here wins over the app-wide + * global theme (see {@link resolvePaneColors}); unset fields fall through. + * Undefined / empty means "use the global theme". Metadata-only — changing + * it never respawns the PTY. + */ + colorOverride?: PaneColors; /** * If true, this pane is visible to the MCP server (Claude can list it, * read its scrollback, etc.). Default-DENY: when undefined or false, the @@ -111,6 +120,7 @@ export function setLeafShell( label: node.label, broadcast: node.broadcast, fontSizeOffset: node.fontSizeOffset, + colorOverride: node.colorOverride, }; if (spec.shellKind === "wsl") { if (spec.distro !== undefined) base.distro = spec.distro; @@ -294,6 +304,32 @@ export function toggleMcpAllow(root: TreeNode, leafId: NodeId): TreeNode { }); } +/** Set (or clear) a leaf's per-pane colour override. Pass `undefined` or an + * empty object to drop the override so the pane falls back to the global + * theme. Metadata-only — does NOT swap the id, so the PTY keeps running. */ +export function setLeafColors( + root: TreeNode, + leafId: NodeId, + colors: PaneColors | undefined, +): TreeNode { + return replaceById(root, leafId, (node) => { + if (node.kind !== "leaf") return node; + const empty = + !colors || + (colors.background === undefined && + colors.foreground === undefined && + colors.cursor === undefined && + colors.selection === undefined); + if (empty) { + if (node.colorOverride === undefined) return node; + const next: LeafNode = { ...node }; + delete next.colorOverride; + return next; + } + return { ...node, colorOverride: colors }; + }); +} + /** Compute the actual pixel font size from a leaf's offset, clamped to * [MIN_FONT_SIZE, MAX_FONT_SIZE]. */ export function resolveFontSize(offset: number | undefined): number { @@ -383,6 +419,7 @@ export function reshapeToPreset( if (src.label !== undefined) slot.label = src.label; if (src.broadcast !== undefined) slot.broadcast = src.broadcast; if (src.fontSizeOffset !== undefined) slot.fontSizeOffset = src.fontSizeOffset; + if (src.colorOverride !== undefined) slot.colorOverride = src.colorOverride; if (src.mcpAllow !== undefined) slot.mcpAllow = src.mcpAllow; } diff --git a/src/lib/theme.test.ts b/src/lib/theme.test.ts new file mode 100644 index 0000000..e17c1d5 --- /dev/null +++ b/src/lib/theme.test.ts @@ -0,0 +1,79 @@ +import { describe, it, expect } from "vitest"; +import { + resolvePaneColors, + toXtermTheme, + DEFAULT_PANE_COLORS, + COLOR_PRESETS, + type PaneColors, +} from "./theme"; + +describe("resolvePaneColors", () => { + it("falls back to defaults when nothing is set", () => { + expect(resolvePaneColors(undefined, undefined)).toEqual(DEFAULT_PANE_COLORS); + }); + + it("uses global values over defaults", () => { + const global: PaneColors = { background: "#111111", cursor: "#abcdef" }; + const r = resolvePaneColors(global, undefined); + expect(r.background).toBe("#111111"); + expect(r.cursor).toBe("#abcdef"); + // Unset fields still come from defaults. + expect(r.foreground).toBe(DEFAULT_PANE_COLORS.foreground); + expect(r.selection).toBe(DEFAULT_PANE_COLORS.selection); + }); + + it("per-pane override wins over global, field by field", () => { + const global: PaneColors = { background: "#111111", foreground: "#222222" }; + const override: PaneColors = { background: "#999999" }; + const r = resolvePaneColors(global, override); + expect(r.background).toBe("#999999"); // override wins + expect(r.foreground).toBe("#222222"); // inherits global + expect(r.cursor).toBe(DEFAULT_PANE_COLORS.cursor); // inherits default + }); + + it("always returns all four fields defined", () => { + const r = resolvePaneColors({}, {}); + expect(Object.keys(r).sort()).toEqual([ + "background", + "cursor", + "foreground", + "selection", + ]); + }); +}); + +describe("toXtermTheme", () => { + it("maps resolved colours onto the xterm ITheme shape", () => { + const theme = toXtermTheme({ + background: "#0c0c0c", + foreground: "#c5c8c6", + cursor: "#ffffff", + selection: "#3a3a3a", + }); + expect(theme.background).toBe("#0c0c0c"); + expect(theme.foreground).toBe("#c5c8c6"); + expect(theme.cursor).toBe("#ffffff"); + // selection maps to xterm 5.x's renamed property. + expect(theme.selectionBackground).toBe("#3a3a3a"); + // cursorAccent is pinned to the background for block-cursor legibility. + expect(theme.cursorAccent).toBe("#0c0c0c"); + }); + + it("keeps the fixed softened white/brightWhite slice", () => { + const theme = toXtermTheme(DEFAULT_PANE_COLORS); + expect(theme.white).toBe("#c5c8c6"); + expect(theme.brightWhite).toBe("#e0e0e0"); + }); +}); + +describe("COLOR_PRESETS", () => { + it("starts with the tiletopia default and every preset is fully specified", () => { + expect(COLOR_PRESETS[0].name).toBe("Tiletopia Dark"); + expect(COLOR_PRESETS[0].colors).toEqual(DEFAULT_PANE_COLORS); + for (const p of COLOR_PRESETS) { + for (const key of ["background", "foreground", "cursor", "selection"] as const) { + expect(p.colors[key]).toMatch(/^#[0-9a-fA-F]{6}$/); + } + } + }); +}); diff --git a/src/lib/theme.ts b/src/lib/theme.ts new file mode 100644 index 0000000..ca70c3d --- /dev/null +++ b/src/lib/theme.ts @@ -0,0 +1,160 @@ +//! Terminal colour theming. +//! +//! tiletopia ships one hard-coded dark palette historically baked into +//! XtermPane. This module turns that into a customisable model: +//! +//! - a GLOBAL default theme (persisted to localStorage, app-wide), and +//! - optional PER-PANE overrides (stored on the LeafNode, persisted with the +//! workspace tree). +//! +//! Only four colours are user-editable — background, foreground, cursor, and +//! selection — the ones that actually move the needle on readability. The +//! rest of xterm's ITheme (the 16-colour ANSI palette, etc.) stays fixed in +//! {@link BASE_XTERM_THEME}: notably `white`/`brightWhite` keep the softened +//! values that tame the Claude TUI's emphasis slots (see XtermPane history). + +import type { ITheme } from "@xterm/xterm"; + +/** The four user-editable colours. All optional: an undefined field on a + * per-pane override falls through to the global default; an undefined field + * on the global default falls through to {@link DEFAULT_PANE_COLORS}. */ +export interface PaneColors { + /** Terminal background. */ + background?: string; + /** Default text colour. */ + foreground?: string; + /** Cursor block colour. */ + cursor?: string; + /** Selection highlight background. */ + selection?: string; +} + +/** Fixed slice of the xterm theme that is NOT user-editable. The softened + * white/brightWhite values date back to the original hard-coded theme — they + * keep the Claude TUI's emphasis text from hitting glaring pure white. */ +const BASE_XTERM_THEME: ITheme = { + white: "#c5c8c6", + brightWhite: "#e0e0e0", +}; + +/** Ground-truth defaults — the historical tiletopia palette. Every editable + * field resolves to one of these when nothing overrides it. Also exposed as + * the first preset ("Tiletopia Dark"). */ +export const DEFAULT_PANE_COLORS: Required = { + background: "#0c0c0c", + foreground: "#c5c8c6", + cursor: "#ffffff", + selection: "#3a3a3a", +}; + +/** A named, ready-to-apply colour set shown as a one-click starting point in + * the colour panel. */ +export interface ColorPreset { + name: string; + colors: Required; +} + +/** Built-in presets. The first is the tiletopia default; the rest are + * well-known community palettes (background/foreground/cursor/selection + * only — the ANSI ramp is left to {@link BASE_XTERM_THEME}). */ +export const COLOR_PRESETS: ColorPreset[] = [ + { name: "Tiletopia Dark", colors: DEFAULT_PANE_COLORS }, + { + name: "Solarized Dark", + colors: { background: "#002b36", foreground: "#839496", cursor: "#93a1a1", selection: "#073642" }, + }, + { + name: "Gruvbox Dark", + colors: { background: "#282828", foreground: "#ebdbb2", cursor: "#ebdbb2", selection: "#504945" }, + }, + { + name: "Dracula", + colors: { background: "#282a36", foreground: "#f8f8f2", cursor: "#f8f8f2", selection: "#44475a" }, + }, + { + name: "Nord", + colors: { background: "#2e3440", foreground: "#d8dee9", cursor: "#d8dee9", selection: "#434c5e" }, + }, + { + name: "Light", + colors: { background: "#fafafa", foreground: "#1c1c1c", cursor: "#1c1c1c", selection: "#cfe0ff" }, + }, +]; + +/** Merge a per-pane override on top of the global default, then fill any + * still-missing field from {@link DEFAULT_PANE_COLORS}. The result always + * has all four fields defined. */ +export function resolvePaneColors( + global: PaneColors | undefined, + override: PaneColors | undefined, +): Required { + return { + background: + override?.background ?? global?.background ?? DEFAULT_PANE_COLORS.background, + foreground: + override?.foreground ?? global?.foreground ?? DEFAULT_PANE_COLORS.foreground, + cursor: override?.cursor ?? global?.cursor ?? DEFAULT_PANE_COLORS.cursor, + selection: + override?.selection ?? global?.selection ?? DEFAULT_PANE_COLORS.selection, + }; +} + +/** Build a full xterm ITheme from resolved colours. cursorAccent is pinned to + * the background so a block cursor's glyph stays readable. */ +export function toXtermTheme(colors: Required): ITheme { + return { + ...BASE_XTERM_THEME, + background: colors.background, + foreground: colors.foreground, + cursor: colors.cursor, + cursorAccent: colors.background, + selectionBackground: colors.selection, + }; +} + +// --------------------------------------------------------------------------- +// Global-default persistence (localStorage; frontend-only, no backend hop). +// localStorage is shared across all windows of the same origin, so a new +// window picks up the saved theme at startup, and the `storage` event lets +// open windows react live (see App's listener). +// --------------------------------------------------------------------------- + +export const GLOBAL_COLORS_STORAGE_KEY = "tiletopia.globalColors.v1"; + +/** #rgb / #rrggbb hex validator — what `` emits and what + * xterm accepts. We reject anything else so a corrupt localStorage value + * can't poison the theme. */ +const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/; + +function sanitizeColors(raw: unknown): PaneColors { + if (typeof raw !== "object" || raw === null) return {}; + const o = raw as Record; + const out: PaneColors = {}; + for (const key of ["background", "foreground", "cursor", "selection"] as const) { + const v = o[key]; + if (typeof v === "string" && HEX_RE.test(v)) out[key] = v; + } + return out; +} + +/** Read the saved global theme. Returns {} (→ all defaults) when absent or + * unparseable. */ +export function loadGlobalColors(): PaneColors { + try { + const raw = localStorage.getItem(GLOBAL_COLORS_STORAGE_KEY); + if (!raw) return {}; + return sanitizeColors(JSON.parse(raw)); + } catch { + return {}; + } +} + +/** Persist the global theme. Empty object is stored as-is (means "all + * defaults"), keeping the round-trip lossless. */ +export function saveGlobalColors(colors: PaneColors): void { + try { + localStorage.setItem(GLOBAL_COLORS_STORAGE_KEY, JSON.stringify(colors)); + } catch (e) { + console.warn("saveGlobalColors failed:", e); + } +} From ca97fb373312812a4d26b066661836babc6a8040 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Mon, 1 Jun 2026 23:49:19 +0100 Subject: [PATCH 32/35] Bump version to 0.4.1 Co-Authored-By: Claude Opus 4.8 (1M context) --- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 102c58e..e77cff9 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "tiletopia", "private": true, - "version": "0.4.0", + "version": "0.4.1", "type": "module", "scripts": { "dev": "vite", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 4f0de08..d7a99cd 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4221,7 +4221,7 @@ dependencies = [ [[package]] name = "tiletopia" -version = "0.4.0" +version = "0.4.1" dependencies = [ "anyhow", "axum", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index bf16fd0..f8c7e52 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tiletopia" -version = "0.4.0" +version = "0.4.1" description = "Tiling multi-terminal manager for WSL" authors = ["megaproxy"] edition = "2021" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index a57e25f..cb37dc1 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "tiletopia", - "version": "0.4.0", + "version": "0.4.1", "identifier": "com.megaproxy.tiletopia", "build": { "beforeDevCommand": "pnpm dev", From 8c6aded5d85d4d953cbd565b58a359fe68e7762b Mon Sep 17 00:00:00 2001 From: megaproxy Date: Mon, 1 Jun 2026 23:53:44 +0100 Subject: [PATCH 33/35] memory: customizable terminal colors session log (v0.4.1) Co-Authored-By: Claude Opus 4.8 (1M context) --- memory.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/memory.md b/memory.md index 3c0a70f..5a6f7a7 100644 --- a/memory.md +++ b/memory.md @@ -108,6 +108,22 @@ Four-agent research pass (terminal-landscape, AI-orchestration, xterm/Tauri ecos ## Session log +### 2026-06-01 — Customizable terminal colors (global theme + per-pane override), v0.4.1 + +**Feature:** user-editable terminal colors. Scope = **global default + per-pane override** (both, per the user's choice). Editable colors = **background / foreground / cursor / selection** only (NOT the full 16-color ANSI ramp — explicitly out of scope). UI = **modal + presets**. + +**New `src/lib/theme.ts`** is the model: `PaneColors` type (4 optional hex fields); `DEFAULT_PANE_COLORS` (the historical palette: bg `#0c0c0c`, fg `#c5c8c6`, cursor `#ffffff`, selection `#3a3a3a`); `COLOR_PRESETS` (Tiletopia Dark, Solarized Dark, Gruvbox Dark, Dracula, Nord, Light); `resolvePaneColors(global, override)` (override > global > default, field-by-field, always returns all 4); `toXtermTheme()` → xterm `ITheme` (maps `selection`→`selectionBackground` per xterm 5.5 rename, pins `cursorAccent`=background, and keeps the fixed softened `white #c5c8c6`/`brightWhite #e0e0e0` slice in `BASE_XTERM_THEME`); `loadGlobalColors`/`saveGlobalColors` (localStorage, hex-validated). + +**Persistence split — NO Rust changes needed.** Global default → **localStorage** (`tiletopia.globalColors.v1`), shared per-origin across windows, live cross-window sync via the `storage` event. Per-pane → new optional **`LeafNode.colorOverride`** riding in the workspace tree; the Rust backend stores the tree as opaque `serde_json::Value` (`window_state.rs`), so any new optional leaf field round-trips for free — confirmed before coding (same reason `fontSizeOffset`/`broadcast`/`mcpAllow` persist). `colorOverride` preserved across `setLeafShell` + `reshapeToPreset`; new metadata-only `setLeafColors` mutator (clears override when passed undefined/all-undefined). + +**Live apply:** `XtermPane` gained a `colors?: Required` prop; mount theme = `toXtermTheme(initialColorsRef ?? DEFAULT_PANE_COLORS)`; a new effect (keyed on the 4 fields, not object identity) sets `term.options.theme` + `term.refresh()` on change — mirrors the existing fontSize effect. No fit/resize (color doesn't change cell geometry). **This subsumed a pre-existing uncommitted softened-foreground tweak** (the old literal `theme:{background,foreground}` block) into theme.ts. + +**Wiring:** orchestration gained `globalColors`, `setLeafColors`, `openColorPanel(leafId?)`. New `ColorPanel.tsx`/`.css` modal (mirrors McpPanel style): **Global default / This pane** tab toggle, 4 color-picker+hex rows (per-row "↺ revert to global" in pane mode), live preview swatch, preset buttons, reset action. Titlebar **🎨** button → global mode; per-pane toolbar **🎨** chip (lights up when overridden) → that pane. + +**Tests:** added `setLeafColors` describe + extended `setLeafShell` preservation test in `tree.test.ts`; new `theme.test.ts` (resolve precedence, toXtermTheme mapping, preset shape). `vitest` **cannot run in WSL** — `node_modules` holds the Windows rollup native binary, not `@rollup/rollup-linux-x64-gnu`; do NOT install it from WSL (corrupts the Windows build tree). `tsc -b` passes (covers src + tests via tsconfig.app's `include:["src"]`). Run `pnpm test` on the Windows host. + +**Commits:** `7e624a3` (feature), `ca97fb3` (bump 0.4.0→**0.4.1** in package.json + tauri.conf.json + Cargo.toml + Cargo.lock). Pushed to origin/main. **Release not yet built** — next step is `pnpm tauri build` on Windows, then `scripts/release.sh v0.4.1` from WSL (script validates tag==package.json version, tags, builds .mcpb, uploads installer+.mcpb via `tea --login rdx4`). + ### 2026-05-30 — FIX: closing any window killed all windows (Tokio-runtime panic) **Symptom:** after dragging a pane out (or spawning) a daughter window, closing *either* the main or a daughter window closed them all, dumping `exit code 101`. From a72b2c3ff4d7591af108233a50c350bf697e0aca Mon Sep 17 00:00:00 2001 From: megaproxy Date: Tue, 2 Jun 2026 00:07:26 +0100 Subject: [PATCH 34/35] memory: note v0.4.1 release has wrong installer asset (0.4.0 .exe) + release.sh hardening TODO Co-Authored-By: Claude Opus 4.8 (1M context) --- memory.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/memory.md b/memory.md index 5a6f7a7..dedafa1 100644 --- a/memory.md +++ b/memory.md @@ -122,7 +122,14 @@ Four-agent research pass (terminal-landscape, AI-orchestration, xterm/Tauri ecos **Tests:** added `setLeafColors` describe + extended `setLeafShell` preservation test in `tree.test.ts`; new `theme.test.ts` (resolve precedence, toXtermTheme mapping, preset shape). `vitest` **cannot run in WSL** — `node_modules` holds the Windows rollup native binary, not `@rollup/rollup-linux-x64-gnu`; do NOT install it from WSL (corrupts the Windows build tree). `tsc -b` passes (covers src + tests via tsconfig.app's `include:["src"]`). Run `pnpm test` on the Windows host. -**Commits:** `7e624a3` (feature), `ca97fb3` (bump 0.4.0→**0.4.1** in package.json + tauri.conf.json + Cargo.toml + Cargo.lock). Pushed to origin/main. **Release not yet built** — next step is `pnpm tauri build` on Windows, then `scripts/release.sh v0.4.1` from WSL (script validates tag==package.json version, tags, builds .mcpb, uploads installer+.mcpb via `tea --login rdx4`). +**Commits:** `7e624a3` (feature), `ca97fb3` (bump 0.4.0→**0.4.1** in package.json + tauri.conf.json + Cargo.toml + Cargo.lock), `8c6aded` (this memory entry). Pushed to origin/main. Then released `v0.4.1` via `scripts/release.sh v0.4.1`. + +**⚠️ UNRESOLVED — wrong installer attached to the v0.4.1 release.** The git tag `v0.4.1` and the Forgejo release entry (title v0.4.1) are correct, but the attached `.exe` is **`tiletopia_0.4.0_x64-setup.exe`**, not 0.4.1. Cause: `release.sh` picks the newest `*-setup.exe` by **mtime** (`ls -1t | head -n1`); a stale 0.4.0 build (23:44) was newest when release.sh ran (23:51); the correct 0.4.1 build landed at 23:56, after publish. `tiletopia.mcpb` asset is fine. **Fix (needs running — was auto-denied as an outward-facing release-asset edit; user to authorize/run):** +``` +tea releases assets create --login rdx4 v0.4.1 src-tauri/target/release/bundle/nsis/tiletopia_0.4.1_x64-setup.exe +tea releases assets delete --login rdx4 --confirm v0.4.1 tiletopia_0.4.0_x64-setup.exe +``` +**TODO — harden `scripts/release.sh`** so this can't recur: select `tiletopia_${pkg_version}_x64-setup.exe` explicitly (fail if missing) instead of newest-by-mtime; optionally bail if no installer is newer than the bump commit. ### 2026-05-30 — FIX: closing any window killed all windows (Tokio-runtime panic) From 738fa2e901df0728df2bdccf886d5e8177e34d15 Mon Sep 17 00:00:00 2001 From: megaproxy Date: Thu, 11 Jun 2026 22:50:04 +0100 Subject: [PATCH 35/35] memory: log new claude-pane cursor-gap bug report + diagnosis plan --- memory.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/memory.md b/memory.md index dedafa1..cb38d7a 100644 --- a/memory.md +++ b/memory.md @@ -108,6 +108,16 @@ Four-agent research pass (terminal-landscape, AI-orchestration, xterm/Tauri ecos ## Session log +### 2026-06-11 — NEW user-reported cursor bug (diagnosis pending user A/B test) + +**Symptom:** typing in a pane, the cursor "gets stuck" / shows a gap between typed text and the cursor block; after a few seconds of not typing the gap "vanishes" (display snaps correct). User Q&A: only noticed **inside claude** (not confirmed at plain bash); **a few seconds** to self-correct; unknown whether visual-only or a real eaten character. Distinct from the 2026-05-28 stuck/ghost cursor (that was the DOM renderer leaving a stale block; fixed via canvas addon). + +**Leading hypothesis: Claude Code TUI input-render buffering, not tiletopia.** Claude's Ink TUI does render+stdin on one event loop; under load it buffers keystroke echo and flushes in a batch — cursor lags/gaps then catches up. Documented upstream: claude-code #58498 (input invisible/cursor frozen, dumps at once), #63504 (Windows host CPU pressure starves input loop), #29366, #2847. Running many parallel claudes (tiletopia's whole purpose) = exactly the CPU-contention trigger. + +**Decisive test (user to run):** same distro, run `claude` in Windows Terminal, type fast mid-session — if it reproduces there, it's claude upstream, not tiletopia. Also check whether it correlates with number of busy panes. + +**If tiletopia-implicated:** note `@xterm/addon-canvas` is now **deprecated upstream** (no fixes, removed in xterm v6; webgl is the recommended path — would need context-pool management given the ~16 WebGL context cap with many panes; xterm 5.5's DOM renderer is faster than when we abandoned it but would regress the 05-28 ghost-cursor fix). Renderer swap is the lever ONLY if the A/B test pins it on tiletopia. + ### 2026-06-01 — Customizable terminal colors (global theme + per-pane override), v0.4.1 **Feature:** user-editable terminal colors. Scope = **global default + per-pane override** (both, per the user's choice). Editable colors = **background / foreground / cursor / selection** only (NOT the full 16-color ANSI ramp — explicitly out of scope). UI = **modal + presets**.