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): say what closing a project parks, offer to end its sessions (#442)

enes01f7d2c18ce1
diff --git a/CLAUDE.md b/CLAUDE.md
index cbc7ca07c..780897b49 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -247,7 +247,27 @@ project's nodes only.** The contract:
nodes, which reattach warm or cold-restore). `hasProjects` counts only **open** projects, so
closing the last open one shows the welcome screen. **Permanent** deletion (`deleteProject`:
`transport.destroy(nodeId)` per terminal + drop agent status + SSH teardown) now only happens
- via the `×` on a "Recently closed" entry.
+ via the `×` on a "Recently closed" entry. **Closing now SAYS what it parks** (issue #442 —
+ "close" read like cleanup while meaning "hide, and keep running"): a project with terminal
+ nodes gets a confirm naming the count, with an opt-in **"end its sessions too"** checkbox
+ (default OFF — parking stays the rule; checked flips the confirm to danger). The pure half is
+ `renderer/lib/projectCloseSessions.ts`: **one definition of N** — the project's terminal-kind
+ nodes, exactly the set the action addresses (`transport.destroy` is idempotent on a dead
+ session), never a liveness-verified count that could disagree with the action; the END happens
+ at confirm time against the re-resolved node set (agents spawn nodes on their own). A relay tab
+ or a 0-terminal project closes silently (byte-identical old path). `endProjectSessions` mirrors
+ `deleteProject`'s teardown EXCEPT it keeps agent status (the persisted sessionId is what lets a
+ reopen cold-restore `--resume`) and never disconnects SSH masters (close never managed the
+ connection). The `×` also confirms now, via `deleteConfirmCopy` — a relay tab gets "removes
+ only this machine's view; reconnecting brings it back" with no danger styling (deleting the
+ view is what turns the next connect into a first-connect re-adopt), local/SSH get the session
+ count + "the folder (incl. .nodeterm/project.json) is not deleted". And "Recently closed" rows
+ show a **live-session badge** (`closedSessionCounts` over ONE on-demand local
+ `sessionMemory.read` per welcome-screen appearance — never a timer; `ok:false` ⇒ no badge,
+ never "0"; an SSH project's host-side sessions are deliberately not claimed by the local
+ count). Server Edition: all renderer-side; the ws-bridge `sessionMemory` is real, so badges
+ describe the server machine; the `sshProject` legs only run for `project.ssh`, which that
+ shell never has.
- A project's `cwd` (folder picker, `dialog:select-folder`) is passed to terminal/Claude
node factories so new terminals open there. **Folder ↔ project is deduped:** "Open folder…"
reuses the existing project with that `cwd` (and its nodes) instead of creating a duplicate.
@@ -1684,7 +1704,10 @@ about which machine they describe. Reading + parsing is `core/session-memory.ts`
and one per panel open / `⟳`. Same rule this file already sets for **Remote usage**, for the same
reason: every remote read is an ssh exec plus a `ps` of somebody else's whole process table. The
full sweep runs on the panel's MOUNT (it is unmounted while closed) and on `⟳` — never on a timer,
- never from the pill.
+ never from the pill. One more consumer, same discipline: the welcome screen runs ONE **local**
+ sweep per appearance (only while "Recently closed" is non-empty) for its per-project
+ live-session badges (issue #442), bypassing the panel's store on purpose — it must not disturb
+ `state/sessionMemory.ts`'s module-level scope stamp, and its scope is always THIS machine.
- **The pill is the single owner of the store's `startHostPoll` / `stopHostPoll`** — the timer and the
active-scope stamp are MODULE SINGLETONS. The panel must never call them: a `stopHostPoll` on
unmount would clear the pill's interval with nothing left to restart it, and the number would
diff --git a/docs/session-memory.md b/docs/session-memory.md
index b56e3e9e4..243bd30cf 100644
--- a/docs/session-memory.md
+++ b/docs/session-memory.md
@@ -303,7 +303,13 @@ previous machine's facts on a real change.
rule `CLAUDE.md` already sets for remote usage, for the same reason.
**The full sweep never runs on a timer and never from the pill.** The panel is *unmounted* while
-closed and its mount is what triggers the sweep.
+closed and its mount is what triggers the sweep. One additional consumer follows the same rule:
+the welcome screen runs one **local** sweep per appearance (only while "Recently closed" lists
+projects) to badge each closed project with its live `nt-*` session count (issue #442,
+`renderer/lib/projectCloseSessions.ts` `closedSessionCounts`). It calls
+`window.nodeTerminal.sessionMemory.read({ remote: false })` directly — not through
+`state/sessionMemory.ts`, whose module-level scope stamp belongs to the pill/panel pair — and a
+failed sweep (`ok:false` / rejection) renders **no badge**, never "0".
**The pill is icon-only at rest.** It sits on every canvas, always, so a permanent
`RAM 15.6 GB / 62.5 GB` is a row of numbers nobody asked for — the pill's job is to be findable, not
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 49f76fb64..93a4ec30f 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -212,6 +212,12 @@ import { PresenceLayer } from '../components/PresenceLayer'
import { Facepile } from '../components/Facepile'
import { PresenceNamePrompt } from '../components/PresenceNamePrompt'
import { nodeTravel, projectTravel } from '../lib/presenceTravel'
+import {
+ closeConfirmCopy,
+ closedSessionCounts,
+ deleteConfirmCopy,
+ planProjectClose
+} from '../lib/projectCloseSessions'
import { backgroundNodeIds, mergeWithKeepAlive, overlayKeepAliveData } from '../lib/webviewKeepAlive'
import { useWebviewKeepAlive } from '../state/webviewKeepAlive'
import {
@@ -1127,6 +1133,25 @@ export function Canvas() {
// whether the dialog offers (and warns about) the push to origin — a repo with no `origin` must
// never be threatened with a publish that cannot happen.
const [mergeTarget, setMergeTargetState] = useState<MergeState | null>(null)
+ // Project awaiting the CLOSE confirm (issue #442): parking stays the default; `end` mirrors the
+ // dialog's opt-in "end its sessions too" checkbox. `count` is the terminal-node count taken at
+ // request time — the confirm re-resolves the node set, so the action ends the set that exists
+ // when the user answers, not a snapshot (agents spawn nodes on their own).
+ const [closeTarget, setCloseTargetState] = useState<{
+ id: string
+ name: string
+ count: number
+ end: boolean
+ } | null>(null)
+ // Closed project awaiting the PERMANENT-delete confirm (the "Recently closed" ×). The copy is
+ // computed at request time by `deleteConfirmCopy` — a relay tab gets the "removes only this
+ // machine's view" wording instead of a destructive one.
+ const [deleteTarget, setDeleteTargetState] = useState<{
+ id: string
+ message: string
+ confirmLabel: string
+ danger: boolean
+ } | null>(null)
const [mergePush, setMergePush] = useState(false)
const settings = useSettings((s) => s.settings)
const gatewayModels = useModelGateway((s) => s.models)
@@ -1335,7 +1360,9 @@ export function Canvas() {
remove: false,
move: false,
merge: false,
- peer: false
+ peer: false,
+ closeProject: false,
+ deleteProject: false
})
// Every confirm setter flips its flag AT CALL TIME. Assigning the mirror during RENDER (what this
// used to do) is a tick too late: two agent verbs arriving in separate IPC events before React
@@ -1361,10 +1388,30 @@ export function Canvas() {
confirmFlags.current.peer = !!v
setPendingPeerState(v)
}, [])
+ const setCloseTarget = useCallback((v: { id: string; name: string; count: number; end: boolean } | null) => {
+ confirmFlags.current.closeProject = !!v
+ setCloseTargetState(v)
+ }, [])
+ const setDeleteTarget = useCallback(
+ (v: { id: string; message: string; confirmLabel: string; danger: boolean } | null) => {
+ confirmFlags.current.deleteProject = !!v
+ setDeleteTargetState(v)
+ },
+ []
+ )
/** Is any confirm open — or being opened (the async gap in `requestRemoveWorktree`)? */
const confirmBusy = useCallback(() => {
const f = confirmFlags.current
- return f.confirm || f.remove || f.move || f.merge || f.peer || removePendingRef.current
+ return (
+ f.confirm ||
+ f.remove ||
+ f.move ||
+ f.merge ||
+ f.peer ||
+ f.closeProject ||
+ f.deleteProject ||
+ removePendingRef.current
+ )
}, [])
const nodeTypes = useMemo(
@@ -10369,20 +10416,79 @@ export function Canvas() {
[persist]
)
- // Close a project: hide it from the tab bar but keep it (and its tmux/agent sessions) intact
- // so it can be reopened later from the start screen. Non-destructive — the inverse of the old
- // "Delete project". Switching away unmounts its nodes (a detach, not a kill); the sessions
- // survive exactly like a project switch, and a cold restart later reconstructs them.
- const closeProject = useCallback(
- (id: string) => {
+ // End every terminal session a project parks, WITHOUT deleting the project (the opt-in half of
+ // the close dialog, issue #442). Mirrors `deleteProject`'s session teardown with two deliberate
+ // differences: agent status is KEPT (the persisted sessionId is what lets a later reopen
+ // cold-restore `claude --resume` the conversation — ending the process is a reboot, not an
+ // amnesia), and SSH masters are NOT disconnected (close never managed the connection before,
+ // and a reopen expects it exactly as a project switch left it).
+ const endProjectSessions = useCallback((id: string) => {
+ const project = useProjects.getState().getProject(id)
+ if (!project) return
+ project.nodes.forEach((n) => {
+ if ((n.kind ?? 'terminal') === 'terminal') {
+ disposeTerminalOnUnmount(sessionForProject(id).id, n.id) // may be parked from a recent switch away
+ transport.destroy(n.id)
+ useAgentNodes.getState().clearForParent(n.id) // ephemeral fan-out of a session that just ended
+ }
+ })
+ // SSH project / host attachments: `transport.destroy` reaches a remote session only through a
+ // LIVE local client, which an unmounted node has not — kill by name over the still-alive
+ // masters, same as deleteProject (idempotent; a dead master is a best-effort miss).
+ const terminalIds = project.nodes
+ .filter((n) => (n.kind ?? 'terminal') === 'terminal')
+ .map((n) => n.id)
+ if (project.ssh) {
+ void window.nodeTerminal.sshProject.killSessions(id, terminalIds).catch(() => {})
+ }
+ for (const scopeId of useSshConn.getState().attachmentScopesOf(id)) {
+ const nodeIds =
+ hostAttachmentsFor(id, project.nodes, project.ssh?.server).find(
+ (a) => a.scopeId === scopeId
+ )?.nodeIds ?? []
+ void window.nodeTerminal.sshProject.killSessions(scopeId, nodeIds).catch(() => {})
+ }
+ }, [])
+
+ // Close a project: hide it from the tab bar but keep it (and, by default, its tmux/agent
+ // sessions) intact so it can be reopened later from the start screen. Non-destructive — the
+ // inverse of the old "Delete project". Switching away unmounts its nodes (a detach, not a
+ // kill); the sessions survive exactly like a project switch, and a cold restart later
+ // reconstructs them. `endSessions` is the close dialog's explicit opt-in — the node set is
+ // re-resolved HERE (after the fresh commit), so the action ends the sessions that exist at
+ // confirm time, not the set that was counted when the dialog opened.
+ const performCloseProject = useCallback(
+ (id: string, endSessions = false) => {
const store = useProjects.getState()
if (id === store.activeProjectId) commitActiveToStore()
+ if (endSessions) endProjectSessions(id)
useReopenHistory.getState().push({ kind: 'project', projectId: id, closedAt: Date.now() })
disposeRelayTabForProject(id)
store.closeProject(id)
void writeDisk()
},
- [commitActiveToStore, writeDisk, disposeRelayTabForProject]
+ [commitActiveToStore, writeDisk, disposeRelayTabForProject, endProjectSessions]
+ )
+
+ // The one entrance for both Close surfaces (tab caret menu + sidebar context menu). A project
+ // parking terminal sessions gets a confirm that SAYS so — with the count, and an opt-in to end
+ // them (issue #442: "close" read like cleanup while actually meaning "hide, and keep running").
+ // A relay tab or a project with no terminal nodes closes silently, exactly as before.
+ const closeProject = useCallback(
+ (id: string) => {
+ const store = useProjects.getState()
+ // Count the LIVE canvas, not a stale serialization — agents may have spawned nodes since
+ // the last commit.
+ if (id === store.activeProjectId) commitActiveToStore()
+ const project = store.getProject(id)
+ const plan = planProjectClose(project)
+ if (plan.kind === 'silent' || !project) {
+ performCloseProject(id)
+ return
+ }
+ setCloseTarget({ id, name: project.name, count: plan.sessionCount, end: false })
+ },
+ [commitActiveToStore, performCloseProject, setCloseTarget]
)
// Right-click on a sidebar project header: mostly the same project actions as the tab caret
@@ -10565,6 +10671,51 @@ export function Canvas() {
[commitActiveToStore, writeDisk, disposeRelayTabForProject]
)
+ // The "Recently closed" × goes through a confirm now (issue #442): it is the one permanently
+ // destructive project action, and its copy must distinguish what is removed here from what
+ // continues to exist elsewhere (a relay tab: only this machine's view; local/SSH: the sessions
+ // end, the folder and its .nodeterm/project.json stay).
+ const requestDeleteClosed = useCallback(
+ (id: string) => {
+ const project = useProjects.getState().getProject(id)
+ if (!project) return
+ setDeleteTarget({ id, ...deleteConfirmCopy(project) })
+ },
+ [setDeleteTarget]
+ )
+
+ // Live `nt-*` session counts for the start screen's "Recently closed" badges — the visibility
+ // half of issue #442 ("something that tells me parked sessions exist"). ONE on-demand LOCAL
+ // sweep per welcome-screen appearance (and per closed-list change), never a timer — the same
+ // cadence discipline as the session-memory panel, and the local sweep is the cheap leg. Uses
+ // `window.nodeTerminal` directly (not the active session's api): the badges describe THIS
+ // machine, whatever tab happens to be active. `ok:false`/a rejected call ⇒ no badges — a failed
+ // sweep must never render as "0 sessions". An SSH project's sessions live on its host and are
+ // deliberately not claimed by this local count (its close dialog already said what it parks).
+ const welcomeVisible = !hasProjects || welcomeOpen
+ const [closedSessionBadges, setClosedSessionBadges] = useState<Record<string, number> | null>(
+ null
+ )
+ useEffect(() => {
+ if (!welcomeVisible || closedProjects.length === 0) {
+ setClosedSessionBadges(null)
+ return
+ }
+ let stale = false
+ void window.nodeTerminal.sessionMemory
+ .read({ remote: false })
+ .then((r) => {
+ if (stale) return
+ setClosedSessionBadges(r.ok ? closedSessionCounts(r.rows, closedProjects) : null)
+ })
+ .catch(() => {
+ if (!stale) setClosedSessionBadges(null)
+ })
+ return () => {
+ stale = true
+ }
+ }, [welcomeVisible, closedProjects])
+
const now = useMemo(() => Date.now(), [transcriptHits])
const transcriptCommands = useMemo<Command[]>(
() =>
@@ -11292,8 +11443,9 @@ export function Canvas() {
color: p.color,
icon: p.icon
}))}
+ sessionCounts={closedSessionBadges ?? undefined}
onReopen={reopenProject}
- onDeleteClosed={deleteProject}
+ onDeleteClosed={requestDeleteClosed}
onClose={hasProjects ? () => setWelcomeOpen(false) : undefined}
overBoard={kanbanOpen}
/>
@@ -11543,6 +11695,44 @@ export function Canvas() {
/>
)}
+ {closeTarget &&
+ (() => {
+ const copy = closeConfirmCopy(closeTarget.name, closeTarget.count)
+ return (
+ <ConfirmDialog
+ message={copy.message}
+ // Ending is the exception, parking the rule: the checkbox defaults OFF, and only a
+ // checked box flips the confirm into the destructive label + danger styling (which
+ // also parks autofocus on Cancel — see ConfirmDialog).
+ option={{
+ label: copy.optionLabel,
+ checked: closeTarget.end,
+ onChange: (end) => setCloseTargetState((t) => (t ? { ...t, end } : t))
+ }}
+ confirmLabel={closeTarget.end ? copy.confirmEnd : copy.confirmKeep}
+ danger={closeTarget.end}
+ onConfirm={() => {
+ performCloseProject(closeTarget.id, closeTarget.end)
+ setCloseTarget(null)
+ }}
+ onCancel={() => setCloseTarget(null)}
+ />
+ )
+ })()}
+
+ {deleteTarget && (
+ <ConfirmDialog
+ message={deleteTarget.message}
+ confirmLabel={deleteTarget.confirmLabel}
+ danger={deleteTarget.danger}
+ onConfirm={() => {
+ deleteProject(deleteTarget.id)
+ setDeleteTarget(null)
+ }}
+ onCancel={() => setDeleteTarget(null)}
+ />
+ )}
+
<UpgradeDialog />
{remotePicker && (
diff --git a/src/renderer/components/WelcomeScreen.test.tsx b/src/renderer/components/WelcomeScreen.test.tsx
new file mode 100644
index 000000000..360803865
--- /dev/null
+++ b/src/renderer/components/WelcomeScreen.test.tsx
@@ -0,0 +1,64 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { WelcomeScreen } from './WelcomeScreen'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const noop = (): void => {}
+
+describe('WelcomeScreen — Recently closed session badges (issue #442)', () => {
+ let root: Root
+ let host: HTMLElement
+
+ beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ })
+
+ afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ })
+
+ const render = async (el: React.ReactElement): Promise<void> => {
+ await act(async () => root.render(el))
+ }
+
+ const base = {
+ onNewProject: noop,
+ onOpenFolder: noop,
+ onCloneRepo: noop,
+ onConnectSsh: noop,
+ closedProjects: [
+ { id: 'p1', name: 'Web', cwd: '/w' },
+ { id: 'p2', name: 'API', cwd: '/a' }
+ ]
+ }
+
+ it('shows a live-session badge only for projects the sweep counted', async () => {
+ await render(<WelcomeScreen {...base} sessionCounts={{ p1: 3 }} />)
+ const badges = host.querySelectorAll('.welcome__recent-sessions')
+ expect(badges).toHaveLength(1)
+ expect(badges[0].textContent).toBe('3 running')
+ // The tooltip carries what the badge means — parked sessions still running on this machine.
+ expect(badges[0].getAttribute('title')).toContain('still running on this machine')
+ })
+
+ it('shows NO badge when counts were not measured — a failed sweep is not "0"', async () => {
+ await render(<WelcomeScreen {...base} />)
+ expect(host.querySelectorAll('.welcome__recent-sessions')).toHaveLength(0)
+ })
+
+ it('the × routes through onDeleteClosed without also triggering the row reopen', async () => {
+ const onReopen = vi.fn()
+ const onDeleteClosed = vi.fn()
+ await render(<WelcomeScreen {...base} onReopen={onReopen} onDeleteClosed={onDeleteClosed} />)
+ const del = host.querySelector('.welcome__recent-del') as HTMLButtonElement
+ act(() => del.click())
+ expect(onDeleteClosed).toHaveBeenCalledWith('p1')
+ expect(onReopen).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/components/WelcomeScreen.tsx b/src/renderer/components/WelcomeScreen.tsx
index e9f162b1e..0e414d42a 100644
--- a/src/renderer/components/WelcomeScreen.tsx
+++ b/src/renderer/components/WelcomeScreen.tsx
@@ -10,6 +10,12 @@ interface WelcomeScreenProps {
onConnectSsh: () => void
/** Closed projects that can be reopened (id + display name + folder + icon/color). */
closedProjects?: { id: string; name: string; cwd?: string; color?: string; icon?: ProjectIcon }[]
+ /**
+ * LIVE local `nt-*` session count per closed project id (one on-demand sweep — see Canvas).
+ * A closed project parks its sessions invisibly (issue #442); this badge is what says they
+ * exist. Absent map or missing id = NOT MEASURED, so no badge — never a claimed "0".
+ */
+ sessionCounts?: Record<string, number>
/** Reopen a closed project (restores its nodes + sessions). */
onReopen?: (id: string) => void
/** Permanently delete a closed project (ends its tmux sessions). */
@@ -34,6 +40,7 @@ export function WelcomeScreen({
onCloneRepo,
onConnectSsh,
closedProjects = [],
+ sessionCounts,
onReopen,
onDeleteClosed,
onClose,
@@ -157,6 +164,16 @@ export function WelcomeScreen({
/>
<span className="welcome__recent-name">{p.name}</span>
{p.cwd && <span className="welcome__recent-path">{p.cwd}</span>}
+ {(sessionCounts?.[p.id] ?? 0) > 0 && (
+ <span
+ className="welcome__recent-sessions"
+ title={`${sessionCounts![p.id]} tmux session${
+ sessionCounts![p.id] === 1 ? ' from this project is' : 's from this project are'
+ } still running on this machine. Reopen the project to pick them up, or × to delete it and end them.`}
+ >
+ {sessionCounts![p.id]} running
+ </span>
+ )}
{onDeleteClosed && (
<button
className="welcome__recent-del"
diff --git a/src/renderer/lib/projectCloseSessions.test.ts b/src/renderer/lib/projectCloseSessions.test.ts
new file mode 100644
index 000000000..0fad0df5d
--- /dev/null
+++ b/src/renderer/lib/projectCloseSessions.test.ts
@@ -0,0 +1,137 @@
+import { describe, it, expect } from 'vitest'
+import {
+ closeConfirmCopy,
+ closedSessionCounts,
+ deleteConfirmCopy,
+ planProjectClose,
+ terminalNodeIds
+} from './projectCloseSessions'
+
+const project = (opts: {
+ name?: string
+ nodes?: { id: string; kind?: string }[]
+ remote?: boolean
+ ssh?: { label?: string; user?: string; host?: string }
+}): any => ({
+ name: opts.name ?? 'Web',
+ remote: opts.remote,
+ ssh: opts.ssh ? { server: { user: 'u', host: 'h', ...opts.ssh }, remoteCwd: '/srv' } : undefined,
+ nodes: (opts.nodes ?? []).map((n) => ({
+ id: n.id,
+ kind: n.kind,
+ title: n.id,
+ position: { x: 0, y: 0 }
+ }))
+})
+
+describe('terminalNodeIds / planProjectClose', () => {
+ it('counts terminal-kind nodes only — the exact set the end action addresses', () => {
+ const p = project({
+ nodes: [
+ { id: 't1', kind: 'terminal' },
+ { id: 't2', kind: 'terminal' },
+ { id: 's1', kind: 'sticky' },
+ { id: 'g1', kind: 'group' }
+ ]
+ })
+ expect(terminalNodeIds(p)).toEqual(['t1', 't2'])
+ expect(planProjectClose(p)).toEqual({ kind: 'confirm', sessionCount: 2 })
+ })
+
+ it('a missing kind defaults to terminal — the serializer backward-compat rule', () => {
+ expect(terminalNodeIds(project({ nodes: [{ id: 'legacy' }] }))).toEqual(['legacy'])
+ })
+
+ it('closes silently when there is nothing to tell the user about', () => {
+ expect(planProjectClose(undefined)).toEqual({ kind: 'silent' })
+ expect(planProjectClose(project({ nodes: [] }))).toEqual({ kind: 'silent' })
+ expect(planProjectClose(project({ nodes: [{ id: 's', kind: 'sticky' }] }))).toEqual({
+ kind: 'silent'
+ })
+ })
+
+ it('a relay tab closes silently — its sessions belong to the host machine', () => {
+ expect(
+ planProjectClose(project({ remote: true, nodes: [{ id: 't1', kind: 'terminal' }] }))
+ ).toEqual({ kind: 'silent' })
+ })
+})
+
+describe('closeConfirmCopy', () => {
+ it('names the count in the message, the option and the destructive confirm label', () => {
+ const c = closeConfirmCopy('Web', 3)
+ expect(c.message).toContain('Close “Web”?')
+ expect(c.message).toContain('3 terminal sessions will keep running')
+ expect(c.message).toContain('Recently closed')
+ expect(c.optionLabel).toContain('End its 3 sessions too')
+ expect(c.confirmKeep).toBe('Close')
+ expect(c.confirmEnd).toBe('Close & end 3 sessions')
+ })
+
+ it('reads naturally in the singular', () => {
+ const c = closeConfirmCopy('Web', 1)
+ expect(c.message).toContain('1 terminal session will keep')
+ expect(c.optionLabel).toContain('End its session too')
+ expect(c.confirmEnd).toBe('Close & end 1 session')
+ })
+})
+
+describe('deleteConfirmCopy', () => {
+ it('local delete: names the sessions it ends and what stays on disk', () => {
+ const c = deleteConfirmCopy(project({ nodes: [{ id: 't1' }, { id: 't2' }] }))
+ expect(c.message).toContain('Delete “Web”?')
+ expect(c.message).toContain('ends its 2 terminal sessions and removes the project')
+ expect(c.message).toContain('.nodeterm/project.json) is not deleted')
+ expect(c.danger).toBe(true)
+ expect(c.confirmLabel).toBe('Delete')
+ })
+
+ it('ssh delete: names the host the sessions end on (label preferred)', () => {
+ const c = deleteConfirmCopy(project({ nodes: [{ id: 't1' }], ssh: { label: 'prod' } }))
+ expect(c.message).toContain('ends its 1 terminal session on prod')
+ expect(c.message).toContain('The folder on the server')
+ const bare = deleteConfirmCopy(project({ nodes: [{ id: 't1' }], ssh: {} }))
+ expect(bare.message).toContain('on u@h')
+ })
+
+ it('no sessions: drops the session clause instead of claiming "0 sessions"', () => {
+ const c = deleteConfirmCopy(project({ nodes: [{ id: 's', kind: 'sticky' }] }))
+ expect(c.message).toContain('Delete “Web”? This removes the project from nodeterm.')
+ expect(c.message).not.toContain('session')
+ })
+
+ it('relay tab: says it removes only the local view and nothing is destroyed', () => {
+ // The #442 follow-up: "Delete" on a host-backed tab drops the reconnect lever, so the next
+ // connect re-adopts the host's project. The copy must carry that, and the dialog must not
+ // wear danger styling for an action that destroys nothing.
+ const c = deleteConfirmCopy(project({ remote: true, nodes: [{ id: 't1' }] }))
+ expect(c.message).toContain('removing it only closes the view here')
+ expect(c.message).toContain('reconnecting will bring the project back')
+ expect(c.confirmLabel).toBe('Remove view')
+ expect(c.danger).toBe(false)
+ })
+})
+
+describe('closedSessionCounts', () => {
+ const rows = (...ids: string[]): { nodeId: string }[] => ids.map((nodeId) => ({ nodeId }))
+
+ it('counts live rows per closed project and omits projects with none', () => {
+ const closed = [
+ { id: 'p1', nodes: [{ id: 'a' }, { id: 'b' }] },
+ { id: 'p2', nodes: [{ id: 'c' }] }
+ ] as any
+ expect(closedSessionCounts(rows('a', 'b', 'x'), closed)).toEqual({ p1: 2 })
+ })
+
+ it('first project owning a node id wins — same rule as resolveSessionRows', () => {
+ const closed = [
+ { id: 'p1', nodes: [{ id: 'a' }] },
+ { id: 'p2', nodes: [{ id: 'a' }] }
+ ] as any
+ expect(closedSessionCounts(rows('a'), closed)).toEqual({ p1: 1 })
+ })
+
+ it('no rows → empty map (the caller renders no badge, never "0")', () => {
+ expect(closedSessionCounts([], [{ id: 'p1', nodes: [{ id: 'a' }] }] as any)).toEqual({})
+ })
+})
diff --git a/src/renderer/lib/projectCloseSessions.ts b/src/renderer/lib/projectCloseSessions.ts
new file mode 100644
index 000000000..8dcbfcb49
--- /dev/null
+++ b/src/renderer/lib/projectCloseSessions.ts
@@ -0,0 +1,149 @@
+// Closing/deleting a project vs. the tmux sessions it parks (issue #442).
+//
+// `closeProject` is deliberately NON-destructive — the tab hides, the project stays on disk, and
+// its tmux sessions keep running so reopening picks them up warm. That contract is kept. What was
+// missing is that nothing SAID so at the moment of the action, and nothing afterwards showed that
+// the parked sessions exist: a closed project is filtered out of the tab bar and the sessions
+// sidebar, so "close" read like cleanup while actually meaning "hide, and keep running".
+//
+// This module is the pure half of the fix:
+// - `planProjectClose` decides whether closing needs a confirm (and how many sessions it must
+// name), with an opt-in "end its sessions too" — the default stays parking.
+// - `deleteConfirmCopy` words the permanent delete (the "Recently closed" ×), distinguishing
+// what is removed HERE from what continues to exist elsewhere (a relay tab is only a view of
+// another machine's project; an SSH/local delete never deletes the folder or its
+// .nodeterm/project.json).
+// - `closedSessionCounts` maps a live session sweep onto closed projects for the start screen's
+// per-row badge.
+//
+// ONE definition of "N sessions" on the dialogs: the project's TERMINAL-kind nodes — exactly the
+// set the action addresses (`transport.destroy` per node id, idempotent on an already-dead
+// session). Working, idle, hibernated and already-exited all count, because the action tells each
+// of them to stop; a liveness-verified count here would let the button and the action disagree
+// the moment a session exits between the count and the confirm. The start-screen badge is the
+// OPPOSITE: it reports sessions that exist, so it derives from a live sweep and never from node
+// counts — and `ok:false` is not "0 sessions" (the session-memory rule), so no sweep ⇒ no badge.
+
+import type { Project, SessionMemoryRow } from '@shared/types'
+
+type ProjectLike = Pick<Project, 'name' | 'nodes' | 'remote' | 'ssh'>
+
+/** The node ids whose tmux sessions a close-with-end / delete addresses (terminal-kind only). */
+export function terminalNodeIds(project: Pick<Project, 'nodes'>): string[] {
+ return (project.nodes ?? [])
+ .filter((n) => (n.kind ?? 'terminal') === 'terminal')
+ .map((n) => n.id)
+}
+
+export type ProjectClosePlan = { kind: 'silent' } | { kind: 'confirm'; sessionCount: number }
+
+/**
+ * Does closing this project need a confirm? Silent (today's exact behavior) when there is nothing
+ * to tell the user about:
+ * - unknown project — nothing to close;
+ * - a RELAY tab (`project.remote`) — a live view of another machine's project. Its sessions are
+ * the host's, closing only drops this machine's connection, and offering to "end" them from
+ * here would promise a kill on a machine this action does not reach;
+ * - no terminal nodes — there are no sessions to park or end, and a dialog would decide nothing.
+ */
+export function planProjectClose(project: ProjectLike | undefined): ProjectClosePlan {
+ if (!project || project.remote) return { kind: 'silent' }
+ const count = terminalNodeIds(project).length
+ return count === 0 ? { kind: 'silent' } : { kind: 'confirm', sessionCount: count }
+}
+
+export interface CloseConfirmCopy {
+ message: string
+ /** The opt-in checkbox. Ending is the exception — parking stays the default. */
+ optionLabel: string
+ /** Confirm label while the checkbox is UNCHECKED (the non-destructive default). */
+ confirmKeep: string
+ /** Confirm label while the checkbox is CHECKED (destructive — the dialog flips to danger). */
+ confirmEnd: string
+}
+
+const plural = (n: number): string => (n === 1 ? '' : 's')
+
+export function closeConfirmCopy(name: string, sessionCount: number): CloseConfirmCopy {
+ const n = sessionCount
+ return {
+ message:
+ `Close “${name}”? Its ${n} terminal session${plural(n)} will keep running in the ` +
+ `background — reopen the project from the start screen's “Recently closed” list to pick ` +
+ `them up again.`,
+ optionLabel: `End its ${n === 1 ? 'session' : `${n} sessions`} too (stops tmux; anything running in them, agents included, is interrupted)`,
+ confirmKeep: 'Close',
+ confirmEnd: `Close & end ${n} session${plural(n)}`
+ }
+}
+
+export interface DeleteConfirmCopy {
+ message: string
+ confirmLabel: string
+ /** A relay-view removal is not destructive — nothing anywhere is deleted or stopped. */
+ danger: boolean
+}
+
+/** How the SSH host is named in the delete copy — the saved label when there is one. */
+function sshHostLabel(project: ProjectLike): string {
+ const s = project.ssh?.server
+ if (!s) return ''
+ return s.label || `${s.user}@${s.host}`
+}
+
+export function deleteConfirmCopy(project: ProjectLike): DeleteConfirmCopy {
+ const name = project.name
+ if (project.remote) {
+ // The issue-#442 follow-up case: "Delete" on a host-backed tab sounds like removal but only
+ // drops this machine's view — and with the tab gone, the next connect re-adopts the host's
+ // project (a first connect again), so it all comes back. Say exactly that.
+ return {
+ message:
+ `Remove “${name}”? This tab is a live view of a project on another machine — removing ` +
+ `it only closes the view here. Nothing is deleted on the host, its sessions keep ` +
+ `running, and reconnecting will bring the project back.`,
+ confirmLabel: 'Remove view',
+ danger: false
+ }
+ }
+ const n = terminalNodeIds(project).length
+ const sessions =
+ n === 0
+ ? ''
+ : project.ssh
+ ? `ends its ${n} terminal session${plural(n)} on ${sshHostLabel(project)} and `
+ : `ends its ${n} terminal session${plural(n)} and `
+ const where = project.ssh ? 'on the server' : 'on disk'
+ return {
+ message:
+ `Delete “${name}”? This ${sessions}removes the project from nodeterm. The folder ${where} ` +
+ `(including .nodeterm/project.json) is not deleted.`,
+ confirmLabel: 'Delete',
+ danger: true
+ }
+}
+
+/**
+ * Per-closed-project count of LIVE local `nt-*` sessions, for the start screen's badge. Rows come
+ * from one on-demand local `sessionMemory.read` (this machine only — an SSH project's sessions
+ * live on its host and are not claimed here). First project owning a node id wins, matching
+ * `resolveSessionRows`. Only ids > 0 are returned, so `counts[id]` is truthy exactly when a badge
+ * should show.
+ */
+export function closedSessionCounts(
+ rows: readonly Pick<SessionMemoryRow, 'nodeId'>[],
+ closedProjects: readonly Pick<Project, 'id' | 'nodes'>[]
+): Record<string, number> {
+ const owner = new Map<string, string>()
+ for (const p of closedProjects) {
+ for (const n of p.nodes ?? []) {
+ if (!owner.has(n.id)) owner.set(n.id, p.id)
+ }
+ }
+ const counts: Record<string, number> = {}
+ for (const row of rows) {
+ const id = owner.get(row.nodeId)
+ if (id) counts[id] = (counts[id] ?? 0) + 1
+ }
+ return counts
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index a9156ec99..ad696e3e8 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -2833,6 +2833,19 @@ body,
flex: 1;
}
+/* Live-session badge on a "Recently closed" row (issue #442): a closed project keeps its tmux
+ sessions running, and this is the one place that says so. Green = the RUNNING vocabulary. */
+.welcome__recent-sessions {
+ flex: none;
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ padding: 1px 7px;
+ border-radius: 999px;
+ color: var(--success);
+ background: rgba(48, 209, 88, 0.14);
+}
+
.welcome__recent-del {
margin-left: auto;
flex: none;