Files
Netcatty/electron/bridges/windowManager/terminalPopupWindow.cjs
T
KenX049andbincxz bcce829294 feat(tabs): move a tab to its own window without reconnecting (#4202)
* feat(tabs): move a tab to its own window without reconnecting (#4201)

Adds "Move Tab to New Window" to the tab context menu. Instead of opening
a new connection like "Copy Tab to New Window", the tab is hidden from the
tab bar and an attach popup takes over the same live PTY, so bastion
sessions are not re-authenticated and no extra seat is used. Closing the
popup returns the tab (with its screen state) to the window it came from.

- popup lifecycle notifies the home window via terminal-popup:attach-closed
- new runtime poppedOut flag; popped-out tabs still persist for restore and
  are not labelled as AI silent sessions in the tray

* fix(tabs): keep moved tabs alive when their source window closes

- A moved-tab popup registers as the lifetime heir of its session. If the
  source window is destroyed, ownership passes to the popup instead of the
  session being closed (worker and in-process paths). AI observe popups are
  unchanged.
- If the source window is gone when the popup closes, skip the hand-back so
  the popup's ownership closes the session.
- Only offer/allow Move Tab to New Window for connected sessions; attach
  mode cannot connect or reconnect a backend.

* fix(tabs): expose Move Tab to New Window through TerminalHost

The handler was registered but not passed into the terminal domain bag,
so AppView received undefined and the menu item never rendered.

* fix(tabs): address move-to-window focus, crash ownership, live count, history, and AI context review findings

* fix(tabs): activate moved-tab lifetime heir only after output rebind succeeds

* fix(tabs): wait for popup attachment before hiding tab and exclude plugin sessions

* fix(tabs): confirm renderer reattach before resolving move and await output restore before unhiding tab

* fix(tabs): preserve detached output across popup crashes and avoid focusing main window from tray

* fix(tabs): deliver attach snapshots and output restore directly to peer session windows

* fix(tabs): schedule automatic output restore retries when popup recovery fails

* fix(tabs): handle reopen replay preservation, stale restore cancellation, startup workspace move, and shutdown log capture

* fix(tabs): reassert popped-out state after tray reopen

* test(terminal): provide log finalizer stubs in popup snapshot harness

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-24 10:50:36 +08:00

495 lines
17 KiB
JavaScript

/* eslint-disable no-undef */
const { randomUUID } = require("node:crypto");
const crashLogBridge = require("../crashLogBridge.cjs");
const {
isAttachPopupClosePrepared,
onAttachOutputRestored,
registerAttachPopupAuthorization,
releaseAttachPopupAuthorization,
restoreAttachedSessionOutput,
waitForAttachPopupOutcome,
} = require("../terminalAttachRestore.cjs");
const {
windowsFramelessContentChromeOptions,
} = require("./windowsWindowChrome.cjs");
const { placeTerminalPopup } = require("./terminalPopupPlacement.cjs");
const ATTACH_CLOSE_PREPARE_TIMEOUT_MS = 2000;
function createTerminalPopupWindowApi(ctx) {
with (ctx) {
const terminalPopupWindows = new Map();
/** attachSessionId -> popupId for AI silent-session observe windows */
const attachSessionPopups = new Map();
function isLiveWindow(win) {
return Boolean(win && typeof win.isDestroyed === "function" && !win.isDestroyed());
}
function isClientRect(value) {
if (!value || typeof value !== "object") return false;
const { x, y, width, height } = value;
return [x, y, width, height].every((entry) => typeof entry === "number" && Number.isFinite(entry))
&& width > 0
&& height > 0
&& width < 10000
&& height < 10000;
}
function resolveTerminalPopupFrame(electronModule, sourceWindow, avoidClientRect, preferred) {
const centered = resolveSettingsWindowBounds(electronModule, {
sourceWindow,
settingsWidth: preferred.width,
settingsHeight: preferred.height,
});
const fallback = {
x: centered.x,
y: centered.y,
width: preferred.width,
height: preferred.height,
};
if (!isClientRect(avoidClientRect) || !isLiveWindow(sourceWindow)) return fallback;
let content;
let zoom = 1;
try {
content = sourceWindow.getContentBounds();
const factor = sourceWindow.webContents?.getZoomFactor?.();
if (typeof factor === "number" && Number.isFinite(factor) && factor > 0) zoom = factor;
} catch {
return fallback;
}
if (!content || ![content.x, content.y, content.width, content.height].every((entry) => Number.isFinite(entry))) {
return fallback;
}
let workArea;
try {
workArea = electronModule?.screen?.getDisplayMatching?.(content)?.workArea;
} catch {
workArea = null;
}
if (!workArea || !Number.isFinite(workArea.width) || workArea.width <= 0) return fallback;
return placeTerminalPopup({
workArea,
sourceBounds: content,
avoid: {
x: content.x + avoidClientRect.x * zoom,
y: content.y + avoidClientRect.y * zoom,
width: avoidClientRect.width * zoom,
height: avoidClientRect.height * zoom,
},
width: preferred.width,
height: preferred.height,
});
}
async function openTerminalPopupWindow(electronModule, options, payload) {
const { BrowserWindow, shell } = electronModule;
const { preload, devServerUrl, isDev, appIcon, isMac, electronDir, sourceWindow } = options;
// Pin the home window at open time so a later mainWindow reassignment
// cannot redirect a moved tab's restore or close notification elsewhere.
const homeWindow = sourceWindow || mainWindow;
const attachSessionId = typeof payload?.attachSessionId === "string" && payload.attachSessionId
? payload.attachSessionId
: null;
const attachAuthorization = attachSessionId ? randomUUID() : null;
// "Move Tab to New Window": the popup owns the session until it hands it back.
const ownsSessionLifetime = Boolean(attachSessionId && payload?.moveSession === true);
const isHomeGone = () => ownsSessionLifetime && !isLiveWindow(homeWindow);
if (attachSessionId) {
const existingPopupId = attachSessionPopups.get(attachSessionId);
const existing = existingPopupId ? terminalPopupWindows.get(existingPopupId) : null;
if (existing && isLiveWindow(existing.win)) {
try {
showAndFocusWindow(existing.win);
} catch {
// ignore focus races
}
return { success: true, popupId: existingPopupId, reused: true };
}
if (existingPopupId) attachSessionPopups.delete(attachSessionId);
}
const osTheme = electronModule?.nativeTheme?.shouldUseDarkColors ? "dark" : "light";
const effectiveTheme = currentTheme === "dark" || currentTheme === "light" ? currentTheme : osTheme;
const frontendBackground = resolveFrontendBackgroundColor(electronDir || __dirname, effectiveTheme);
const backgroundColor = frontendBackground || "#1a1a1a";
const preferredWidth = 920;
const preferredHeight = 580;
const placed = resolveTerminalPopupFrame(electronModule, sourceWindow || mainWindow, payload?.avoidClientRect, {
width: preferredWidth,
height: preferredHeight,
});
const popupWidth = placed.width;
const popupHeight = placed.height;
const popupX = placed.x;
const popupY = placed.y;
const title = typeof payload?.title === "string" && payload.title.trim()
? payload.title.trim()
: "Terminal";
const popupId = String(payload?.popupId || randomUUID());
if (terminalPopupWindows.has(popupId)) {
throw new Error(`Terminal popup ID is already active: ${popupId}`);
}
crashLogBridge.captureDiagnostic("terminal-popup", "creating popup window", {
popupId,
title,
isDev,
popupX,
popupY,
});
const windowsChrome = windowsFramelessContentChromeOptions();
const win = new BrowserWindow({
title,
width: popupWidth,
height: popupHeight,
...(popupX !== undefined && popupY !== undefined ? { x: popupX, y: popupY } : {}),
minWidth: 480,
minHeight: 320,
backgroundColor,
icon: appIcon,
show: false,
frame: false,
...(isMac ? { trafficLightPosition: { x: 12, y: 12 } } : {}),
...windowsChrome,
webPreferences: {
preload,
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
spellcheck: false,
backgroundThrottling: false,
v8CacheOptions: V8_CACHE_OPTIONS,
},
});
let lifecycleReleased = false;
let closePreparationRequested = false;
let closePreparationTimer = null;
let restoreRetryTimer = null;
let attachClosedNotified = false;
const clearRestoreRetryTimer = () => {
if (restoreRetryTimer) {
clearTimeout(restoreRetryTimer);
restoreRetryTimer = null;
}
};
const notifyAttachClosed = () => {
clearRestoreRetryTimer();
if (!attachSessionId || attachClosedNotified) return;
// If a newer attach popup already took over this session, do not unhide the tab.
if (attachSessionPopups.has(attachSessionId)) {
attachClosedNotified = true;
return;
}
attachClosedNotified = true;
// Lets a tab moved into this popup reappear in the window it came from.
try {
if (isLiveWindow(homeWindow)) {
homeWindow.webContents.send("netcatty:terminal-popup:attach-closed", { sessionId: attachSessionId });
}
} catch {
// ignore destroyed home window
}
};
const scheduleAttachRestoreRetry = (attempt = 0) => {
if (
attachClosedNotified
|| !attachSessionId
|| !isLiveWindow(homeWindow)
|| attachSessionPopups.has(attachSessionId)
) {
clearRestoreRetryTimer();
return;
}
onAttachOutputRestored(attachSessionId, notifyAttachClosed);
if (attempt >= 4) return;
clearRestoreRetryTimer();
restoreRetryTimer = setTimeout(() => {
restoreRetryTimer = null;
if (
attachClosedNotified
|| !isLiveWindow(homeWindow)
|| attachSessionPopups.has(attachSessionId)
) {
return;
}
void Promise.resolve(restoreAttachedSessionOutput(attachSessionId))
.then((res) => {
if (attachSessionPopups.has(attachSessionId)) return;
if (!res || res.success || res.unavailable) {
notifyAttachClosed();
} else {
scheduleAttachRestoreRetry(attempt + 1);
}
})
.catch(() => {
scheduleAttachRestoreRetry(attempt + 1);
});
}, 150 * (2 ** attempt));
restoreRetryTimer.unref?.();
};
const releaseLifecycle = () => {
if (lifecycleReleased) return;
lifecycleReleased = true;
if (closePreparationTimer) clearTimeout(closePreparationTimer);
terminalPopupWindows.delete(popupId);
const homeGone = isHomeGone();
let restorePromise = null;
if (attachSessionId && attachSessionPopups.get(attachSessionId) === popupId && !homeGone) {
attachSessionPopups.delete(attachSessionId);
// Window may be destroyed before React cleanup runs; always restore
// the display route from the main-process lifecycle.
try {
restorePromise = Promise.resolve(restoreAttachedSessionOutput(attachSessionId));
} catch (err) {
crashLogBridge.captureError?.("terminal-popup", err, {
popupId,
attachSessionId,
step: "restore attach output on close",
});
}
}
releaseAttachPopupAuthorization(attachAuthorization);
if (attachSessionPopups.get(attachSessionId) === popupId) attachSessionPopups.delete(attachSessionId);
if (attachSessionId && !homeGone) {
if (restorePromise) {
void restorePromise.then((res) => {
if (!res || res.success || res.unavailable) {
notifyAttachClosed();
} else {
// Keep the home tab hidden and actively retry output recovery.
scheduleAttachRestoreRetry(0);
}
}).catch(() => {
scheduleAttachRestoreRetry(0);
});
} else {
notifyAttachClosed();
}
}
unregisterAppContentWindow(win);
notifyAppContentWindowClosed(win);
};
terminalPopupWindows.set(popupId, { releaseLifecycle, win, homeWindow });
if (attachSessionId) {
attachSessionPopups.set(attachSessionId, popupId);
registerAttachPopupAuthorization(
attachAuthorization,
attachSessionId,
win.webContents.id,
{ ownsLifetime: ownsSessionLifetime },
);
}
registerAppContentWindow(win);
crashLogBridge.captureDiagnostic("terminal-popup", "popup BrowserWindow created", {
popupId,
title,
webContentsId: win.webContents?.id,
});
try {
win.webContents?.setWindowOpenHandler?.(
createExternalOnlyWindowOpenHandler(shell),
);
} catch {
// ignore
}
win.on("close", (event) => {
if (!attachSessionId || isAttachPopupClosePrepared(attachAuthorization) || isHomeGone()) return;
event?.preventDefault?.();
if (closePreparationRequested) return;
closePreparationRequested = true;
try {
win.webContents.send("netcatty:terminal-popup:prepare-close", {
sessionId: attachSessionId,
authorization: attachAuthorization,
});
} catch {
// Timeout below force-closes and restores the route.
}
closePreparationTimer = setTimeout(() => {
closePreparationTimer = null;
try {
if (isLiveWindow(win)) win.destroy();
} catch {
releaseLifecycle();
}
}, ATTACH_CLOSE_PREPARE_TIMEOUT_MS);
});
win.on("closed", releaseLifecycle);
try {
win.webContents?.on?.("did-fail-load", (_event, errorCode, errorDescription, validatedURL) => {
console.warn("[TerminalPopup] Failed to load renderer", {
popupId,
errorCode,
errorDescription,
validatedURL,
});
});
win.webContents?.on?.("render-process-gone", (_event, details) => {
console.warn("[TerminalPopup] Renderer process gone", { popupId, details });
if (attachSessionId && !isHomeGone()) {
restoreAttachedSessionOutput(attachSessionId);
}
try {
if (isLiveWindow(win)) win.destroy();
} catch {
releaseLifecycle();
}
});
win.webContents?.on?.("console-message", (_event, level, message, line, sourceId) => {
crashLogBridge.captureDiagnostic("terminal-popup-console", message, {
popupId,
level,
line,
sourceId,
});
});
} catch {
// ignore diagnostics wiring failures
}
win.on("page-title-updated", (e) => { e.preventDefault(); });
try {
win.setBackgroundColor(backgroundColor);
} catch {
// ignore
}
applyWindowOpacityToWindow(win);
if (isMac) {
try {
win.setWindowButtonVisibility(true);
} catch {
// ignore
}
try {
win.setWindowButtonPosition({ x: 12, y: 12 });
} catch {
// ignore
}
}
const popupPath = "#/terminal-popup";
try {
if (isDev) {
try {
const baseUrl = getDevRendererBaseUrl(devServerUrl);
crashLogBridge.captureDiagnostic("terminal-popup", "loading dev popup URL", {
popupId,
url: `${baseUrl}${popupPath}`,
});
await win.loadURL(`${baseUrl}${popupPath}`);
} catch (e) {
console.warn("[TerminalPopup] Dev server not reachable", e);
crashLogBridge.captureError("terminal-popup", e, {
popupId,
step: "load dev popup URL",
});
await win.loadURL(`app://netcatty/index.html${popupPath}`);
}
} else {
crashLogBridge.captureDiagnostic("terminal-popup", "loading packaged popup URL", {
popupId,
url: `app://netcatty/index.html${popupPath}`,
});
await win.loadURL(`app://netcatty/index.html${popupPath}`);
}
win.webContents.send("netcatty:window:terminalPopupConfig", {
...payload,
popupId,
...(attachAuthorization ? { attachAuthorization } : {}),
});
crashLogBridge.captureDiagnostic("terminal-popup", "popup config delivered", {
popupId,
title,
});
if (ownsSessionLifetime) {
// Wait for the popup to actually attach (snapshot + output rebind)
// before showing it or telling the source window to hide the tab.
const attachOutcome = await waitForAttachPopupOutcome(attachAuthorization);
if (!attachOutcome?.success || lifecycleReleased || !isLiveWindow(win)) {
const errorMessage = attachOutcome?.error || "Failed to attach terminal popup";
try {
if (isLiveWindow(win)) {
if (typeof win.destroy === "function") win.destroy();
else win.close();
}
} catch {
// Lifecycle cleanup below remains fail-safe if Electron cleanup throws.
}
releaseLifecycle();
return { success: false, error: errorMessage };
}
}
showAndFocusWindow(win);
crashLogBridge.captureDiagnostic("terminal-popup", "popup window shown", {
popupId,
title,
visible: typeof win.isVisible === "function" ? win.isVisible() : undefined,
});
return { success: true, popupId };
} catch (error) {
try {
if (isLiveWindow(win)) {
if (typeof win.destroy === "function") win.destroy();
else win.close();
}
} catch {
// Lifecycle cleanup below remains fail-safe if Electron cleanup throws.
}
releaseLifecycle();
throw error;
}
}
function closeTerminalPopupWindow(popupId, requesterWindow = null) {
const record = terminalPopupWindows.get(popupId);
if (!record) return false;
if (requesterWindow && record.homeWindow && requesterWindow !== record.homeWindow && requesterWindow !== record.win) {
return false;
}
if (!isLiveWindow(record.win)) {
record.releaseLifecycle();
return true;
}
try {
record.win.close();
} catch {
try {
record.win.destroy?.();
} catch {
// The lifecycle registry must still be released below.
} finally {
record.releaseLifecycle();
}
}
return true;
}
return {
openTerminalPopupWindow,
closeTerminalPopupWindow,
getTerminalPopupWindows() {
return Array.from(terminalPopupWindows.values());
},
};
}
}
module.exports = { createTerminalPopupWindowApi };