Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(projects): offer to close the project when its last session is closed (#848)

Erik Zwep2a64ce473a42
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 72a50b0d8..83864267f 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -291,6 +291,11 @@ import {
deleteConfirmCopy,
planProjectClose
} from '../lib/projectCloseSessions'
+import {
+ USER_CLOSED_SESSION_EVENT,
+ lastSessionCloseCopy,
+ shouldOfferProjectClose
+} from '../lib/lastSessionClose'
import { backgroundNodeIds, mergeWithKeepAlive, overlayKeepAliveData } from '../lib/webviewKeepAlive'
import { useWebviewKeepAlive } from '../state/webviewKeepAlive'
import {
@@ -1690,6 +1695,9 @@ export function Canvas() {
confirmLabel: string
danger: boolean
} | null>(null)
+ // Issue #848 (opt-in): the project whose LAST session node the user just closed with ×, awaiting
+ // "close the project too?". Declining only clears this; the session was already ended by ×.
+ const [lastSessionOffer, setLastSessionOffer] = useState<{ id: string; name: string } | null>(null)
const [mergePush, setMergePush] = useState(false)
const settings = useSettings((s) => s.settings)
const gatewayModels = useModelGateway((s) => s.models)
@@ -1754,6 +1762,29 @@ export function Canvas() {
// onBrowserNewWindow effect can dedup repeat opens and rate-cap a flood of window.open calls.
const browserPopupSpawnsRef = useRef<{ url: string; source: string; t: number }[]>([])
const loadingRef = useRef(false)
+ // Issue #848: TerminalNode's × announces the user's own close (and nothing else does — not an
+ // exit, restart, hibernation, bulk delete, canvas-control close, project close or quit). Decided
+ // HERE against the live canvas while the closed node is still on it, and only for the project
+ // whose nodes `nodesRef` actually holds — see lib/lastSessionClose for what counts as a session.
+ useEffect(() => {
+ const onUserClosedSession = (e: Event): void => {
+ const nodeId = (e as CustomEvent<{ nodeId?: unknown }>).detail?.nodeId
+ if (typeof nodeId !== 'string') return
+ const store = useProjects.getState()
+ const projectId = nodesProjectIdRef.current
+ if (!projectId || projectId !== store.activeProjectId) return
+ const project = store.getProject(projectId)
+ const offer = shouldOfferProjectClose({
+ enabled: useSettings.getState().settings.offerCloseProjectOnLastSession,
+ closedNodeId: nodeId,
+ nodes: nodesRef.current,
+ project
+ })
+ if (offer && project) setLastSessionOffer({ id: project.id, name: project.name })
+ }
+ window.addEventListener(USER_CLOSED_SESSION_EVENT, onUserClosedSession)
+ return () => window.removeEventListener(USER_CLOSED_SESSION_EVENT, onUserClosedSession)
+ }, [])
const flowWrapRef = useRef<HTMLDivElement>(null)
// Glass terminals: while the camera moves, every glass node's backdrop changes each frame and
// the 28px blur is re-rasterised for all of them. The class drops the blur (the tint stays, and
@@ -18381,6 +18412,34 @@ export function Canvas() {
)
})()}
+ {lastSessionOffer && (
+ (() => {
+ const copy = lastSessionCloseCopy(lastSessionOffer.name)
+ return (
+ <ConfirmDialog
+ message={copy.message}
+ confirmLabel={copy.confirmLabel}
+ cancelLabel={copy.cancelLabel}
+ // Non-destructive (the canvas is kept, reopenable from Recently closed), so no danger
+ // styling. It appears right after a click the user aimed at a node, so it is answered
+ // by an explicit click: no Enter-confirm, no autofocused button a stray keystroke
+ // could activate (see components/confirm-key).
+ danger={false}
+ enterConfirms={false}
+ autoFocusButtons={false}
+ onConfirm={() => {
+ // The existing close path (issue #848: reuse, don't reimplement). With no session
+ // node left it closes silently; if an agent spawned one since, it gets the
+ // usual #442 confirm instead.
+ closeProject(lastSessionOffer.id)
+ setLastSessionOffer(null)
+ }}
+ onCancel={() => setLastSessionOffer(null)}
+ />
+ )
+ })()
+ )}
+
{deleteTarget && (
<ConfirmDialog
message={deleteTarget.message}
diff --git a/src/renderer/canvas/canvas-wiring.test.tsx b/src/renderer/canvas/canvas-wiring.test.tsx
index ffacc4ebb..59db68875 100644
--- a/src/renderer/canvas/canvas-wiring.test.tsx
+++ b/src/renderer/canvas/canvas-wiring.test.tsx
@@ -539,3 +539,40 @@ describe('the canvas lock is remembered only when the user opted in', () => {
expect(effect).toContain('if (!canvasLockRestored.current) {')
})
})
+
+describe('the last-session close offer is wired to the × and to the existing close path (issue #848)', () => {
+ // The decision lives in lib/lastSessionClose and is tested there; what those tests cannot see is
+ // WHO raises it and WHAT accepting it does. Both are a line each in files with no render harness.
+ const TERMINAL_SRC = fs.readFileSync(path.join(__dirname, '..', 'nodes', 'TerminalNode.tsx'), 'utf8')
+ const closeButton = TERMINAL_SRC.slice(
+ TERMINAL_SRC.indexOf('<Tooltip label="Close (ends the session)">'),
+ TERMINAL_SRC.indexOf('<IconClose />', TERMINAL_SRC.indexOf('<Tooltip label="Close (ends the session)">'))
+ )
+
+ it('only the × announces a user close, and before the node leaves the canvas', () => {
+ // Before `deleteElements`: the decision needs the closed node still present, so a second
+ // click on a node already gone finds nothing to offer.
+ expect(indexOfPresent(closeButton, 'announceUserClosedSession(id)')).toBeLessThan(
+ indexOfPresent(closeButton, 'deleteElements({ nodes: [{ id }] })')
+ )
+ // Exactly one announcer in the node: no other teardown (restart, respawn, exit) may ask.
+ expect(TERMINAL_SRC.split('announceUserClosedSession(').length - 1).toBe(1)
+ })
+
+ it('Canvas decides with the opt-in setting and the live canvas, and accepts through closeProject', () => {
+ const listener = CANVAS_SRC.slice(
+ CANVAS_SRC.indexOf('window.addEventListener(USER_CLOSED_SESSION_EVENT'),
+ CANVAS_SRC.indexOf('window.removeEventListener(USER_CLOSED_SESSION_EVENT')
+ )
+ expect(CANVAS_SRC).toContain('const onUserClosedSession = (e: Event): void => {')
+ const handler = CANVAS_SRC.slice(
+ CANVAS_SRC.indexOf('const onUserClosedSession = (e: Event): void => {'),
+ CANVAS_SRC.indexOf('window.addEventListener(USER_CLOSED_SESSION_EVENT')
+ )
+ expect(listener).toContain('onUserClosedSession')
+ expect(handler).toContain('useSettings.getState().settings.offerCloseProjectOnLastSession')
+ expect(handler).toContain('nodes: nodesRef.current')
+ const dialog = CANVAS_SRC.slice(CANVAS_SRC.indexOf('{lastSessionOffer && ('))
+ expect(dialog.slice(0, 1500)).toContain('closeProject(lastSessionOffer.id)')
+ })
+})
diff --git a/src/renderer/components/settings/sections/BehaviorSection.tsx b/src/renderer/components/settings/sections/BehaviorSection.tsx
index 88de51467..a53ce4e21 100644
--- a/src/renderer/components/settings/sections/BehaviorSection.tsx
+++ b/src/renderer/components/settings/sections/BehaviorSection.tsx
@@ -40,6 +40,10 @@ const ROWS = {
title: 'Zoom when going to a node',
keywords: ['zoom', 'focus', 'go to', 'node', 'jump', 'camera', 'session', 'sidebar']
},
+ closeProjectOnLastSession: {
+ title: 'Offer to close a project after its last session',
+ keywords: ['close', 'project', 'last', 'session', 'node', 'tab', 'recently closed', 'cleanup', 'agent', 'terminal']
+ },
rememberLock: {
title: 'Remember the canvas lock',
keywords: ['lock', 'canvas', 'view', 'pan', 'zoom', 'freeze', 'remember', 'restart', 'persist']
@@ -237,6 +241,19 @@ export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.
}
/>
</SearchableRow>
+ <SearchableRow {...ROWS.closeProjectOnLastSession}>
+ <FieldRow
+ label="Offer to close a project after its last session"
+ description="When you close the last terminal or agent node in a project with ×, ask whether to close the project too. It stays reopenable from Recently closed."
+ control={
+ <Switch
+ checked={settings.offerCloseProjectOnLastSession}
+ onChange={(v) => update({ offerCloseProjectOnLastSession: v })}
+ ariaLabel="Offer to close a project after its last session"
+ />
+ }
+ />
+ </SearchableRow>
<SearchableRow {...ROWS.rememberLock}>
<FieldRow
label="Remember the canvas lock"
diff --git a/src/renderer/lib/lastSessionClose.test.ts b/src/renderer/lib/lastSessionClose.test.ts
new file mode 100644
index 000000000..14d38b391
--- /dev/null
+++ b/src/renderer/lib/lastSessionClose.test.ts
@@ -0,0 +1,108 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ USER_CLOSED_SESSION_EVENT,
+ announceUserClosedSession,
+ isSessionNode,
+ lastSessionCloseCopy,
+ shouldOfferProjectClose
+} from './lastSessionClose'
+
+const project = { remote: undefined, closed: false }
+const term = (id: string) => ({ id, type: 'terminal' })
+
+describe('isSessionNode (issue #848)', () => {
+ it('counts terminal-kind nodes — plain shells and agents alike — and nothing else', () => {
+ expect(isSessionNode({ type: 'terminal' })).toBe(true)
+ // An untyped node is a terminal, the same `?? 'terminal'` default terminalNodeIds applies.
+ expect(isSessionNode({})).toBe(true)
+ for (const type of ['sticky', 'markdown', 'browser', 'editor', 'files', 'group', 'subagent']) {
+ expect(isSessionNode({ type }), type).toBe(false)
+ }
+ })
+})
+
+describe('shouldOfferProjectClose (issue #848)', () => {
+ it('offers when the × closed the only session node on the canvas', () => {
+ expect(
+ shouldOfferProjectClose({ enabled: true, closedNodeId: 'a', nodes: [term('a')], project })
+ ).toBe(true)
+ })
+
+ it('is opt-in: never offers while the setting is off', () => {
+ expect(
+ shouldOfferProjectClose({ enabled: false, closedNodeId: 'a', nodes: [term('a')], project })
+ ).toBe(false)
+ })
+
+ it('does not offer while another session node remains — hibernated or parked ones included', () => {
+ // Extra fields are what a real canvas node carries; the decision must ignore them.
+ const hibernated = { id: 'b', type: 'terminal', data: { hibernated: true } }
+ // A hibernated agent is still a terminal node on the canvas, so it still counts (the issue's
+ // own reason for tying the offer to the click rather than to "no process is running").
+ expect(
+ shouldOfferProjectClose({
+ enabled: true,
+ closedNodeId: 'a',
+ nodes: [term('a'), hibernated],
+ project
+ })
+ ).toBe(false)
+ })
+
+ it('still offers when only non-session nodes (notes, markdown, a browser) remain', () => {
+ expect(
+ shouldOfferProjectClose({
+ enabled: true,
+ closedNodeId: 'a',
+ nodes: [term('a'), { id: 's', type: 'sticky' }, { id: 'w', type: 'browser' }, { id: 'm', type: 'markdown' }],
+ project
+ })
+ ).toBe(true)
+ })
+
+ it('does not offer for a node that is not (or no longer) on this canvas', () => {
+ // A repeated click on a node already gone, or a × on a node rendered outside the active
+ // canvas, must not ask — the click has to be the one that removed the last session HERE.
+ expect(
+ shouldOfferProjectClose({ enabled: true, closedNodeId: 'gone', nodes: [], project })
+ ).toBe(false)
+ expect(
+ shouldOfferProjectClose({ enabled: true, closedNodeId: 'x', nodes: [{ id: 'x', type: 'sticky' }], project })
+ ).toBe(false)
+ })
+
+ it('does not offer without an open, local project', () => {
+ const base = { enabled: true, closedNodeId: 'a', nodes: [term('a')] }
+ expect(shouldOfferProjectClose({ ...base, project: undefined })).toBe(false)
+ expect(shouldOfferProjectClose({ ...base, project: { closed: true } })).toBe(false)
+ // A relay tab is a view of another machine's project: "close" there only removes the view,
+ // which a reconnect brings straight back — not what this offer promises.
+ expect(
+ shouldOfferProjectClose({ ...base, project: { remote: { hostId: 'h' } as never, closed: false } })
+ ).toBe(false)
+ })
+})
+
+describe('lastSessionCloseCopy', () => {
+ it('names the project and says where to reopen it', () => {
+ const copy = lastSessionCloseCopy('Demo')
+ expect(copy.message).toContain('“Demo”')
+ expect(copy.message).toContain('Recently closed')
+ expect(copy.confirmLabel).toBe('Close project')
+ expect(copy.cancelLabel).toBe('Keep open')
+ })
+})
+
+describe('announceUserClosedSession', () => {
+ afterEach(() => vi.restoreAllMocks())
+
+ it('dispatches the node id on the window event Canvas listens to', () => {
+ const seen: unknown[] = []
+ const target = new EventTarget()
+ vi.stubGlobal('window', target)
+ target.addEventListener(USER_CLOSED_SESSION_EVENT, (e) => seen.push((e as CustomEvent).detail))
+ announceUserClosedSession('n1')
+ expect(seen).toEqual([{ nodeId: 'n1' }])
+ vi.unstubAllGlobals()
+ })
+})
diff --git a/src/renderer/lib/lastSessionClose.ts b/src/renderer/lib/lastSessionClose.ts
new file mode 100644
index 000000000..05c3a9a28
--- /dev/null
+++ b/src/renderer/lib/lastSessionClose.ts
@@ -0,0 +1,75 @@
+// "That was the last session — close the project too?" (issue #848, opt-in).
+//
+// Users finish work in a project by closing its nodes, but the project tab stays open, so the tab
+// strip only grows. Closing a project is cheap — `closeProject` keeps the canvas and lists the
+// project under "Recently closed" — so the moment the user closes the LAST session node with ×
+// is the natural moment to offer it.
+//
+// The trigger is the × click itself, never "no process is running": a restart, a session that
+// exits on its own, a hibernated agent (its node is still on the canvas), a bulk delete, a
+// canvas-control close, a project close or an app quit must never ask. That is why the node
+// ANNOUNCES the user's click (`announceUserClosedSession`, called only from TerminalNode's ×) and
+// Canvas decides with `shouldOfferProjectClose` against its live node list.
+//
+// "Session node" is the code's own definition: a TERMINAL-kind node — plain shells and agents
+// alike, working, idle, hibernated or exited — the same `(kind ?? 'terminal') === 'terminal'`
+// classification `terminalNodeIds` (lib/projectCloseSessions) uses for the close/delete dialogs.
+// Notes, markdown, browser, editor and other nodes do not count: they end no session, and the
+// canvas they sit on is kept by the close anyway (the issue's open question — answered "still
+// offer", the smallest reading of "last session node").
+
+import type { Project } from '@shared/types'
+
+/** Window event TerminalNode's × raises; Canvas listens. `detail: { nodeId }`. */
+export const USER_CLOSED_SESSION_EVENT = 'nodeterm:user-closed-session'
+
+/** Called by the × on a terminal/agent node, BEFORE the node is removed from the canvas. */
+export function announceUserClosedSession(nodeId: string): void {
+ window.dispatchEvent(new CustomEvent(USER_CLOSED_SESSION_EVENT, { detail: { nodeId } }))
+}
+
+/** Is this canvas node a session (terminal-kind) node? An untyped node is a terminal. */
+export function isSessionNode(node: { type?: string }): boolean {
+ return (node.type ?? 'terminal') === 'terminal'
+}
+
+export interface LastSessionCloseInput {
+ /** `settings.offerCloseProjectOnLastSession` — default off. */
+ enabled: boolean
+ /** The node whose × was clicked. */
+ closedNodeId: string
+ /** The ACTIVE canvas's nodes, read while the closed node is still among them. */
+ nodes: readonly { id: string; type?: string }[]
+ /** The active project. */
+ project: Pick<Project, 'remote' | 'closed'> | undefined
+}
+
+/**
+ * Should closing `closedNodeId` offer to close the project? Only when the setting is on, the
+ * project is an open LOCAL/SSH project (a relay tab's "close" only drops a view a reconnect
+ * brings back), the clicked node is a session node still on this canvas (a repeated click on a
+ * node already gone, or one rendered off-canvas, asks nothing), and no other session node remains.
+ */
+export function shouldOfferProjectClose(input: LastSessionCloseInput): boolean {
+ const { enabled, closedNodeId, nodes, project } = input
+ if (!enabled || !project || project.closed || project.remote) return false
+ const closed = nodes.find((n) => n.id === closedNodeId)
+ if (!closed || !isSessionNode(closed)) return false
+ return !nodes.some((n) => n.id !== closedNodeId && isSessionNode(n))
+}
+
+export interface LastSessionCloseCopy {
+ message: string
+ confirmLabel: string
+ cancelLabel: string
+}
+
+export function lastSessionCloseCopy(name: string): LastSessionCloseCopy {
+ return {
+ message:
+ `That was the last session in “${name}”. Close the project too? You can reopen it from ` +
+ `the start screen's “Recently closed” list.`,
+ confirmLabel: 'Close project',
+ cancelLabel: 'Keep open'
+ }
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 0d2cc9590..ca373851a 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -233,6 +233,7 @@ import { isLiquidGlass } from '../lib/appTheme'
import { readsClaudeTranscript } from '../lib/transcriptGates'
import { liveProjectJumpTarget } from '../lib/projectJump'
import { pushSessionRename } from '../lib/sessionRename'
+import { announceUserClosedSession } from '../lib/lastSessionClose'
import { useSettings } from '../state/settings'
import { useCodexIdentity, codexSharedIdentity, codexFallbackText } from '../state/codexIdentity'
import { ensureCodexLaunchCaps } from '../state/codexCli'
@@ -6355,6 +6356,10 @@ export function TerminalNode({
aria-label="Close"
onClick={() => {
transport.destroy(id)
+ // Issue #848: THIS click — and no other teardown — may offer to close the project
+ // when it removes the last session node. Announced before `deleteElements`, so
+ // Canvas still sees the node it is deciding about (lib/lastSessionClose).
+ announceUserClosedSession(id)
deleteElements({ nodes: [{ id }] })
}}
>
diff --git a/src/shared/default-settings.test.ts b/src/shared/default-settings.test.ts
index 2c34c6f86..7323067bf 100644
--- a/src/shared/default-settings.test.ts
+++ b/src/shared/default-settings.test.ts
@@ -36,6 +36,12 @@ describe('DEFAULT_SETTINGS', () => {
expect(DEFAULT_SETTINGS.copyOnSelect).toBe(false)
})
+ it('does not offer to close a project after its last session by default (issue #848)', () => {
+ // Opt-in: not everyone closes their last session when they are done with a project, so an
+ // install that never turns this on must never see the question.
+ expect(DEFAULT_SETTINGS.offerCloseProjectOnLastSession).toBe(false)
+ })
+
it('keeps common identifier and path characters inside terminal word selections', () => {
expect(DEFAULT_SETTINGS.terminalWordSeparator).not.toMatch(/[-_/.]/)
})
diff --git a/src/shared/types.ts b/src/shared/types.ts
index e27de074e..4dd7e098b 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1822,6 +1822,12 @@ export interface Settings {
* costs them the sense of where they were. Either way the node is centred and kept clear of the
* floating chrome (renderer/lib/nodeFocus). */
focusZoomToNode: boolean
+ /** Closing the LAST session (terminal/agent) node of a project with its × offers to close the
+ * project too (issue #848). Opt-in — default OFF, because not everyone closes their last
+ * session when they are done with a project. Only the user's × click asks; a restart, an exit,
+ * a hibernated agent (still a node) or a bulk/programmatic close never does
+ * (renderer/lib/lastSessionClose). Declining keeps the project open. */
+ offerCloseProjectOnLastSession: boolean
/** Whether the bottom-left canvas lock survives a restart. OFF by default, and deliberately so:
* the lock was transient by design, because a canvas that will not pan on the next launch reads
* as "the app is frozen" to whoever opens it, and the lit button is a small thing to spot. Users
@@ -2240,6 +2246,7 @@ export const DEFAULT_SETTINGS: Settings = {
panHoverDelay: 600,
doubleClickFocus: true,
focusZoomToNode: true,
+ offerCloseProjectOnLastSession: false,
rememberCanvasLock: false,
openMarkdownPreview: true,
openMarkdownPreviewMigrated: true,