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

@ -18,6 +18,11 @@ import {
mcpPolicySave,
writeToPane,
killPane,
markPaneTransferring,
claimPane,
createPaneWindow,
takePendingWindowInit,
pushWindowWorkspaces,
type PaneId,
type SpawnSpec,
type SshHost,
@ -29,6 +34,14 @@ import {
type McpAuditEntry,
} from "./ipc";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
const MAIN_WINDOW_LABEL = "main";
/** Current window label, captured once at module load used to decide
* load path (load_workspace vs take_pending_window_init) and to push
* this window's state to the cross-window aggregator. */
const CURRENT_WINDOW_LABEL = getCurrentWebviewWindow().label;
const IS_MAIN_WINDOW = CURRENT_WINDOW_LABEL === MAIN_WINDOW_LABEL;
import {
type TreeNode,
type NodeId,
@ -83,7 +96,6 @@ import "./App.css";
import "./lib/layout/Gutter.css";
const LEGACY_STORAGE_KEY = "tiletopia.tree.v1";
const SAVE_DEBOUNCE_MS = 500;
/** Picker default for *new* panes. SSH never lives here SSH connections
* are always explicit, never a default. */
@ -220,6 +232,10 @@ export default function App() {
// ---- non-reactive lookups -----------------------------------------------
const paneIdByLeafRef = useRef<Map<NodeId, PaneId>>(new Map());
const nextNotifIdRef = useRef(1);
/** Leaves that just arrived via a window transfer, mapped to the
* existing PaneId their XtermPane should adopt. One-shot: cleared in
* registerPaneId once the pane registers. */
const transferredPaneIdsRef = useRef<Map<NodeId, PaneId>>(new Map());
const treeRef = useRef(tree);
useEffect(() => {
treeRef.current = tree;
@ -237,25 +253,62 @@ export default function App() {
useEffect(() => {
let cancelled = false;
(async () => {
let loadedEnvelope: ReturnType<typeof deserializeWorkspaces> = null;
try {
const json = await loadWorkspace();
if (json) loadedEnvelope = deserializeWorkspaces(json);
} catch (e) {
console.warn("loadWorkspace failed:", e);
}
if (!loadedEnvelope) {
// First: is this a detached window with a pending transfer payload?
// Non-main windows ALWAYS go through this path (they never read
// workspace.json — only main owns it). A detached window with no
// pending init is the dev-reload / edge case; we boot with a blank
// default workspace.
let initialEnvelope: ReturnType<typeof deserializeWorkspaces> = null;
let adoptedLeafId: NodeId | null = null;
if (!IS_MAIN_WINDOW) {
try {
const legacy = localStorage.getItem(LEGACY_STORAGE_KEY);
if (legacy) {
loadedEnvelope = deserializeWorkspaces(legacy);
if (loadedEnvelope) {
void saveWorkspace(serializeWorkspaces(loadedEnvelope));
const pending = await takePendingWindowInit(CURRENT_WINDOW_LABEL);
if (pending) {
try {
const adoptedLeaf = JSON.parse(pending.leafJson) as LeafNode;
if (adoptedLeaf && adoptedLeaf.kind === "leaf") {
transferredPaneIdsRef.current.set(adoptedLeaf.id, pending.paneId);
adoptedLeafId = adoptedLeaf.id;
initialEnvelope = {
version: 2,
workspaces: [
{
id: newId(),
name: pending.workspaceName || "Detached",
tree: adoptedLeaf,
},
],
};
}
} catch (e) {
console.warn("invalid pending leafJson:", e);
}
localStorage.removeItem(LEGACY_STORAGE_KEY);
}
} catch (e) {
console.warn("legacy localStorage migration failed:", e);
console.warn("takePendingWindowInit failed:", e);
}
} else {
// Main window: load workspace.json (and legacy fallback).
try {
const json = await loadWorkspace();
if (json) initialEnvelope = deserializeWorkspaces(json);
} catch (e) {
console.warn("loadWorkspace failed:", e);
}
if (!initialEnvelope) {
try {
const legacy = localStorage.getItem(LEGACY_STORAGE_KEY);
if (legacy) {
initialEnvelope = deserializeWorkspaces(legacy);
if (initialEnvelope) {
void saveWorkspace(serializeWorkspaces(initialEnvelope));
}
localStorage.removeItem(LEGACY_STORAGE_KEY);
}
} catch (e) {
console.warn("legacy localStorage migration failed:", e);
}
}
}
@ -283,7 +336,7 @@ export default function App() {
if (cancelled) return;
let envelope = loadedEnvelope;
let envelope = initialEnvelope;
if (!envelope) {
envelope = singletonEnvelope(
newLeaf(defaultShellAsLeafProps(initialDefault)),
@ -296,6 +349,13 @@ export default function App() {
}
setWorkspaces(envelope.workspaces);
setCurrentWorkspaceId(envelope.workspaces[0].id);
if (adoptedLeafId) {
setActiveLeafByWorkspace((prev) => {
const m = new Map(prev);
m.set(envelope!.workspaces[0].id, adoptedLeafId);
return m;
});
}
setDistros(resolvedDistros);
setHosts(resolvedHosts);
setDefaultShell(initialDefault);
@ -306,15 +366,16 @@ export default function App() {
};
}, []);
// ---- debounced save ------------------------------------------------------
// ---- workspace sync to backend aggregator -------------------------------
// Every window pushes its own workspaces snapshot; the backend merges
// across windows and debounces the actual workspace.json write (500ms
// tokio sleep inside Rust). This replaces the v0.3.0 per-window
// saveWorkspace path which would race when two windows wrote at once.
useEffect(() => {
if (!ready) return;
const id = window.setTimeout(() => {
saveWorkspace(
serializeWorkspaces({ version: 2, workspaces }),
).catch((e) => console.warn("saveWorkspace failed:", e));
}, SAVE_DEBOUNCE_MS);
return () => clearTimeout(id);
pushWindowWorkspaces(CURRENT_WINDOW_LABEL, JSON.stringify(workspaces)).catch(
(e) => console.warn("pushWindowWorkspaces failed:", e),
);
}, [workspaces, ready]);
// ---- focus polling → setActive (xterm.js eats pointerdown) --------------
@ -899,6 +960,9 @@ export default function App() {
return;
}
paneIdByLeafRef.current.set(leafId, paneId);
// One-shot: now that the pane has registered, the transferred-id
// hint is consumed.
transferredPaneIdsRef.current.delete(leafId);
const waiter = pendingPaneRegistrations.current.get(leafId);
if (waiter) {
pendingPaneRegistrations.current.delete(leafId);
@ -908,6 +972,71 @@ export default function App() {
[],
);
const getInitialPaneIdFor = useCallback(
(leafId: NodeId): PaneId | undefined =>
transferredPaneIdsRef.current.get(leafId),
[],
);
/** Pop the given leaf into a fresh top-level window. The source's
* XtermPane will unmount as the leaf leaves this window's tree;
* markPaneTransferring keeps the underlying PTY alive until the new
* window's XtermPane adopts it via existingPaneId. */
const moveToNewWindow = useCallback(
async (leafId: NodeId) => {
const leaf = findLeaf(treeRef.current, leafId);
if (!leaf || leaf.kind !== "leaf") {
notify("Cannot move — pane not found");
return;
}
const paneId = paneIdByLeafRef.current.get(leafId);
if (paneId == null) {
notify("Cannot move — PTY not ready yet");
return;
}
try {
await markPaneTransferring(paneId);
} catch (e) {
notify(`mark_pane_transferring failed: ${e}`);
return;
}
// Snapshot the leaf BEFORE removing — closeLeaf may produce a tree
// where this leaf is no longer present, breaking findLeaf later.
const leafJson = JSON.stringify(leaf);
const workspaceName = leaf.label ?? `Pane ${paneId}`;
// Remove from current tree (sibling promotes naturally via closeLeaf).
// If this leaf was the entire tree, fall back to a fresh default so
// the source workspace never becomes empty (matches close behavior).
setTree(
(t) =>
closeLeaf(t, leafId) ?? newLeaf(defaultShellAsLeafProps(defaultShell)),
);
paneIdByLeafRef.current.delete(leafId);
setActiveLeafByWorkspace((prev) => {
const wsId = currentWorkspaceIdRef.current;
if (!wsId) return prev;
if (prev.get(wsId) !== leafId) return prev;
const m = new Map(prev);
m.set(wsId, null);
return m;
});
try {
await createPaneWindow({ leafJson, paneId, workspaceName });
} catch (e) {
notify(`Failed to open new window: ${e}`);
// The leaf is already gone from our tree and the PTY is orphaned
// in transferring state. Drop the refcount so a manual kill could
// eventually succeed; but the leaf no longer exists in any tree.
void claimPane(paneId).catch(() => {});
}
},
[defaultShell, notify],
);
/** Insert a new leaf into the tree from a SpawnSpec used by the MCP
* spawn_pane and connect_host handlers. Returns the new leaf's id
* (caller awaits waitForPaneRegistration on it for the paneId).
@ -1097,6 +1226,8 @@ export default function App() {
setHeaderDragOver,
endHeaderDrag,
reportLeafIdle,
moveToNewWindow,
getInitialPaneIdFor,
}),
[
activeLeafId,
@ -1119,6 +1250,8 @@ export default function App() {
setHeaderDragOver,
endHeaderDrag,
reportLeafIdle,
moveToNewWindow,
getInitialPaneIdFor,
],
);
@ -1126,11 +1259,18 @@ export default function App() {
// Whenever the tree, hosts, or active selection change AND the MCP server
// is running, push a fresh mirror down to the backend. Per-leaf mcpAllow
// gates whether each leaf appears in the mirror (default-deny).
//
// Multi-window scoping: only the MAIN window pushes the mirror. Detached
// windows have their own current-workspace tree but Claude sees ONE
// workspace surface — main's current tab. Otherwise two windows would
// overwrite each other's mirrors on every keystroke and Claude's view
// would flap unpredictably.
const allowedPaneCount = useMemo(
() => Array.from(walkLeaves(tree)).filter((l) => l.mcpAllow).length,
[tree],
);
useEffect(() => {
if (!IS_MAIN_WINDOW) return;
if (!mcpStatus.running) return;
const leaves: Record<string, McpMirroredLeaf> = {};
for (const leaf of walkLeaves(tree)) {
@ -1590,6 +1730,10 @@ export default function App() {
);
useEffect(() => {
// Only the main window handles MCP requests — paneIdByLeafRef is
// per-window so a request targeting a leaf in another window would
// fail anyway. Keeps responsibility clean: MCP sees main, period.
if (!IS_MAIN_WINDOW) return;
let cancelled = false;
let unlisten: (() => void) | undefined;
void onMcpRequest(async (req: McpActionRequest) => {

View file

@ -15,6 +15,8 @@ import {
killPane,
onPaneData,
onPaneExit,
getPaneRing,
claimPane,
type PaneId,
type SpawnSpec,
} from "../ipc";
@ -50,6 +52,12 @@ interface XtermPaneProps {
* changing it later does NOT respawn callers force a respawn by
* changing the React `key` (see Pane.svelte / LeafPane). */
spec: SpawnSpec;
/** Attach to an existing PTY (transferred from another window) instead of
* spawning a new one. When set: spec is ignored at the spawn step, the
* scrollback ring is replayed into xterm.js, the live data listener is
* attached, and the transfer refcount is claimed (decremented) so the
* source window's killPane is no longer suppressed. */
existingPaneId?: PaneId;
onStatus?: (msg: string, ok: boolean) => void;
/** Fired once when the backend PTY is alive and we have its PaneId. */
onSpawn?: (paneId: PaneId) => void;
@ -73,6 +81,7 @@ const DEFAULT_XTERM_FONT_SIZE = 13;
export default function XtermPane({
spec,
existingPaneId,
onStatus,
onSpawn,
onInput,
@ -153,33 +162,78 @@ export default function XtermPane({
const cols = term!.cols;
const rows = term!.rows;
try {
paneId = await spawnPane({ spec, cols, rows });
if (destroyed) {
void killPane(paneId);
if (existingPaneId != null) {
// Adoption path: a window-transfer landed us here with an existing
// PTY id. Don't spawn — replay the scrollback ring first (so the
// user sees recent output like a thinking Claude session), then
// attach the live listener, resize the PTY to this window's grid,
// and release the transfer-refcount.
paneId = existingPaneId;
paneIdRef.current = paneId;
onStatusRef.current?.(`pane ${paneId} adopted`, true);
onSpawnRef.current?.(paneId);
try {
const ringB64 = await getPaneRing(paneId);
if (destroyed) return;
if (ringB64) {
term?.write(b64ToBytes(ringB64));
}
} catch (e) {
console.warn("getPaneRing failed:", e);
}
if (destroyed) return;
unlistenData = await onPaneData(paneId, (b64) => {
term?.write(b64ToBytes(b64));
onDataReceivedRef.current?.();
});
if (destroyed) return;
unlistenExit = await onPaneExit(paneId, () => {
term?.write("\r\n\x1b[33m[pane exited]\x1b[0m\r\n");
onStatusRef.current?.(`pane ${paneId} exited`, false);
});
// Match the PTY to our cell grid (the source window may have had
// different dimensions).
try {
await resizePane(paneId, cols, rows);
} catch (e) {
console.warn("resizePane on adopt failed:", e);
}
// Release the transfer refcount so future killPane calls on this
// id are no longer suppressed.
try {
await claimPane(paneId);
} catch (e) {
console.warn("claimPane failed:", e);
}
} else {
try {
paneId = await spawnPane({ spec, cols, rows });
if (destroyed) {
void killPane(paneId);
return;
}
paneIdRef.current = paneId;
onStatusRef.current?.(`pane ${paneId} alive`, true);
onSpawnRef.current?.(paneId);
} catch (e) {
if (destroyed) return;
const msg = `spawn_pane failed: ${e}`;
term?.write(`\r\n\x1b[31m${msg}\x1b[0m\r\n`);
onStatusRef.current?.(msg, false);
return;
}
paneIdRef.current = paneId;
onStatusRef.current?.(`pane ${paneId} alive`, true);
onSpawnRef.current?.(paneId);
} catch (e) {
if (destroyed) return;
const msg = `spawn_pane failed: ${e}`;
term?.write(`\r\n\x1b[31m${msg}\x1b[0m\r\n`);
onStatusRef.current?.(msg, false);
return;
unlistenData = await onPaneData(paneId, (b64) => {
term?.write(b64ToBytes(b64));
onDataReceivedRef.current?.();
});
unlistenExit = await onPaneExit(paneId, () => {
term?.write("\r\n\x1b[33m[pane exited]\x1b[0m\r\n");
onStatusRef.current?.(`pane ${paneId} exited`, false);
});
}
unlistenData = await onPaneData(paneId, (b64) => {
term?.write(b64ToBytes(b64));
onDataReceivedRef.current?.();
});
unlistenExit = await onPaneExit(paneId, () => {
term?.write("\r\n\x1b[33m[pane exited]\x1b[0m\r\n");
onStatusRef.current?.(`pane ${paneId} exited`, false);
});
term?.onData((data) => {
if (paneId == null) return;
const b64 = stringToB64(data);

View file

@ -53,6 +53,53 @@ export const resizePane = (id: PaneId, cols: number, rows: number): Promise<void
export const killPane = (id: PaneId): Promise<void> => invoke("kill_pane", { id });
/** Increment the "do not kill" transfer refcount for a pane. Source window
* calls this BEFORE removing the leaf from its tree so the unmount-driven
* kill_pane on the source becomes a no-op until the target window's
* XtermPane has claimed it. */
export const markPaneTransferring = (id: PaneId): Promise<void> =>
invoke("mark_pane_transferring", { id });
/** Decrement the transfer refcount. Target window's XtermPane calls this
* after subscribing to pane://{id}/data and replaying the ring snapshot. */
export const claimPane = (id: PaneId): Promise<void> =>
invoke("claim_pane", { id });
/** Snapshot of the per-pane scrollback ring as base64. Target window's
* XtermPane writes it into xterm.js before attaching the live data
* listener so a transferred pane doesn't open blank. */
export const getPaneRing = (id: PaneId): Promise<string> =>
invoke("get_pane_ring", { id });
// ---- multi-window pane transfer -------------------------------------------
export interface PendingInit {
leafJson: string;
paneId: PaneId;
workspaceName: string;
}
/** Open a new window and stash the pending-init payload keyed by the new
* window's label. Returns the new label. */
export const createPaneWindow = (payload: PendingInit): Promise<string> =>
invoke("create_pane_window", { payload });
/** Read and remove the pending-init for the current window. Null when there
* is no pending payload (main window startup, or this call already
* consumed it). */
export const takePendingWindowInit = (
label: string,
): Promise<PendingInit | null> =>
invoke("take_pending_window_init", { label });
/** Push this window's workspaces snapshot to the backend aggregator. The
* backend debounces and writes the merged envelope to workspace.json. */
export const pushWindowWorkspaces = (
label: string,
workspacesJson: string,
): Promise<void> =>
invoke("push_window_workspaces", { label, workspacesJson });
export const onPaneData = (
id: PaneId,
cb: (b64: string) => void,

View file

@ -269,3 +269,36 @@
min-height: 0;
position: relative;
}
/* Right-click context menu on the pane toolbar. Fixed-positioned popover
floating in the viewport; the LeafPane parent renders it inside its
own DOM tree so clicks within the menu still get the
stop-propagation chain. */
.pane-context-menu {
z-index: 200;
min-width: 180px;
background: #1a1a1a;
color: #e6e6e6;
border: 1px solid #2a5a8c;
border-radius: 4px;
padding: 4px;
font-family: "Cascadia Mono", "JetBrains Mono", "Consolas", monospace;
font-size: 12px;
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.6);
}
.pane-context-menu-item {
display: block;
width: 100%;
text-align: left;
background: transparent;
color: #e6e6e6;
border: none;
border-radius: 2px;
padding: 6px 10px;
font: inherit;
cursor: pointer;
}
.pane-context-menu-item:hover {
background: #2a5a8c;
color: #fff;
}

View file

@ -185,6 +185,38 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) {
setStatusOk(ok);
}, []);
// ---- right-click context menu ------------------------------------------
// Single entry in v1: "Move to new window" (pops the pane out into a
// fresh top-level tiletopia window without losing the PTY).
const [menuPos, setMenuPos] = useState<{ x: number; y: number } | null>(null);
const openContextMenu = useCallback(
(e: MouseEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
setMenuPos({ x: e.clientX, y: e.clientY });
},
[],
);
const closeContextMenu = useCallback(() => setMenuPos(null), []);
useEffect(() => {
if (!menuPos) return;
const onDocClick = () => setMenuPos(null);
const onEsc = (e: globalThis.KeyboardEvent) => {
if (e.key === "Escape") setMenuPos(null);
};
// Defer attaching the click listener so the click that opened the menu
// doesn't immediately close it.
const t = window.setTimeout(() => {
window.addEventListener("click", onDocClick);
window.addEventListener("keydown", onEsc, true);
}, 0);
return () => {
clearTimeout(t);
window.removeEventListener("click", onDocClick);
window.removeEventListener("keydown", onEsc, true);
};
}, [menuPos]);
// ---- header-drag swap ---------------------------------------------------
// Drag the toolbar onto another pane's toolbar/body to swap their tree
// positions. Uses a movement threshold so accidental tiny moves while
@ -306,6 +338,7 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) {
onPointerMove={onToolbarPointerMove}
onPointerUp={onToolbarPointerUp}
onPointerCancel={onToolbarPointerCancel}
onContextMenu={openContextMenu}
>
{editingLabel ? (
<input
@ -482,6 +515,7 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) {
{spec ? (
<XtermPane
spec={spec}
existingPaneId={orch.getInitialPaneIdFor(leaf.id)}
onStatus={onStatus}
onSpawn={onPaneSpawned}
onInput={onTerminalInput}
@ -500,6 +534,31 @@ export default function LeafPane({ leaf }: { leaf: LeafNode }) {
</div>
)}
</div>
{menuPos && (
<div
className="pane-context-menu"
style={{
position: "fixed",
top: menuPos.y,
left: menuPos.x,
}}
role="menu"
onClick={(e) => e.stopPropagation()}
onContextMenu={(e) => e.preventDefault()}
>
<button
type="button"
className="pane-context-menu-item"
role="menuitem"
onClick={() => {
closeContextMenu();
orch.moveToNewWindow(leaf.id);
}}
>
Move to new window
</button>
</div>
)}
</div>
);
}

View file

@ -56,6 +56,17 @@ export interface Orchestration {
// own quiet-state crosses the threshold; App aggregates so the titlebar
// can show an "N idle" count without spamming toast notifications.
reportLeafIdle: (leafId: NodeId, idle: boolean) => void;
// Multi-window pane transfer ---------------------------------------------
/** Pop a pane out of the current workspace into a fresh top-level window.
* The PTY stays alive across the move (the new window's XtermPane
* adopts the existing PaneId; scrollback ring is replayed). */
moveToNewWindow: (leafId: NodeId) => 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
* registered. */
getInitialPaneIdFor: (leafId: NodeId) => PaneId | undefined;
}
const OrchestrationContext = createContext<Orchestration | null>(null);

View file

@ -45,6 +45,16 @@ export const SHORTCUT_SECTIONS: ShortcutSection[] = [
{ keys: "Ctrl+1 … Ctrl+9", description: "Switch to tab 1 … 9" },
],
},
{
title: "Multi-window",
items: [
{
keys: "Right-click pane toolbar → Move to new window",
description:
"Pop the active pane into a fresh tiletopia window (PTY survives the move; scrollback ring replays)",
},
],
},
{
title: "Navigation",
items: [