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
fix(pty): a join-only create refuses what it cannot confirm, never detaches, withdraws old votes
review2fcf6c6139e2
diff --git a/src/core/pty-join-only.test.ts b/src/core/pty-join-only.test.tsindex fe4121da4..334b5d497 100644--- a/src/core/pty-join-only.test.ts+++ b/src/core/pty-join-only.test.ts@@ -14,6 +14,8 @@ import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'/** One fake pty per spawn, recorded so a test can assert "exactly one spawn" and push output. */interface FakePty {+ /** The argv the pty was spawned with — the tmux attach flags are asserted from it. */+ args: string[]onDataCb?: (d: string) => voidonExitCb?: (e: { exitCode: number }) => voidwrites: string[]@@ -29,8 +31,8 @@ vi.mock('./session-host-backend', async () =>)vi.mock('node-pty', () => ({- spawn: (_file: string, _args: string[], _opts: unknown) => {- const p: FakePty = { writes: [], resizes: [], killed: false }+ spawn: (_file: string, args: string[], _opts: unknown) => {+ const p: FakePty = { args: [...(args ?? [])], writes: [], resizes: [], killed: false }spawned.push(p)return {onData: (cb: (d: string) => void) => {@@ -57,6 +59,22 @@ vi.mock('./pty-devices', async (importOriginal) => ({readPtyDevices: () => ({ ceiling: 511, inUse: 8 })}))+// The SSH cases never run a real `ssh`: with no ssh executable the only thing a create that gets+// PAST the join-only gate can do is spawn (a local plain shell here), which is exactly what those+// tests must not see. Every other executable lookup is the real one.+vi.mock('./exec-path', async (importOriginal) => {+ const real = await importOriginal<typeof import('./exec-path')>()+ return {+ ...real,+ findExecutableSync: (bin: string, fallbacks?: string[]) =>+ bin === 'ssh' ? null : real.findExecutableSync(bin, fallbacks)+ }+})+vi.mock('./remote-ssh/agent-probe', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./remote-ssh/agent-probe')>()),+ probeAgentSockToPin: async () => undefined+}))+const OWNER = 1const VIEWER = 2@@ -73,26 +91,57 @@ afterEach(() => {resetPlatformForTests()})+type ConfirmedProcessRun = (file: string, args: readonly string[], opts?: object) => Promise<unknown>+/** The default manager: no tmux (init() never runs in unit tests), so a session is a plain shell. */-async function manager() {+async function manager(deps: { confirmedProcessRun?: ConfirmedProcessRun } = {}) {const { PtyManager } = await import('./pty-manager')- const m = new PtyManager()+ const m = new PtyManager(deps)m.registerIpc()return m}/**- * A manager whose sessions are tmux-BACKED, with the `has-session` probe answering `exists`. The- * tmux path is forced (as pty-coattach.test.ts does) and every tmux subprocess the spawn path would- * run is stubbed, so no real tmux socket is touched.+ * What `tmux has-session` does for this node: the session is there, tmux says it is not (its own+ * exit 1), or the probe could not run at all (EAGAIN under a bulk load, a timeout).*/-async function tmuxManager(exists: boolean) {- const m = await manager()+type Probe = 'present' | 'absent' | 'error'++/**+ * `tmux has-session -t <target>` against a set of live session names, the way tmux 3.4 resolves+ * the target (measured): `=name` matches exactly; a bare name falls through to PREFIX matching on+ * a miss, so `nt-n1` "exists" while only `nt-n12` is alive.+ */+function hasSession(live: string[], args: readonly string[]): boolean {+ const target = args[args.indexOf('-t') + 1] ?? ''+ if (target.startsWith('=')) return live.includes(target.slice(1))+ return live.some((s) => s === target || s.startsWith(target))+}++/**+ * A manager whose sessions are tmux-BACKED. The tmux path is forced (as pty-coattach.test.ts does)+ * and both existence probes answer from `probe` without touching a tmux socket:+ * - the STRICT one through the injected process runner, which emulates `has-session` (above) and+ * rejects the way `execFile` does — `code: 1` for tmux's own "no session", `code: 'EAGAIN'` for+ * a probe that could not run;+ * - the FOLDED warm/cold one (`tmuxSessionExists`, a bare target) stubbed to what the real one+ * answers: only tmux's own exit 1 is absence, so a failed probe reads as "exists".+ */+async function tmuxManager(probe: Probe, live: string[] = probe === 'present' ? ['nt-n1'] : []) {+ const confirmedProcessRun: ConfirmedProcessRun = async (_file, args) => {+ if (probe === 'error')+ throw Object.assign(new Error('spawn EAGAIN'), { code: 'EAGAIN' })+ if (hasSession(live, args)) return { stdout: '', stderr: '' }+ throw Object.assign(new Error("can't find session"), { code: 1 })+ }+ const m = await manager({ confirmedProcessRun });(m as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'vi.spyOn(m as unknown as { tmuxSessionExists: (k: string) => Promise<boolean> },'tmuxSessionExists'- ).mockResolvedValue(exists)+ ).mockImplementation(async (k: string) =>+ probe === 'error' ? true : hasSession(live, ['-t', `nt-${k}`])+ )// The warm-reattach stale-cwd probe runs `tmux display-message`; answer "not stale".vi.spyOn(m as unknown as { paneCwdStale: (k: string) => Promise<boolean> },@@ -101,6 +150,18 @@ async function tmuxManager(exists: boolean) {return m}+const SSH_REMOTE = { controlPath: '/tmp/nt-test-cm', conn: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }++/** A manager whose REMOTE freshness read answers `verdict` (see remote-session-index.ts). */+async function sshManager(verdict: 'present' | 'absent' | 'unknown') {+ const m = await manager()+ vi.spyOn(+ m as unknown as { remoteSessionVerdict: () => Promise<string> },+ 'remoteSessionVerdict'+ ).mockResolvedValue(verdict)+ return m+}+const create = (clientId: number, options: Partial<PtyCreateOptions>) =>fake.handlers[IPC.ptyCreate](clientId, {cols: 80,@@ -123,7 +184,7 @@ describe('joinOnly: a viewer may watch a terminal but never start one', () => {})it('refuses when tmux says the session is gone, and spawns no tmux client', async () => {- await tmuxManager(false)+ await tmuxManager('absent')expect(await create(VIEWER, { joinOnly: true })).toEqual(REFUSED)expect(spawned).toHaveLength(0)})@@ -153,7 +214,7 @@ describe('joinOnly: a viewer may watch a terminal but never start one', () => {})it('warm-reattaches a tmux session that is still running', async () => {- await tmuxManager(true)+ await tmuxManager('present')const res = await create(VIEWER, { joinOnly: true })expect(res.unavailable).toBeUndefined()expect(res.sessionId).not.toBe('')@@ -170,6 +231,65 @@ describe('joinOnly: a viewer may watch a terminal but never start one', () => {expect(spawned).toHaveLength(1)})+ // The folded warm/cold probe answers "exists" when tmux could not be asked, because for the+ // OWNER that is the safe fold (never type a resume into a live pane). For a viewer it is the+ // unsafe one: "exists" sends it on to `new-session -A`, which CREATES the session if it was+ // really gone — and then the owner's next open reads `fresh:false` and skips its cold restore.+ it('refuses when the tmux probe could not run (EAGAIN), and spawns nothing', async () => {+ await tmuxManager('error')+ expect(await create(VIEWER, { joinOnly: true })).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ })++ it('refuses when there is no tmux to ask at all (the binary cannot be executed)', async () => {+ // No stubs: both probes run for real against a path that does not exist (spawn ENOENT).+ const m = await manager()+ ;(m as unknown as { tmuxPath: string }).tmuxPath = '/nonexistent/nodeterm-test/tmux'+ expect(await create(VIEWER, { joinOnly: true })).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ })++ // App-minted node ids share a prefix and differ in a trailing counter (`term-abc-1`,+ // `term-abc-12`). tmux resolves a BARE target by prefix on a miss, while `new-session -A -s`+ // matches exactly — so a bare probe would read `nt-n1` as alive and the attach would create it.+ it('refuses when only a session whose name EXTENDS this one is alive (exact-target probe)', async () => {+ await tmuxManager('absent', ['nt-n12'])+ expect(await create(VIEWER, { joinOnly: true, persistKey: 'n1' })).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ })++ it('refuses an SSH node whose host could not be read (verdict unknown)', async () => {+ await sshManager('unknown')+ expect(await create(VIEWER, { joinOnly: true, sshRemote: SSH_REMOTE })).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ })++ it('refuses an SSH node whose host says the session is gone', async () => {+ await sshManager('absent')+ expect(await create(VIEWER, { joinOnly: true, sshRemote: SSH_REMOTE })).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ })++ // `-D` detaches every OTHER tmux client of the session on attach: the user's own+ // `tmux -L node-terminal attach`, another app on the same socket. A watch-only view must mirror+ // them, the way a relay-served pty does (`tmuxAttachFlags`), never kick them off.+ it('a join-only warm reattach does not detach other tmux clients (no -D)', async () => {+ await tmuxManager('present')+ await create(VIEWER, { joinOnly: true })+ expect(spawned).toHaveLength(1)+ const argv = spawned[0].args+ expect(argv).toContain('new-session')+ expect(argv).toContain('-A')+ expect(argv).not.toContain('-D')+ })++ it('control: the owner\'s warm reattach still takes the session over (-D)', async () => {+ await tmuxManager('present')+ await create(OWNER, {})+ expect(spawned).toHaveLength(1)+ expect(spawned[0].args).toContain('-D')+ })+it('an absent joinOnly still spawns (the non-viewer path is unchanged)', async () => {await manager()const a = await create(OWNER, {})@@ -222,11 +342,23 @@ describe('sizeVote: false — a viewer never constrains the shared pty size', ()expect(spawned[0].resizes).toEqual([])})+ // The same subscriber key can join twice: a renderer reload re-joins under the same ClientId,+ // and so does a client whose role changed from editor to viewer. Its earlier vote must not+ // survive the re-join that says it no longer votes.+ it('a re-join as a non-voter withdraws the vote the same view held before', async () => {+ await manager()+ await create(OWNER, { cols: 120, rows: 40 })+ await create(VIEWER, { cols: 60, rows: 20 }) // an editor: votes, the pty shrinks+ expect(spawned[0].resizes.at(-1)).toEqual({ cols: 60, rows: 20 })+ await create(VIEWER, { cols: 60, rows: 20, sizeVote: false }) // same view, now watch-only+ expect(spawned[0].resizes.at(-1)).toEqual({ cols: 120, rows: 40 })+ })+it('a viewer that warm-reattached holds no vote once the owner joins', async () => {// The viewer's create is the first in this process, so it SPAWNS the tmux client (at its own// grid — the pty needs some size). That must not seed a vote: when the owner then co-attaches,// the pty takes the owner's size instead of staying pinned at the viewer's small window.- await tmuxManager(true)+ await tmuxManager('present')const v = await create(VIEWER, { cols: 40, rows: 10, joinOnly: true, sizeVote: false })expect(v.fresh).toBe(false)const a = await create(OWNER, { cols: 120, rows: 40 })diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 034edfd8f..7b88d2f9d 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -752,11 +752,13 @@ export interface DetachedSinks {* subscribes to the existing `Session` in this process — it does NOT start a second tmux client.* The app therefore always has exactly ONE tmux client per session, so tmux's own multi-client* size negotiation never engages and "smallest subscriber wins" is decided by us (pty-size.ts).- * A relay-served (detached) pty is the one exception: the host's local client is already attached- * to the same session and must be mirrored, not kicked off.+ * A relay-served (detached) pty is one exception: the host's local client is already attached+ * to the same session and must be mirrored, not kicked off. A JOIN-ONLY reattach (a hosted-relay+ * viewer, `PtyCreateOptions.joinOnly`) is the other: a watch-only view must never detach the+ * user's own `tmux attach`, another app on the same socket, or a relay-served pty.*/-export function tmuxAttachFlags(detached: boolean): string[] {- return detached ? ['-A'] : ['-A', '-D']+export function tmuxAttachFlags(mirror: boolean): string[] {+ return mirror ? ['-A'] : ['-A', '-D']}// Output coalescing: a fast producer (e.g. `yes`, a verbose build, tmux full-screen@@ -2149,8 +2151,11 @@ export class PtyManager {const size = normalizeSize(options.cols, options.rows)// A non-voting view (`sizeVote: false`, a hosted-relay viewer) stays out of the min, exactly// like a parked subscriber: it still gets output, and `shown` makes applySize tell it the- // authoritative size to render.+ // authoritative size to render. The same key can arrive here already holding a vote (a+ // renderer reload re-joins under the same ClientId, and so does a client whose role changed+ // from editor to viewer), so a non-voting join WITHDRAWS it; applySize below re-derives the size.if (options.sizeVote !== false) existing.sizes.set(sub, size)+ else existing.sizes.delete(sub)existing.shown.set(sub, size)const before = existing.appliedSizethis.applySize(existingId, existing)@@ -2279,19 +2284,33 @@ export class PtyManager {? await this.remoteSessionVerdict(options.sshRemote, sessionName(options.persistKey as string)): undefinedconst freshUnverified = remoteVerdict === 'unknown'+ // A join-only create (hosted-relay viewer) asks the STRICT local question instead of the folded+ // one: `tmuxSessionExists` answers "exists" when tmux could not be asked, which is the safe fold+ // for an owner (never type a resume into a live pane) and the unsafe one for a viewer — it sends+ // the create on to `new-session -A`, which CREATES the session if it was really gone, and the+ // owner's next open then reads `fresh:false` and skips its cold restore.+ const joinOnlyLocalVerdict =+ options.joinOnly && !options.sshRemote && !warmWindowsBackend && tmuxBacked+ ? await this.strictTmuxVerdict(options.persistKey as string)+ : undefinedlet fresh = options.sshRemote? remoteVerdict === 'absent': warmWindowsBackend? false: tmuxBacked- ? !(await this.tmuxSessionExists(options.persistKey as string))+ ? joinOnlyLocalVerdict+ ? joinOnlyLocalVerdict === 'absent'+ : !(await this.tmuxSessionExists(options.persistKey as string)): true- // A join-only create (hosted-relay viewer) must never start a session: only a reattach to one- // that already exists is allowed. `fresh` here is "nothing to reattach to" — and for a node- // that would land on the session-host backend it is a placeholder `true` (that backend's- // attach-or-create IS its probe, see above), so a join-only create is refused there too rather- // than sent a round trip that could create. Fails closed: a viewer never starts anything.- if (options.joinOnly && fresh) return { sessionId: '', fresh: false, unavailable: 'join-only' }+ // A join-only create must never start a session: only a reattach to one we POSITIVELY saw is+ // allowed. Refused when there is nothing to reattach to (`fresh`) and when we could not tell+ // (`freshUnverified` for SSH, an unanswered strict probe locally). For a node that would land+ // on the session-host backend `fresh` is a placeholder `true` (that backend's attach-or-create+ // IS its probe, see above), so it is refused there too rather than sent a round trip that could+ // create. Fails closed: a viewer never starts anything. One refusal value for both reasons —+ // the renderer's sentence claims only that no running terminal was found.+ if (options.joinOnly && (fresh || freshUnverified || joinOnlyLocalVerdict === 'unknown'))+ return { sessionId: '', fresh: false, unavailable: 'join-only' }// Ensure the login-shell PATH is resolved (prewarmed in init(); usually already settled)// so the session env below picks it up — awaiting keeps the event loop free either way.await resolveShellPath()@@ -2673,6 +2692,31 @@ export class PtyManager {}}+ /**+ * The strict existence probe a JOIN-ONLY create needs, as a tri-state: `unknown` when tmux could+ * not be asked (a spawn error, a timeout), which such a create must refuse rather than read as+ * "exists" the way the warm/cold fold (`tmuxSessionExists`) does.+ *+ * The target is EXACT (`-t =nt-<id>`), unlike `confirmedTmuxSessionExists`'s bare name. Measured+ * on tmux 3.4: with only `nt-term-abc-12` alive, `has-session -t nt-term-abc-1` exits 0 (a miss+ * falls through to fnmatch then PREFIX matching), while `new-session -A -s nt-term-abc-1` matches+ * exactly and CREATES `nt-term-abc-1`. App-minted ids share a prefix and differ in a trailing+ * counter, so a bare probe would let a viewer start a session whenever a longer id is alive.+ */+ private async strictTmuxVerdict(persistKey: string): Promise<'present' | 'absent' | 'unknown'> {+ if (!this.tmuxPath) return 'absent'+ try {+ await this.confirmedProcessRun(+ this.tmuxPath,+ ['-L', TMUX_SOCKET, 'has-session', '-t', `=${sessionName(persistKey)}`],+ { timeout: PROBE_TIMEOUT_MS }+ )+ return 'present'+ } catch (error) {+ return probeSaysAbsent(error) ? 'absent' : 'unknown'+ }+ }+/** Destructive-confirmation variant of the warm-attach probe. Warm attach treats an unavailable* probe as "possibly exists" to avoid typing into a live session; an awaited restart must not* report success on uncertainty, because its caller mutates profile state only after this says@@ -3280,7 +3324,8 @@ export class PtyManager {// local renderer client (a remount should take sole ownership of its session). A host-served// PTY (sinks set) MUST NOT detach others: the host's own local client is attached to the same// `nt-<id>` session, and a connecting client should MIRROR it (tmux co-attach), not kick it- // off — `-D` there is exactly what showed "[detached]" in every host window on connect.+ // off — `-D` there is exactly what showed "[detached]" in every host window on connect. A+ // join-only (watch-only) reattach mirrors for the same reason: see `tmuxAttachFlags`.// (tmux sizes a co-attached session to the smallest client — the accepted mirroring tradeoff.)// `-e` sets the session environment explicitly (the tmux server is shared, so relying// on the client's inherited env would leak the first session's values into later ones).@@ -3296,7 +3341,8 @@ export class PtyManager {'-f',this.confPath,'attach-session',- ...(sinks ? [] : ['-d']),+ // `-d` detaches other clients, so it follows `tmuxAttachFlags`' mirror rule.+ ...(sinks || options.joinOnly ? [] : ['-d']),'-t',sessionName(options.persistKey)]@@ -3337,7 +3383,7 @@ export class PtyManager {...Object.keys(customEnvMerged),...Object.keys(projectEnv ?? {})])- const attachFlags = tmuxAttachFlags(!!sinks)+ const attachFlags = tmuxAttachFlags(!!sinks || !!options.joinOnly)args = ['-L',TMUX_SOCKET,diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex e3687079b..99ba58e44 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -3304,10 +3304,25 @@ export function TerminalNode({// the near-side guard above produces, retry included.if (unavailable) {const refusal = ptyRefusal(unavailable)- // A hosted-relay VIEWER opened a terminal nobody has running. Nothing failed and nothing- // is offline, so neither overlay applies — "Try again" would only respawn into the same- // refusal. Say why the pane is empty and stop; "Refresh terminal" re-asks on demand.+ // A hosted-relay VIEWER opened a terminal it could not find running. Nothing failed and+ // nothing is offline, so neither overlay applies — "Try again" would only respawn into the+ // same refusal. What CAN still be on screen is state from an earlier run of this effect+ // (a refresh re-enters here): a spawn-error overlay (only its own "Try again" clears it),+ // the stale-cwd and lost-session banners (the success path resets them on every create+ // result, and this path returns before it; "Restart in folder" would recycle a session+ // this view does not hold), a refused-launch banner about a launch into a session that+ // is not attached, and a letterbox sized to a pty that is not attached. Clear them the+ // way the neighbouring refusals set theirs, say why the pane is empty, and stop;+ // "Refresh terminal" re-asks on demand.if (unavailable === 'join-only') {+ setCo(termKey, {+ offline: false,+ spawnError: null,+ staleCwd: false,+ lostSession: false,+ launchTooLongBytes: null,+ letterbox: false+ })if (!disposed) term.write(`\r\n\x1b[90m[${refusal.message}]\x1b[0m\r\n`)return}diff --git a/src/renderer/nodes/join-only-refusal-wiring.test.ts b/src/renderer/nodes/join-only-refusal-wiring.test.tsnew file mode 100644index 000000000..060726e10--- /dev/null+++ b/src/renderer/nodes/join-only-refusal-wiring.test.ts@@ -0,0 +1,56 @@+// TerminalNode's handling of a `'join-only'` create refusal (a hosted-relay viewer asked for a+// terminal it could not find running).+//+// The DECISION about the words is pure and tested in `shared/pty-refusal.test.ts`. What only the+// source can show is what the node does with it: this branch returns BEFORE the success path that+// resets the per-node banners on every create result, and before the neighbouring refusals' own+// `setCo`, so anything an earlier run of the lifecycle effect left on screen (a spawn-error+// overlay, a stale-cwd banner offering to recycle a session this view does not hold) would stay+// there over an empty pane unless this branch clears it.++import { describe, it, expect } from 'vitest'+import fs from 'fs'+import path from 'path'++const src = fs.readFileSync(path.resolve(__dirname, 'TerminalNode.tsx'), 'utf8').replace(/\r\n/g, '\n')++/** The body of `if (unavailable === 'join-only') { … }`, up to its `return`. */+function joinOnlyBranch(): string {+ const start = src.indexOf("if (unavailable === 'join-only') {")+ expect(start, 'the join-only branch must still exist').toBeGreaterThan(-1)+ const end = src.indexOf('return', start)+ expect(end).toBeGreaterThan(start)+ return src.slice(start, end)+}++/** The CoState field names. */+function coStateFields(): string[] {+ const start = src.indexOf('interface CoState {')+ const end = src.indexOf('const NO_CO: CoState', start)+ expect(start).toBeGreaterThan(-1)+ expect(end).toBeGreaterThan(start)+ return [...src.slice(start, end).matchAll(/^ {2}(\w+):/gm)].map((m) => m[1])+}++describe("TerminalNode: a 'join-only' refusal", () => {+ it('resets every CoState field that describes a session, and only those', () => {+ const branch = joinOnlyBranch()+ const fields = coStateFields()+ expect(fields).toContain('spawnError') // sanity: the scrape found the shape it expects+ // `closed` / `ended` are verdicts about the NODE (deleted by another user, recycle never came+ // back) that a refused create does not contradict; every other field describes a session or a+ // spawn attempt, and none is true of a view that attached to nothing.+ for (const f of fields.filter((f) => f !== 'closed' && f !== 'ended'))+ expect(branch, `join-only branch must reset ${f}`).toMatch(new RegExp(`\\b${f}:`))+ expect(branch).not.toMatch(/\bclosed:/)+ expect(branch).not.toMatch(/\bended:/)+ })++ it('shows no overlay and reports no SSH drop', () => {+ const branch = joinOnlyBranch()+ expect(branch).toMatch(/spawnError: null/)+ expect(branch).toMatch(/offline: false/)+ expect(branch).not.toMatch(/reportSshDrop/)+ expect(branch).toMatch(/term\.write\(/)+ })+})diff --git a/src/shared/pty-refusal.test.ts b/src/shared/pty-refusal.test.tsindex b4853129e..dac08aaad 100644--- a/src/shared/pty-refusal.test.ts+++ b/src/shared/pty-refusal.test.ts@@ -14,7 +14,12 @@ describe('PTY refusal presentation', () => {it('a join-only refusal is not a lost connection, and says why nothing is shown', () => {expect(ptyRefusal('join-only')).toEqual({connectionLost: false,- message: 'this terminal is not running — a viewer can only watch terminals that are already open'+ message: 'no running terminal was found to watch — a viewer can only watch terminals that are already open'})})+ // The same refusal covers "tmux said it is gone" AND "tmux could not be asked", so the sentence+ // must not assert the first: a probe that failed says nothing about whether the terminal runs.+ it('the join-only message does not claim the terminal is not running', () => {+ expect(ptyRefusal('join-only').message).not.toMatch(/is not running/)+ })})diff --git a/src/shared/pty-refusal.ts b/src/shared/pty-refusal.tsindex 261654814..d650d9933 100644--- a/src/shared/pty-refusal.ts+++ b/src/shared/pty-refusal.ts@@ -11,11 +11,13 @@ export function ptyRefusal(unavailable: NonNullable<PtyCreateResult['unavailableconnectionLost: false}}- // A hosted-relay viewer asked for a terminal nobody has open. Nothing is disconnected — read as a- // lost connection it would report an SSH drop and kick the reconnector for a healthy project.+ // A hosted-relay viewer asked for a terminal it could not find running. Nothing is disconnected —+ // read as a lost connection it would report an SSH drop and kick the reconnector for a healthy+ // project. The refusal covers two facts (tmux said the session is gone; tmux could not be asked),+ // so the sentence claims only what both share: no running terminal was FOUND.if (unavailable === 'join-only') {return {- message: 'this terminal is not running — a viewer can only watch terminals that are already open',+ message: 'no running terminal was found to watch — a viewer can only watch terminals that are already open',connectionLost: false}}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 19a860026..a5deef469 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -360,8 +360,9 @@ export interface PtyCreateResult {* (§5 property 4). Remote managed Codex accounts refuse unknown/unsafe ids or unresolved/unsafe homes.* System SSH Codex may attach before remote home discovery. Nothing spawned on refusal.*- * `'join-only'`: `PtyCreateOptions.joinOnly` was set (a hosted-relay viewer) and there was no- * running session to join or reattach to, so nothing was started. Not a lost connection.+ * `'join-only'`: `PtyCreateOptions.joinOnly` was set (a hosted-relay viewer) and no running+ * session could be confirmed to join or reattach to — either it is gone, or its existence could+ * not be checked — so nothing was started. Not a lost connection.*/unavailable?: 'ssh' | 'codex-account' | 'join-only'}