Phase 2: drag-/right-click-a-pane-to-new-window

Right-click any pane's title bar → "Move to new window" pops it into a
fresh tiletopia window with its PTY intact. Same Tauri process; the
PtyManager is shared, so the existing PaneId stays valid and Tauri 2's
process-wide event routing keeps pane://{id}/data flowing into the new
window's XtermPane.

Mechanism (Rust-side, plan-agent's main correction over my draft):
- pty.rs: PtyManager.transferring is a per-pane refcount; kill_pane
  becomes a no-op while it's >0. Source window's React unmount calls
  kill_pane → silently dropped while in flight; target window's
  claim_pane decrements after it has subscribed.
- window_state.rs: per-window workspaces snapshot map +
  debounced-by-tokio aggregate save. Each window pushes its tabs via
  push_window_workspaces; backend writes the merged
  { version: 2, workspaces: [...] } envelope. Non-main windows have
  their entries dropped on CloseRequested so closing a detached window
  discards its tabs (Chrome-style).
- commands: mark_pane_transferring, claim_pane, get_pane_ring (base64
  scrollback ring snapshot), create_pane_window, take_pending_window_init,
  push_window_workspaces.

Frontend:
- XtermPane gets `existingPaneId?: PaneId`: skip spawn, replay ring
  snapshot via term.write before attaching the live data listener,
  resize PTY to this window's grid, claim_pane. Scrollback replay was
  the plan agent's other ship-in-v1 call — without it a transferred
  Claude session looks blank until next prompt repaint.
- LeafPane: onContextMenu opens a fixed-positioned "Move to new
  window" popover. Esc / outside-click dismiss.
- orchestration adds moveToNewWindow + getInitialPaneIdFor; App owns a
  one-shot transferredPaneIdsRef cleared in registerPaneId.
- App mount branches on getCurrentWebviewWindow().label: main loads
  workspace.json as before; non-main calls take_pending_window_init
  and builds a singleton workspace around the adopted leaf.
- MCP mirror + onMcpRequest only run in main (paneIdByLeafRef is per-
  window; Claude sees the main window's current tab as the single
  workspace surface).

pnpm check (tsc -b) clean. 79/79 vitest pass. Rust side authored in
WSL; cargo build needs verification on Windows host before this is
runnable.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
megaproxy 2026-05-28 18:57:31 +01:00
parent 1a035ad0a6
commit 8ad51787fc
12 changed files with 797 additions and 48 deletions

View file

@ -3,7 +3,7 @@
use std::sync::Arc;
use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
use tauri::{AppHandle, Manager};
use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder};
use tokio::sync::RwLock;
use crate::creds;
@ -11,6 +11,7 @@ use crate::hosts::{self, SshHost, SshHostView};
use crate::mcp::{self, McpMirror, McpServerHandle, McpState, PendingActions, RunningServer};
use crate::mcp_policy::McpPolicy;
use crate::pty::{list_wsl_distros, PaneId, PtyManager, SpawnSpec};
use crate::window_state::{PendingInit, PendingInits, WindowsState};
const WORKSPACE_FILE: &str = "workspace.json";
@ -62,6 +63,165 @@ pub async fn kill_pane(
manager.kill(id).map_err(|e| e.to_string())
}
/// Bump the per-pane "do not kill during transfer" refcount. Called by the
/// source window just before removing the leaf from its tree (which triggers
/// React to unmount XtermPane, which calls `kill_pane`). The kill is then a
/// no-op until {@link claim_pane} drops the refcount.
#[tauri::command]
pub async fn mark_pane_transferring(
manager: tauri::State<'_, Arc<PtyManager>>,
id: PaneId,
) -> Result<(), String> {
manager.mark_transferring(id);
Ok(())
}
/// Drop the transfer refcount one. Called by the target window's XtermPane
/// mount once it has subscribed to the pane's events and replayed the
/// scrollback ring — at which point the PTY is safely "owned" by the
/// target.
#[tauri::command]
pub async fn claim_pane(
manager: tauri::State<'_, Arc<PtyManager>>,
id: PaneId,
) -> Result<(), String> {
manager.claim(id);
Ok(())
}
/// Return the per-pane scrollback ring snapshot as base64. The target
/// window's XtermPane writes it into xterm.js BEFORE attaching the live
/// pane://{id}/data listener, so the user sees recent output (covers
/// "Claude is in the middle of a thought" — a transferred pane that's
/// idle shouldn't look blank). Bounded by PANE_RING_CAPACITY (~256 KiB).
#[tauri::command]
pub async fn get_pane_ring(
manager: tauri::State<'_, Arc<PtyManager>>,
id: PaneId,
) -> Result<String, String> {
let ring = manager
.ring(id)
.ok_or_else(|| format!("no pane with id {id}"))?;
let (bytes, _seq) = ring.lock().snapshot();
Ok(B64.encode(&bytes))
}
/// Spawn a new app window and stash the pending-init payload keyed by the
/// new window's label. The target window pulls it via
/// {@link take_pending_window_init} during App mount.
///
/// Returns the new window's label so the caller can correlate.
#[tauri::command]
pub async fn create_pane_window(
app: AppHandle,
pendings: tauri::State<'_, Arc<PendingInits>>,
payload: PendingInit,
) -> Result<String, String> {
// Generate a label that's deterministic-but-unique. Tauri requires
// labels to be ASCII-alphanumeric + dashes/underscores.
let label = format!(
"pane-window-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_micros())
.unwrap_or(0)
);
// Stash BEFORE building the window — the target may finish bootstrapping
// and call take_pending_window_init before we return from build().
pendings.by_label.lock().insert(label.clone(), payload);
// Position the new window offset from the source's outer rect so it
// doesn't land exactly on top. If we can't query the source, fall back
// to the OS-default (center).
let (px, py, w, h) = source_window_geometry(&app);
let mut builder = WebviewWindowBuilder::new(
&app,
label.clone(),
WebviewUrl::App("index.html".into()),
)
.title("tiletopia")
.inner_size(w, h)
.min_inner_size(480.0, 320.0)
.resizable(true)
.decorations(true)
.visible(true);
if let (Some(x), Some(y)) = (px, py) {
builder = builder.position(x + 60.0, y + 60.0);
} else {
builder = builder.center();
}
if let Err(e) = builder.build() {
// Clean up our pending entry so we don't leak it.
pendings.by_label.lock().remove(&label);
return Err(format!("create webview window: {e}"));
}
Ok(label)
}
/// Read and remove the pending-init for the current window. Returns None
/// when there is no pending payload (main window startup; window opened
/// without a transfer; second call after the first consumed it).
#[tauri::command]
pub async fn take_pending_window_init(
pendings: tauri::State<'_, Arc<PendingInits>>,
label: String,
) -> Result<Option<PendingInit>, String> {
Ok(pendings.by_label.lock().remove(&label))
}
/// Push this window's workspaces snapshot to the backend aggregator. Called
/// every time the React state changes (debounced inside Rust); the next
/// debounce tick writes the aggregated envelope to disk.
///
/// `workspaces_json` is the per-window list as JSON (an array of
/// `{ id, name, tree }` objects — matches the frontend's envelope.workspaces
/// shape). Stored as serde Values so this module doesn't need to know
/// anything about the tree shape.
#[tauri::command]
pub async fn push_window_workspaces(
app: AppHandle,
state: tauri::State<'_, Arc<WindowsState>>,
label: String,
workspaces_json: String,
) -> Result<(), String> {
let parsed: serde_json::Value = serde_json::from_str(&workspaces_json)
.map_err(|e| format!("invalid workspaces JSON: {e}"))?;
let arr = parsed
.as_array()
.ok_or_else(|| "workspaces JSON must be an array".to_string())?;
let owned = arr.to_vec();
let state_arc: Arc<WindowsState> = (*state).clone();
state_arc.push(app, label, owned);
Ok(())
}
/// Best-effort: read outer position + inner size of the main window so the
/// new window opens nearby instead of slamming the OS default. Returns
/// (Some(x), Some(y), w, h) when available; falls back to a reasonable
/// default size when the main window query fails.
fn source_window_geometry(app: &AppHandle) -> (Option<f64>, Option<f64>, f64, f64) {
// Try the focused window first, then fall back to the main one.
let win = app
.webview_windows()
.into_iter()
.find_map(|(_, w)| if w.is_focused().unwrap_or(false) { Some(w) } else { None })
.or_else(|| app.get_webview_window("main"));
let Some(win) = win else {
return (None, None, 1100.0, 700.0);
};
let pos = win.outer_position().ok();
let size = win.inner_size().ok();
let scale = win.scale_factor().unwrap_or(1.0);
let w = size.as_ref().map(|s| s.width as f64 / scale).unwrap_or(1100.0);
let h = size.as_ref().map(|s| s.height as f64 / scale).unwrap_or(700.0);
let px = pos.as_ref().map(|p| p.x as f64 / scale);
let py = pos.as_ref().map(|p| p.y as f64 / scale);
(px, py, w, h)
}
/// Write the workspace JSON to `%APPDATA%\com.megaproxy.tiletopia\workspace.json`.
/// Writes to a `.tmp` and renames over the real file so a crash mid-write
/// can't leave a partial file readable.

