Files
Netcatty/electron/bridges/rendererSessionLifetime.cjs
T
3d593b206b fix(terminal): close sessions when their owning window is destroyed (#3839)
* fix(terminal): close sessions when their owning renderer is destroyed

* test(terminal): keep a shared SSH transport when a copied window closes

Closing a child window must drop only the shells that window owns.
Cover several tabs on one connection split across the main window and
the copied window, for both the in-process lifetime tracker and the
worker close path.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-10-22 20:00:38 +08:00

34 lines
1.5 KiB
JavaScript

"use strict";
// In-process terminal backends share one registry. Remember the first renderer
// for each session object, not its mutable output route: an attached popup is
// only a display, and a replacement boot is a different object.
const owners = new WeakMap();
const trackedRegistries = new WeakMap();
function trackRendererSessionLifetime(sessions, sessionId, contents, closeSession, transferOwnership = false) {
const session = sessions?.get(sessionId);
// Worker/agent senders are synthetic and have no renderer destruction event.
if (!session || typeof contents?.once !== "function") return;
if (owners.has(session) && !transferOwnership) return;
owners.set(session, contents);
let tracked = trackedRegistries.get(sessions);
if (!tracked) trackedRegistries.set(sessions, tracked = new WeakSet());
const closeOwnedSessions = () => {
for (const [id, current] of [...sessions]) {
if (owners.get(current) !== contents || sessions.get(id) !== current) continue;
closeSession({ sender: contents }, { sessionId: id, bootEpoch: current.bootEpoch });
}
};
if (!tracked.has(contents)) {
tracked.add(contents);
contents.once("destroyed", closeOwnedSessions);
}
// An asynchronous start may finish after its window disappeared. Let its
// synchronous setup finish (including acquiring SSH leases), then close only
// the still-owned object through the same path as an explicit tab close.
if (contents.isDestroyed?.()) queueMicrotask(closeOwnedSessions);
}
module.exports = { trackRendererSessionLifetime };