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>
153 lines
5.7 KiB
Rust
153 lines
5.7 KiB
Rust
//! 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>>,
|
|
}
|