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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(windows): sessionDetails host feature — per-session pid, subscribers, output clock
review07ebcaac8ffa
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex d258adf6a..a9b302c36 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -489,6 +489,9 @@ anything else. Board-level fields survive every transform — `pullLinks` is oneopt into retires a live session. Add the capability to `SESSION_HOST_FEATURES`, send it only tosockets that listed it (the `geometry` push of issue #914 is the worked example), and pin thatagainst the real bundled host as `session-host/geometry-host.test.ts` does.+ The same goes for a richer REPLY: `listSessions`' per-session rows ride the `sessionDetails`+ feature, and a host that never negotiated it answers `{names}` — which a consumer must read as+ "named, not described", never as "detached" or "no processes".- **Finding a Windows executable is not the same as being able to spawn it.** A PATH lookup maycorrectly resolve an npm CLI to `<name>.cmd`, but Node's `execFile`/`spawn` cannot execute thatdiff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.tsindex 821497f6a..7682315d8 100644--- a/src/core/session-host-backend.ts+++ b/src/core/session-host-backend.ts@@ -12,7 +12,8 @@ import {SessionHostClient,SessionHostProtocolCompatibilityError,type HostShutdownOutcome,- type HostUpdateInspection+ type HostUpdateInspection,+ type SessionHostListing} from './session-host-client'import { SessionHostPty } from './session-host-pty'import { ensureStagedHostRuntime } from './session-host-runtime'@@ -150,12 +151,14 @@ export async function sessionHostKillSession(reserveReplacement?: booleanrequireV2?: booleanexpectedAbsent?: boolean+ expectedGeneration?: string} = {}): Promise<void> {return getClient().killSession(name, options)}export { SessionHostProtocolCompatibilityError }+export type { SessionHostListing }/** `tmux has-session`'s equivalent — currently unused by the create path (which gets `fresh`* straight from the real attach-or-create round trip instead, via `SessionHostPty.ready`) but@@ -171,6 +174,13 @@ export async function sessionHostListSessions(): Promise<string[]> {return getClient().listSessions()}+/** The observability read — pid, subscribers, output clock and generation per session — for the+ * session reaper, the session-memory panel and dev-server ports. Never launches a host; `null` is+ * a FAILED read, never "no sessions" (see `SessionHostListing`). */+export async function sessionHostListSessionsDetailed(): Promise<SessionHostListing | null> {+ return getClient().listSessionsDetailed()+}+/** Prepare-for-update (issue #829): what the running host holds, without ever launching one. */export async function sessionHostInspectForUpdate(): Promise<HostUpdateInspection> {return getClient().inspectForUpdate()diff --git a/src/core/session-host-client-details.test.ts b/src/core/session-host-client-details.test.tsnew file mode 100644index 000000000..550cb9aa7--- /dev/null+++ b/src/core/session-host-client-details.test.ts@@ -0,0 +1,195 @@+// The client half of `sessionDetails` (Windows parity: session reaper, session-memory panel,+// dev-server ports). Drives the real SessionHostClient against a fake host over a real socket. The+// rules: the read never LAUNCHES a host; a failed read is `null`, never an empty listing; a host+// that did not negotiate the feature names its sessions without describing them (`sessions: null`);+// malformed rows are dropped, never trusted; and a kill planned from a row carries that row's+// generation.+import fs from 'fs'+import net from 'net'+import os from 'os'+import path from 'path'+import { spawnSync } from 'child_process'+import { afterEach, describe, expect, it } from 'vitest'+import { sessionHostPaths } from '../session-host/paths'+import {+ SESSION_HOST_PROTOCOL_VERSION,+ LineFramer,+ encodeFrame,+ type SessionHostRequest+} from '../session-host/protocol'+import { SessionHostClient } from './session-host-client'++const servers = new Set<net.Server>()+const sockets = new Set<net.Socket>()+const dirs = new Set<string>()++afterEach(() => {+ for (const s of sockets) s.destroy()+ sockets.clear()+ for (const s of servers) s.close()+ servers.clear()+ for (const d of dirs) fs.rmSync(d, { recursive: true, force: true })+ dirs.clear()+})++function fixture(publish: boolean): { userDataDir: string; endpoint: string } {+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-details-client-'))+ dirs.add(userDataDir)+ const paths = sessionHostPaths(userDataDir)+ if (publish) {+ fs.writeFileSync(paths.tokenPath, 'a'.repeat(64))+ fs.writeFileSync(+ paths.statePath,+ JSON.stringify({+ pid: spawnSync(process.execPath, ['-e', '']).pid,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: Date.now(),+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION+ })+ )+ }+ return { userDataDir, endpoint: paths.endpoint }+}++const GEN_A = 'gen-aaaaaaaa'+const GEN_B = 'gen-bbbbbbbb'++async function fakeHost(+ endpoint: string,+ opts: { details: boolean; listReply?: Record<string, unknown> }+): Promise<SessionHostRequest[]> {+ const requests: SessionHostRequest[] = []+ const server = net.createServer((socket) => {+ sockets.add(socket)+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const req of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ requests.push(req)+ const reply = (body: Record<string, unknown>): void => {+ socket.write(encodeFrame({ id: req.id, ...body }))+ }+ if (req.cmd === 'hello') {+ const asked = (req as { features?: string[] }).features ?? []+ reply({+ ok: true,+ result: {+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,+ features: opts.details ? asked : asked.filter((f) => f !== 'sessionDetails')+ }+ })+ } else if (req.cmd === 'listSessions') {+ reply(+ opts.listReply ?? {+ ok: true,+ result: {+ names: ['nt-a', 'nt-b'],+ ...(opts.details+ ? {+ sessions: [+ { name: 'nt-a', pid: 11, subscribers: 0, lastOutputMs: 1000, createdMs: 900, generation: GEN_A },+ { name: 'nt-b', pid: 12, subscribers: 2, lastOutputMs: 2000, createdMs: 900, generation: GEN_B }+ ]+ }+ : {})+ }+ }+ )+ } else {+ reply({ ok: true, result: {} })+ }+ }+ })+ })+ servers.add(server)+ await new Promise<void>((resolve) => server.listen(endpoint, resolve))+ return requests+}++describe('SessionHostClient.listSessionsDetailed', () => {+ it('answers "no host" without launching one when nothing is published', async () => {+ const { userDataDir } = fixture(false)+ // No bundle paths: a launch attempt would throw instead of answering.+ const client = new SessionHostClient({ userDataDir })+ await expect(client.listSessionsDetailed()).resolves.toEqual({ running: false, names: [], sessions: [] })+ expect(fs.existsSync(sessionHostPaths(userDataDir).statePath)).toBe(false)+ })++ it('negotiates the feature and returns the validated rows', async () => {+ const { userDataDir, endpoint } = fixture(true)+ const requests = await fakeHost(endpoint, { details: true })+ const client = new SessionHostClient({ userDataDir })+ const listing = await client.listSessionsDetailed()+ expect(listing).toEqual({+ running: true,+ names: ['nt-a', 'nt-b'],+ sessions: [+ { name: 'nt-a', pid: 11, subscribers: 0, lastOutputMs: 1000, createdMs: 900, generation: GEN_A },+ { name: 'nt-b', pid: 12, subscribers: 2, lastOutputMs: 2000, createdMs: 900, generation: GEN_B }+ ]+ })+ const hello = requests.find((r) => r.cmd === 'hello') as { features?: string[] }+ expect(hello.features).toContain('sessionDetails')+ })++ it('a host without the feature names its sessions but does not describe them', async () => {+ const { userDataDir, endpoint } = fixture(true)+ await fakeHost(endpoint, { details: false })+ const client = new SessionHostClient({ userDataDir })+ await expect(client.listSessionsDetailed()).resolves.toEqual({+ running: true,+ names: ['nt-a', 'nt-b'],+ sessions: null+ })+ })++ it('drops malformed rows and rows for names the host did not list', async () => {+ const { userDataDir, endpoint } = fixture(true)+ const good = { name: 'nt-a', pid: 11, subscribers: 0, lastOutputMs: 1, createdMs: 1, generation: GEN_A }+ await fakeHost(endpoint, {+ details: true,+ listReply: {+ ok: true,+ result: {+ names: ['nt-a', 'nt-b'],+ sessions: [+ good,+ { ...good, name: 'nt-b', subscribers: -1 },+ { ...good, name: 'nt-b', pid: 0 },+ { ...good, name: 'nt-b', generation: 'x' },+ { ...good, name: 'nt-b', lastOutputMs: 'soon' },+ { ...good, name: 'nt-ghost' },+ null+ ]+ }+ }+ })+ const client = new SessionHostClient({ userDataDir })+ expect((await client.listSessionsDetailed())?.sessions).toEqual([good])+ })++ it('a refused or malformed reply is null — never an empty listing', async () => {+ for (const listReply of [+ { ok: false, error: 'boom' },+ { ok: true, result: { names: 'nt-a' } },+ { ok: true, result: {} }+ ]) {+ const { userDataDir, endpoint } = fixture(true)+ await fakeHost(endpoint, { details: true, listReply })+ const client = new SessionHostClient({ userDataDir })+ await expect(client.listSessionsDetailed()).resolves.toBeNull()+ }+ })++ it('a kill planned from a listing carries that row\'s generation', async () => {+ const { userDataDir, endpoint } = fixture(true)+ const requests = await fakeHost(endpoint, { details: true })+ const client = new SessionHostClient({ userDataDir })+ await client.listSessionsDetailed()+ await client.killSession('nt-a', { expectedGeneration: GEN_A })+ const kill = requests.find((r) => r.cmd === 'killSession') as { expectedGeneration?: string }+ expect(kill.expectedGeneration).toBe(GEN_A)+ // No existence probe was needed: the caller already observed the generation.+ expect(requests.some((r) => r.cmd === 'hasSession')).toBe(false)+ })+})diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.tsindex 451882439..aefda8b53 100644--- a/src/core/session-host-client.ts+++ b/src/core/session-host-client.ts@@ -35,6 +35,7 @@ import {type KillSessionResult,type ExecuteLaunchResult,type ListSessionsResult,+ type SessionHostSessionDetail,type ShutdownResult} from '../session-host/protocol'import { resolveSessionHostScript, spawnSessionHost } from './session-host-launcher'@@ -68,6 +69,57 @@ export type HostUpdateInspection =| { running: false }| { running: true; sessions: string[]; shutdown: boolean }+/**+ * What the running host holds, for the observability surfaces (session reaper, session-memory+ * panel, dev-server ports). `null` from `listSessionsDetailed` is the FAILED read — never this+ * shape with no sessions, because a failed read is never evidence of absence.+ * - `running: false` — no host is published, so there are no sessions. An ANSWER.+ * - `sessions: null` — a host that predates `sessionDetails` can name its sessions but not+ * describe them; consumers must treat every name as unmeasured / not reapable.+ * - otherwise `sessions` holds a validated row per live generation; a name without a row is not+ * described (retiring, or a malformed row dropped here) and is treated the same way.+ */+export interface SessionHostListing {+ running: boolean+ names: string[]+ sessions: SessionHostSessionDetail[] | null+}++const GENERATION_RE = /^[A-Za-z0-9_-]{8,128}$/++/** Keep only rows whose every field is the type the consumers rely on. A malformed row is dropped+ * — its session then reads as undescribed, never as detached or empty. */+function validSessionDetails(raw: unknown): SessionHostSessionDetail[] {+ if (!Array.isArray(raw)) return []+ const out: SessionHostSessionDetail[] = []+ for (const r of raw) {+ if (!r || typeof r !== 'object') continue+ const o = r as Record<string, unknown>+ if (+ typeof o.name !== 'string' ||+ !Number.isSafeInteger(o.pid) ||+ (o.pid as number) <= 0 ||+ !Number.isSafeInteger(o.subscribers) ||+ (o.subscribers as number) < 0 ||+ !Number.isFinite(o.lastOutputMs) ||+ !Number.isFinite(o.createdMs) ||+ typeof o.generation !== 'string' ||+ !GENERATION_RE.test(o.generation)+ ) {+ continue+ }+ out.push({+ name: o.name,+ pid: o.pid as number,+ subscribers: o.subscribers as number,+ lastOutputMs: o.lastOutputMs as number,+ createdMs: o.createdMs as number,+ generation: o.generation+ })+ }+ return out+}+export type HostShutdownOutcome =| { kind: 'no-host' }| { kind: 'unsupported' }@@ -300,6 +352,9 @@ export class SessionHostClient {* ask the host to end every session and exit. An older host lacks it, and the app then falls* back to the manual steps — never to killing the host itself. */private hostShutdownFeature = false+ /** The current connection negotiated `sessionDetails`: `listSessions` then carries per-session+ * rows (pid, subscribers, output clock, generation) for the observability surfaces. */+ private hostSessionDetailsFeature = false/** The pid the host published in its state file for the current connection. Read only to* confirm a shutdown actually ended the process. */private hostPid: number | null = null@@ -609,6 +664,7 @@ export class SessionHostClient {let protocolVersion: 1 | 2 | null = nulllet geometryEvents = falselet shutdownFeature = false+ let sessionDetailsFeature = falseconst finish = (ok: boolean, trailing: SessionHostFrame[] = []): void => {if (settled) returnsettled = true@@ -623,6 +679,7 @@ export class SessionHostClient {return}this.hostShutdownFeature = shutdownFeature+ this.hostSessionDetailsFeature = sessionDetailsFeaturethis.hostPid = Number.isInteger(identity.state.pid) ? identity.state.pid : nullthis.attachSocket(socket, protocolVersion, geometryEvents)for (const frame of trailing) this.handleFrame(socket, frame)@@ -721,6 +778,7 @@ export class SessionHostClient {const features = (frame.result as HelloResult | undefined)?.featuresgeometryEvents = Array.isArray(features) && features.includes('geometry')shutdownFeature = Array.isArray(features) && features.includes('shutdown')+ sessionDetailsFeature = Array.isArray(features) && features.includes('sessionDetails')finish(true, frames.slice(index + 1))} else {failHandshake(new Error(`session-host hello rejected: ${frame.error}`))@@ -1702,6 +1760,10 @@ export class SessionHostClient {reserveReplacement?: booleanrequireV2?: booleanexpectedAbsent?: boolean+ /** The generation the caller OBSERVED (a `listSessionsDetailed` row). Wins over anything+ * this client remembers, so a kill planned from a listing can never end a same-name+ * successor created after it — the host answers "already gone" instead. */+ expectedGeneration?: string} = {}): Promise<void> {const reserveReplacement = options.reserveReplacement === true@@ -1733,7 +1795,8 @@ export class SessionHostClient {const state = this.sessions.get(name)const identity: KillOperationIdentity = knownIdentity ?? {operationId: randomUUID(),- expectedGeneration: state?.generation ?? this.sessionGenerations.get(name),+ expectedGeneration:+ options.expectedGeneration ?? state?.generation ?? this.sessionGenerations.get(name),reserveReplacement,requireV2,expectedAbsent@@ -1983,4 +2046,35 @@ export class SessionHostClient {const result = await this.request<ListSessionsResult>({ cmd: 'listSessions' })return result.names}++ /**+ * The observability read (see `SessionHostListing`). Like `inspectForUpdate` it never launches a+ * host when nothing is published — a session reaper, a memory panel or a ports chip asking a+ * question must not start the process whose sessions it is asking about. Every failure (a+ * request that threw, a reply without `names`) is `null`, never an empty listing.+ */+ async listSessionsDetailed(): Promise<SessionHostListing | null> {+ try {+ const connected = !!this.socket && !this.socket.destroyed+ if (!connected) {+ const paths = sessionHostPaths(this.deps.userDataDir)+ const identity = readExistingSessionHostIdentity(paths.statePath, {+ expectedEndpoint: paths.endpoint,+ expectedTokenPath: paths.tokenPath+ })+ if (identity.kind === 'absent') return { running: false, names: [], sessions: [] }+ }+ const result = await this.request<ListSessionsResult>({ cmd: 'listSessions' })+ if (!result || !Array.isArray(result.names) || !result.names.every((n) => typeof n === 'string')) {+ return null+ }+ // Read AFTER the request: `request()` is what establishes the connection on a cold client.+ const sessions = this.hostSessionDetailsFeature && Array.isArray(result.sessions)+ ? validSessionDetails(result.sessions).filter((row) => result.names.includes(row.name))+ : null+ return { running: true, names: result.names, sessions }+ } catch {+ return null+ }+ }}diff --git a/src/session-host/host.ts b/src/session-host/host.tsindex a06d1a9d0..b5157479b 100644--- a/src/session-host/host.ts+++ b/src/session-host/host.ts@@ -31,6 +31,7 @@ import {type CaptureResult,type KillSessionResult,type ListSessionsResult,+ type SessionHostSessionDetail,type ShutdownResult} from './protocol'import { HostSession } from './session'@@ -342,6 +343,9 @@ async function main(): Promise<void> {* session and exit (issue #829): the command is destructive, so an app build that never asked* for it can never trigger it by accident. */const shutdownSockets = new WeakSet<net.Socket>()+ /** Connections that negotiated `sessionDetails`: only these get per-session rows (pid,+ * subscribers, output clock, generation) on `listSessions`. An older client reads `{names}`. */+ const sessionDetailsSockets = new WeakSet<net.Socket>()/** Set while a `shutdown` is ending sessions. New sessions (attach / attachExisting / launches)* are refused for its duration; cleared again only if the shutdown could not end everything. */let shuttingDown = false@@ -379,6 +383,7 @@ async function main(): Promise<void> {: []if (features.includes('geometry')) geometrySockets.add(socket)if (features.includes('shutdown')) shutdownSockets.add(socket)+ if (features.includes('sessionDetails')) sessionDetailsSockets.add(socket)return features.length > 0? { protocolVersion: currentProtocolVersion(), features }: { protocolVersion: currentProtocolVersion() }@@ -464,6 +469,8 @@ async function main(): Promise<void> {// node-pty may flush a queued data callback after its exit callback. Once endSession has// disposed the emulator and broadcast exit, no data may touch or appear after that boundary.if (session.exited) return+ // Output is output whether or not it is shown: the reaper's idleness clock (sessionDetails).+ session.lastOutputAt = Date.now()// Trusted launch input is typed through the same ConPTY and therefore echoed by the shell.// While HostSession verifies that echo, keep the entire chunk out of both renderer push// frames and the reconstructable screen so executable/argv/prompt material stays core-only.@@ -1053,8 +1060,27 @@ async function main(): Promise<void> {await sessions.get(req.name)?.detach(socket)return { ok: true }}- case 'listSessions':- return { ok: true, result: { names: [...sessions.keys()] } satisfies ListSessionsResult }+ case 'listSessions': {+ const names = [...sessions.keys()]+ if (!sessionDetailsSockets.has(socket)) {+ return { ok: true, result: { names } satisfies ListSessionsResult }+ }+ // Only live generations are described: a retiring/exited one is already being ended, and+ // describing it would invite a second kill or a memory row for a dying tree.+ const details: SessionHostSessionDetail[] = []+ for (const s of sessions.values()) {+ if (s.exited || s.retiring) continue+ details.push({+ name: s.name,+ pid: s.proc.pid,+ subscribers: s.subscribers.size,+ lastOutputMs: s.lastOutputAt,+ createdMs: s.createdAt,+ generation: s.generation+ })+ }+ return { ok: true, result: { names, sessions: details } satisfies ListSessionsResult }+ }case 'ping':return { ok: true }case 'shutdown':diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.tsindex 5bdae9e02..436aa5b35 100644--- a/src/session-host/protocol.ts+++ b/src/session-host/protocol.ts@@ -205,8 +205,8 @@ export interface AttachResult {geometry?: { cols: number; rows: number }}/** Additive, independently negotiated capabilities (see the `hello` request). */-export type SessionHostFeature = 'geometry' | 'shutdown'-export const SESSION_HOST_FEATURES: readonly SessionHostFeature[] = ['geometry', 'shutdown']+export type SessionHostFeature = 'geometry' | 'shutdown' | 'sessionDetails'+export const SESSION_HOST_FEATURES: readonly SessionHostFeature[] = ['geometry', 'shutdown', 'sessionDetails']/** `result` of a successful `shutdown`: the session names whose process trees were ended. The* host exits right after this reply is flushed. A shutdown that could not confirm every kill@@ -243,6 +243,28 @@ export interface CaptureResult {}export interface ListSessionsResult {names: string[]+ /** One row per LIVE generation — present only for a connection that negotiated the+ * `sessionDetails` feature, so an older client keeps reading `{names}` byte-for-byte. A name in+ * `names` with no row here (a generation already retiring) is simply not described; a consumer+ * must never read that absence as "detached" or "no processes". */+ sessions?: SessionHostSessionDetail[]+}++/** What the observability surfaces (session reaper, session-memory panel, dev-server ports) need+ * to know about one host session — the session host's answer to tmux's `list-windows`/`list-panes`+ * formats. All stamps are epoch MILLISECONDS on the host's clock. */+export interface SessionHostSessionDetail {+ name: string+ /** The pty's own child (the pane's shell) — the root of the session's process tree. */+ pid: number+ /** Connections subscribed to this generation's output right now (tmux's `session_attached`). */+ subscribers: number+ /** When the pty last produced OUTPUT — the reaper's idleness clock (tmux's `window_activity`).+ * Starts at `createdMs`; nothing that only LOOKS at the session (attach, capture) moves it. */+ lastOutputMs: number+ createdMs: number+ /** Exact process generation, so a kill planned from this row cannot hit a same-name successor. */+ generation: string}/**diff --git a/src/session-host/session-details-host.test.ts b/src/session-host/session-details-host.test.tsnew file mode 100644index 000000000..a736f354b--- /dev/null+++ b/src/session-host/session-details-host.test.ts@@ -0,0 +1,243 @@+// `sessionDetails` (Windows parity: session reaper, session-memory panel, dev-server ports): the+// per-session rows `listSessions` carries for a connection that negotiated the feature, driven+// against the REAL bundled host over its socket protocol (same harness as shutdown-host.test.ts).+// Pinned: an older client still gets `{names}` only; subscriber counts follow attach/detach; the+// output clock moves on pty output and on NOTHING that merely looks (attach, capture).+import { afterEach, describe, expect, it } from 'vitest'+import { spawn, type ChildProcess } from 'child_process'+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'fs'+import net, { type Socket } from 'net'+import os from 'os'+import path from 'path'+import { build, type Plugin } from 'esbuild'+import {+ LineFramer,+ SESSION_HOST_PROTOCOL_VERSION,+ encodeFrame,+ type ListSessionsResult,+ type SessionHostEvent,+ type SessionHostFrame,+ type SessionHostResponse,+ type SessionHostSpawnOptions+} from './protocol'+import { sessionHostPaths, type SessionHostState } from './paths'++/** A pty that echoes every write back as output, after a short delay. */+function fakePtyPlugin(): Plugin {+ return {+ name: 'session-host-details-fake-pty',+ setup(bundle) {+ bundle.onResolve({ filter: /^node-pty$/ }, () => ({ path: 'node-pty', namespace: 'sd' }))+ bundle.onLoad({ filter: /^node-pty$/, namespace: 'sd' }, () => ({+ loader: 'js',+ contents: `+ let nextPid = 5100+ export function spawn() {+ let onData+ let onExit+ return {+ pid: nextPid++,+ onData(cb) { onData = cb },+ onExit(cb) { onExit = cb },+ write(d) { setTimeout(() => onData?.(d), 5) },+ resize() {},+ pause() {},+ resume() {},+ kill() { setTimeout(() => onExit?.({ exitCode: 0 }), 20) }+ }+ }+ `+ }))+ }+ }+}++async function waitForIdentity(dataDir: string): Promise<{ state: SessionHostState; token: string }> {+ const paths = sessionHostPaths(dataDir)+ for (let attempt = 0; attempt < 200; attempt++) {+ try {+ const state = JSON.parse(readFileSync(paths.statePath, 'utf8')) as SessionHostState+ const token = readFileSync(paths.tokenPath, 'utf8').trim()+ if (state.endpoint && token) return { state, token }+ } catch {+ /* publication is asynchronous by design; keep polling within the test bound */+ }+ await new Promise((resolve) => setTimeout(resolve, 20))+ }+ throw new Error('session host did not publish its identity')+}++type Connection = {+ socket: Socket+ events: SessionHostEvent[]+ request(frame: Record<string, unknown> & { id: number }): Promise<SessionHostResponse>+}++function connect(endpoint: string): Promise<Connection> {+ return new Promise((resolve, reject) => {+ const socket = net.connect(endpoint)+ const framer = new LineFramer()+ const events: SessionHostEvent[] = []+ const waiters = new Map<number, (frame: SessionHostResponse) => void>()+ socket.on('data', (chunk: Buffer) => {+ for (const frame of framer.push<SessionHostFrame>(chunk.toString('utf8'))) {+ if ('type' in frame) {+ events.push(frame)+ continue+ }+ waiters.get(frame.id)?.(frame)+ waiters.delete(frame.id)+ }+ })+ socket.once('error', reject)+ socket.once('connect', () =>+ resolve({+ socket,+ events,+ request: (frame) =>+ new Promise<SessionHostResponse>((done, fail) => {+ const timer = setTimeout(() => fail(new Error(`timed out on ${frame.id}`)), 4_000)+ waiters.set(frame.id, (response) => {+ clearTimeout(timer)+ done(response)+ })+ socket.write(encodeFrame(frame))+ })+ })+ )+ })+}++function waitForExit(child: ChildProcess): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()+ return new Promise((resolve) => child.once('exit', () => resolve()))+}++const SPAWN: SessionHostSpawnOptions = { cwd: '.', shell: 'fake-shell', args: [], env: {}, cols: 80, rows: 24 }++const cleanupPaths: string[] = []+afterEach(() => {+ for (const target of cleanupPaths.splice(0)) {+ rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })+ }+})++async function startHost(): Promise<{ child: ChildProcess; state: SessionHostState; token: string }> {+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-details-'))+ cleanupPaths.push(fixtureDir)+ const dataDir = path.join(fixtureDir, 'user-data')+ mkdirSync(dataDir)+ const paths = sessionHostPaths(dataDir)+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)+ const bundlePath = path.join(fixtureDir, 'host.cjs')+ await build({+ absWorkingDir: process.cwd(),+ entryPoints: ['src/session-host/host.ts'],+ outfile: bundlePath,+ bundle: true,+ platform: 'node',+ format: 'cjs',+ plugins: [fakePtyPlugin()],+ logLevel: 'silent'+ })+ const child = spawn(process.execPath, [bundlePath, dataDir], { cwd: process.cwd(), stdio: 'ignore', windowsHide: true })+ const { state, token } = await waitForIdentity(dataDir)+ return { child, state, token }+}++let nextId = 100+const req = (conn: Connection, body: Record<string, unknown>): Promise<SessionHostResponse> =>+ conn.request({ id: nextId++, ...body })++async function hello(conn: Connection, token: string, features?: string[]): Promise<SessionHostResponse> {+ return req(conn, {+ cmd: 'hello',+ token,+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,+ ...(features ? { features } : {})+ })+}++const list = async (conn: Connection): Promise<ListSessionsResult> => {+ const res = await req(conn, { cmd: 'listSessions' })+ expect(res.ok).toBe(true)+ return (res as { result: ListSessionsResult }).result+}++const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))++describe('session-host sessionDetails', () => {+ it('describes each live session only to a connection that negotiated it', async () => {+ const { child, state, token } = await startHost()+ const sockets: Socket[] = []+ try {+ const modern = await connect(state.endpoint)+ const legacy = await connect(state.endpoint)+ sockets.push(modern.socket, legacy.socket)+ const negotiated = await hello(modern, token, ['geometry', 'shutdown', 'sessionDetails'])+ expect(negotiated).toMatchObject({ ok: true, result: { features: ['geometry', 'shutdown', 'sessionDetails'] } })+ await hello(legacy, token, ['geometry', 'shutdown'])++ const before = Date.now()+ expect((await req(modern, { cmd: 'attach', name: 'nt-a', spawn: SPAWN, scrollback: 100 })).ok).toBe(true)+ expect((await req(modern, { cmd: 'attach', name: 'nt-b', spawn: SPAWN, scrollback: 100 })).ok).toBe(true)++ // An older client reads exactly what it always did.+ expect(await list(legacy)).toEqual({ names: ['nt-a', 'nt-b'] })++ const detailed = await list(modern)+ expect(detailed.names).toEqual(['nt-a', 'nt-b'])+ expect(detailed.sessions).toHaveLength(2)+ for (const row of detailed.sessions ?? []) {+ expect(row.subscribers).toBe(1)+ expect(row.pid).toBeGreaterThanOrEqual(5100)+ expect(row.generation).toMatch(/^[A-Za-z0-9_-]{8,128}$/)+ expect(row.createdMs).toBeGreaterThanOrEqual(before - 5)+ expect(row.lastOutputMs).toBe(row.createdMs) // nothing has printed yet+ }+ expect(new Set(detailed.sessions?.map((r) => r.pid)).size).toBe(2)++ // Detach: the subscriber count drops; the other connection attaching raises it again.+ expect((await req(modern, { cmd: 'detach', name: 'nt-a' })).ok).toBe(true)+ const afterDetach = await list(modern)+ expect(afterDetach.sessions?.find((r) => r.name === 'nt-a')?.subscribers).toBe(0)+ expect(afterDetach.sessions?.find((r) => r.name === 'nt-b')?.subscribers).toBe(1)+ expect((await req(legacy, { cmd: 'attachExisting', name: 'nt-b' })).ok).toBe(true)+ expect((await list(modern)).sessions?.find((r) => r.name === 'nt-b')?.subscribers).toBe(2)+ } finally {+ for (const socket of sockets) socket.destroy()+ child.kill()+ await waitForExit(child)+ }+ }, 30_000)++ it('the output clock moves on pty output and not on attach or capture', async () => {+ const { child, state, token } = await startHost()+ const sockets: Socket[] = []+ try {+ const conn = await connect(state.endpoint)+ sockets.push(conn.socket)+ await hello(conn, token, ['sessionDetails'])+ expect((await req(conn, { cmd: 'attach', name: 'nt-a', spawn: SPAWN, scrollback: 100 })).ok).toBe(true)+ const created = (await list(conn)).sessions?.[0]+ await sleep(30)+ // Looking moves nothing.+ expect((await req(conn, { cmd: 'detach', name: 'nt-a' })).ok).toBe(true)+ expect((await req(conn, { cmd: 'attachExisting', name: 'nt-a' })).ok).toBe(true)+ expect((await req(conn, { cmd: 'capture', name: 'nt-a', full: true })).ok).toBe(true)+ expect((await list(conn)).sessions?.[0].lastOutputMs).toBe(created?.lastOutputMs)+ // Output does.+ expect((await req(conn, { cmd: 'write', name: 'nt-a', data: 'hi' })).ok).toBe(true)+ let moved = false+ for (let i = 0; i < 100 && !moved; i++) {+ await sleep(10)+ moved = ((await list(conn)).sessions?.[0].lastOutputMs ?? 0) > (created?.lastOutputMs ?? 0)+ }+ expect(moved).toBe(true)+ } finally {+ for (const socket of sockets) socket.destroy()+ child.kill()+ await waitForExit(child)+ }+ }, 30_000)+})diff --git a/src/session-host/session.ts b/src/session-host/session.tsindex 2a13a88d0..b14b3fd8d 100644--- a/src/session-host/session.ts+++ b/src/session-host/session.ts@@ -170,6 +170,10 @@ export class HostSession {* co-attach, one level further down the stack. */readonly subscribers = new Set<Socket>()readonly createdAt = Date.now()+ /** When the pty last produced output (epoch ms) — the session reaper's idleness clock, reported+ * by `listSessions` to `sessionDetails` connections. Starts at creation, like tmux's+ * `window_activity`; host.ts stamps it on every pty `data` callback and nothing else moves it. */+ lastOutputAt = this.createdAt/** Set once, by whichever path (natural pty exit or an explicit `killSession`) ends this* session first — guards against double-dispose/double-broadcast when both could race. */exited = false