View file

@ -6,11 +6,13 @@ mod hosts;
mod mcp;
mod mcp_policy;
mod pty;
mod window_state;
use std::sync::Arc;
use crate::mcp::{McpServerHandle, McpState, PendingActions};
use crate::pty::PtyManager;
use crate::window_state::{PendingInits, WindowsState, MAIN_WINDOW_LABEL};
pub fn run() {
let _ = tracing_subscriber::fmt()
@ -40,6 +42,15 @@ pub fn run() {
// Pending action registry — separate managed state so mcp_action_reply can
// grab it without needing to lock McpState or reach into TileService.
let pending_actions: Arc<PendingActions> = Arc::new(PendingActions::default());
// Cross-window workspace aggregator: every window pushes its tab list
// here; backend debounces + writes the merged envelope to workspace.json.
let windows_state: Arc<WindowsState> = Arc::new(WindowsState::default());
// Pane-transfer pending-init registry: source window stashes a payload
// keyed by the new window's label; target window pulls it during mount.
let pending_inits: Arc<PendingInits> = Arc::new(PendingInits::default());
let windows_state_for_event = Arc::clone(&windows_state);
let pending_inits_for_event = Arc::clone(&pending_inits);
tauri::Builder::default()
.plugin(tauri_plugin_clipboard_manager::init())
@ -48,12 +59,34 @@ pub fn run() {
.manage(mcp_state)
.manage(McpServerHandle::default())
.manage(pending_actions)
.manage(windows_state)
.manage(pending_inits)
.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
// resurrect on next launch. Matches Chrome-style "closing a
// detached window discards its tabs" intent.
if let tauri::WindowEvent::CloseRequested { .. } = event {
let label = window.label().to_string();
if label != MAIN_WINDOW_LABEL {
pending_inits_for_event.by_label.lock().remove(&label);
windows_state_for_event
.forget(window.app_handle().clone(), &label);
}
}
})
.invoke_handler(tauri::generate_handler![
commands::list_distros,
commands::spawn_pane,
commands::write_to_pane,
commands::resize_pane,
commands::kill_pane,
commands::mark_pane_transferring,
commands::claim_pane,
commands::get_pane_ring,
commands::create_pane_window,
commands::take_pending_window_init,
commands::push_window_workspaces,
commands::save_workspace,
commands::load_workspace,
commands::list_ssh_hosts,

View file

@ -109,6 +109,16 @@ struct PaneHandle {
pub struct PtyManager {
panes: Mutex<HashMap<PaneId, PaneHandle>>,
next_id: AtomicU64,
/// Per-pane "this PTY is mid-transfer between windows; do not kill it
/// even if some window's XtermPane unmounts" refcount. Incremented by
/// {@link mark_transferring} when a transfer begins; decremented by
/// {@link claim} when the target window finishes mounting. While >0,
/// {@link kill} is a no-op for that id.
///
/// Refcount (vs. plain flag) so concurrent transfers — or the rare
/// case where a transfer is retried before the previous one fully
/// releases — don't drop the suppression early.
transferring: Mutex<HashMap<PaneId, u32>>,
}
impl PtyManager {
@ -116,6 +126,27 @@ impl PtyManager {
Self {
panes: Mutex::new(HashMap::new()),
next_id: AtomicU64::new(1),
transferring: Mutex::new(HashMap::new()),
}
}
/// Bump the transferring refcount for a pane. While >0, {@link kill} is
/// a no-op so the source window's React unmount-cleanup can't tear
/// down the PTY mid-transfer.
pub fn mark_transferring(&self, id: PaneId) {
*self.transferring.lock().entry(id).or_insert(0) += 1;
}
/// Decrement the transferring refcount. When it reaches zero the entry
/// is removed and {@link kill} can act on this pane again.
pub fn claim(&self, id: PaneId) {
let mut map = self.transferring.lock();
if let Some(rc) = map.get_mut(&id) {
if *rc > 1 {
*rc -= 1;
} else {
map.remove(&id);
}
}
}
@ -258,6 +289,14 @@ impl PtyManager {
}
pub fn kill(&self, id: PaneId) -> Result<()> {
// If a transfer is in flight for this pane, suppress the kill so
// the source window's unmount-cleanup can't race the target
// window's mount-claim. The target's claim() will decrement the
// refcount; the next caller of kill() (if any) will actually kill.
if self.transferring.lock().contains_key(&id) {
tracing::debug!("pty kill suppressed during transfer for pane {id}");
return Ok(());
}
let mut panes = self.panes.lock();
if let Some(mut pane) = panes.remove(&id) {
// Best-effort: ask the child to die. Dropping `master` after this

View file

@ -0,0 +1,153 @@
//! Cross-window workspace state aggregator.
//!
//! Each window owns its own list of workspaces (tabs) in its React state.
//! When that list changes, the window calls `push_window_workspaces` to
//! ship a snapshot down here. This module merges every window's snapshot
//! into one envelope and persists it to `workspace.json` on a debounced
//! timer — same `{ version: 2, workspaces: [...] }` shape the frontend
//! reads at startup.
//!
//! The Rust side stays agnostic of the per-tree shape: workspaces are
//! stored as `serde_json::Value` so this module never needs to be updated
//! when LeafNode / SplitNode fields change.
//!
//! Lifetime of per-window entries:
//! - Created/updated on every `push_window_workspaces` call.
//! - The main window pushes initially after loading from disk; detached
//! windows push after takeing their pending-init payload.
//! - On detached-window close (handled in lib.rs), the entry is removed
//! so the next save doesn't resurrect tabs the user explicitly closed.
//! The main window's entry persists across the app lifetime.
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Context, Result};
use parking_lot::Mutex;
use serde_json::Value;
use tauri::{AppHandle, Manager};
use tokio::task::JoinHandle;
use tokio::time::{sleep, Duration};
const WORKSPACE_FILE: &str = "workspace.json";
const SAVE_DEBOUNCE: Duration = Duration::from_millis(500);
/// The label of the main (boot) window. Matches `tauri.conf.json`'s
/// `windows[0].label`. Used to decide whether a window-close should
/// retain or discard that window's tabs.
pub const MAIN_WINDOW_LABEL: &str = "main";
#[derive(Default)]
pub struct WindowsState {
per_window: Mutex<HashMap<String, Vec<Value>>>,
save_task: Mutex<Option<JoinHandle<()>>>,
}
impl WindowsState {
/// Replace this window's workspaces snapshot and schedule a debounced
/// save. Subsequent calls within the debounce window cancel the
/// previous save task — so a flurry of UI mutations only writes once.
pub fn push(
self: &Arc<Self>,
app: AppHandle,
label: String,
workspaces: Vec<Value>,
) {
self.per_window.lock().insert(label, workspaces);
self.schedule_save(app);
}
/// Drop a window's snapshot from the aggregate. Called on close of a
/// non-main window so its tabs don't reappear on next launch.
pub fn forget(self: &Arc<Self>, app: AppHandle, label: &str) {
let removed = self.per_window.lock().remove(label).is_some();
if removed {
self.schedule_save(app);
}
}
/// Build the on-disk envelope by concatenating every window's
/// workspaces in stable label order (main first when present, then
/// the rest sorted alphabetically by label — deterministic so the
/// file diff stays stable across no-op saves).
fn build_envelope(&self) -> Value {
let map = self.per_window.lock();
let mut keys: Vec<&String> = map.keys().collect();
keys.sort_by(|a, b| {
// main first, then alpha
match (a.as_str(), b.as_str()) {
(MAIN_WINDOW_LABEL, _) => std::cmp::Ordering::Less,
(_, MAIN_WINDOW_LABEL) => std::cmp::Ordering::Greater,
(x, y) => x.cmp(y),
}
});
let mut workspaces: Vec<Value> = Vec::new();
for k in keys {
if let Some(list) = map.get(k) {
for w in list {
workspaces.push(w.clone());
}
}
}
serde_json::json!({
"version": 2,
"workspaces": workspaces,
})
}
fn schedule_save(self: &Arc<Self>, app: AppHandle) {
let me = Arc::clone(self);
let mut slot = self.save_task.lock();
if let Some(prev) = slot.take() {
prev.abort();
}
let handle = tokio::spawn(async move {
sleep(SAVE_DEBOUNCE).await;
if let Err(e) = me.save_now(&app).await {
tracing::warn!("debounced workspace save failed: {e:#}");
}
});
*slot = Some(handle);
}
async fn save_now(&self, app: &AppHandle) -> Result<()> {
let envelope = self.build_envelope();
let json = serde_json::to_string(&envelope).context("serialize envelope")?;
let dir = app
.path()
.app_config_dir()
.map_err(|e| anyhow::anyhow!("app_config_dir: {e}"))?;
std::fs::create_dir_all(&dir).context("create_dir_all")?;
let path = dir.join(WORKSPACE_FILE);
let tmp = dir.join(format!("{WORKSPACE_FILE}.tmp"));
std::fs::write(&tmp, json.as_bytes()).context("write tmp")?;
std::fs::rename(&tmp, &path).context("rename tmp -> final")?;
Ok(())
}
}
// ---------------------------------------------------------------------------
// Pane-transfer pending-init registry
// ---------------------------------------------------------------------------
/// Payload the source window stashes in the backend before opening a new
/// window; the target window pulls it during App mount via
/// `take_pending_window_init`.
///
/// `leaf_json` and `workspace_name` are owned by the source — the backend
/// doesn't parse the leaf shape. `pane_id` is the existing PTY id the
/// target window's XtermPane should attach to (instead of spawning).
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct PendingInit {
#[serde(rename = "leafJson")]
pub leaf_json: String,
#[serde(rename = "paneId")]
pub pane_id: crate::pty::PaneId,
#[serde(rename = "workspaceName")]
pub workspace_name: String,
}
#[derive(Default)]
pub struct PendingInits {
pub by_label: Mutex<HashMap<String, PendingInit>>,
}