Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(cli): stop a conflicting claude --bg job before resuming its session (#1611)

Jacob Pham11ef228d8e80
diff --git a/cli/src/core/agents/swap.spec.ts b/cli/src/core/agents/swap.spec.ts
index e1031677a..d20e7c92b 100644
--- a/cli/src/core/agents/swap.spec.ts
+++ b/cli/src/core/agents/swap.spec.ts
@@ -14,9 +14,11 @@ import { setAgentSignaller } from '../../lib/processSignals.js'
import { createPaneSwap, SWAP_SETTLE_MS, type PaneSwapDeps } from './swap.js'
import type { NativeLaunch } from '../../engines/nativeLaunch.js'
import { NATIVE_LAUNCH_MARKER } from '../../lib/nativePaneHold.js'
+import { stopConflictingBackgroundJob } from '../../lib/claudeBackgroundJob.js'
vi.mock('../../lib/deleteAgentFallback.js', async (real) => ({ ...await real<object>(), terminateDeletedAgent: vi.fn(async () => ({ ok: true })) }))
vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), buildEngineLaunchArgv: vi.fn(() => ['zsh', '-lc', 'claude']) }))
+vi.mock('../../lib/claudeBackgroundJob.js', () => ({ stopConflictingBackgroundJob: vi.fn(async () => {}) }))
vi.mock('../../lib/terminalAgentDiscovery.js', async (real) => ({ ...await real<object>(), processRows: vi.fn(async () => null) }))
vi.mock('../../lib/paneEngineProcess.js', async (real) => ({
...await real<object>(),
@@ -58,6 +60,37 @@ describe('the pane-process swap', () => {
prepared.buildArgv({ resumeSessionId: 's1', bypassPermission: false })
expect(buildEngineLaunchArgv).toHaveBeenCalledWith('claude', expect.objectContaining({ native, resumeSessionId: 's1' }))
})
+ it('wires a background-job check for a plain Claude pane restart, with its own session and env', async () => {
+ const prepared = setup().swap.paneSwapDeps(session(), place(), { env: { CLAUDE_CONFIG_DIR: '/custom' } })
+ expect(prepared.stopConflictingJob).toBeDefined()
+ await prepared.stopConflictingJob!()
+ expect(stopConflictingBackgroundJob).toHaveBeenCalledWith(expect.objectContaining({
+ sessionId: 's1', env: expect.objectContaining({ CLAUDE_CONFIG_DIR: '/custom' }),
+ }))
+ })
+ it('skips the background-job check for a non-Claude engine', () => {
+ const prepared = setup(session({ engine: 'codex' })).swap.paneSwapDeps(session({ engine: 'codex' }), place())
+ expect(prepared.stopConflictingJob).toBeUndefined()
+ })
+ it('skips the background-job check for a DSH agent: its pane may run on a different host', () => {
+ const dshSession = session({ dsh: { id: 'fixture-dsh', url: 'https://example.test' } as never })
+ const prepared = setup(dshSession).swap.paneSwapDeps(dshSession, place())
+ expect(prepared.stopConflictingJob).toBeUndefined()
+ })
+ it('still checks for a background job on a captured-native launch, with that launch\'s own environment', async () => {
+ // `native` is the captured launch for every ordinary LOCAL Claude run (launchOverrides.ts), not a
+ // signal the pane is elsewhere — it must not turn this off. `env` here stands in for what
+ // launchOverrides.ts really produces: `native.environment` (its CLAUDE_CONFIG_DIR) merged in already.
+ const native: NativeLaunch = { token: 'prepared-native', opencodeMajor: null,
+ environment: { CLAUDE_CONFIG_DIR: '/native/claude-home' }, proofs: [], current: () => true,
+ prepareHooks: async () => true, permission: async () => 'supported' }
+ const prepared = setup().swap.paneSwapDeps(session(), place(), { native, env: { CLAUDE_CONFIG_DIR: '/native/claude-home' } })
+ expect(prepared.stopConflictingJob).toBeDefined()
+ await prepared.stopConflictingJob!()
+ expect(stopConflictingBackgroundJob).toHaveBeenCalledWith(expect.objectContaining({
+ sessionId: 's1', env: expect.objectContaining({ CLAUDE_CONFIG_DIR: '/native/claude-home' }),
+ }))
+ })
it('refuses, before anything is stopped, a relaunch Windows would run through cmd.exe; builds no launch script for it', () => {
vi.mocked(buildEngineLaunchArgv).mockClear()
const tools = mkdtempSync(join(tmpdir(), 'swap-windows-'))
diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.ts
index ba149e2dc..7924b5cd5 100644
--- a/cli/src/core/agents/swap.ts
+++ b/cli/src/core/agents/swap.ts
@@ -8,6 +8,8 @@
import { homedir } from 'node:os'
import { checkPidRuntime, terminateDeletedAgent } from '../../lib/deleteAgentFallback.js'
import { buildEngineCommandArgv, buildEngineLaunchArgv, engineLaunchEnv } from '../../lib/engineLaunch.js'
+import { engineBin } from '../../lib/engineBin.js'
+import { stopConflictingBackgroundJob } from '../../lib/claudeBackgroundJob.js'
import { windowsLaunchRefusal } from '../../lib/windows/launch.js'
import { isWindowsHeldPane, windowsPaneLaunch } from '../../lib/windows/engineStart.js'
import { mergedLaunchEnv } from './launchEnv.js'
@@ -162,6 +164,16 @@ export function createPaneSwap({ byAgent, prepareSessionResume, keepAbandonedCon
launchRefusal: (opts) => {
try { buildEngineCommandArgv(session.engine, relaunchOptions(opts)); return null } catch (error) { return windowsLaunchRefusal(error).detail }
},
+ // Claude only. `launch.native` is the captured launch for every ordinary LOCAL Claude run
+ // (launchOverrides.ts), not a signal the pane is elsewhere, so it must not gate this off. A DSH
+ // agent's pane is the one case that may run on a different host entirely, whose `claude --bg`
+ // jobs this process cannot see.
+ ...(session.engine === 'claude' && !session.dsh ? { stopConflictingJob: () =>
+ // The exact environment the pane is about to get, the same way `respawn` above builds it: `launch.env`
+ // already carries a native launch's own CLAUDE_CONFIG_DIR (launchOverrides.ts merges `native.environment`
+ // into it), and `engineLaunchEnv` adds Windows's own-process variables.
+ stopConflictingBackgroundJob({ bin: engineBin(session.engine), sessionId: session.sessionId,
+ env: { ...process.env, ...launch.env, ...engineLaunchEnv(session.engine, launch.native) } }) } : {}),
log: (message) => console.log(message),
}
}
diff --git a/cli/src/lib/claudeBackgroundJob.spec.ts b/cli/src/lib/claudeBackgroundJob.spec.ts
new file mode 100644
index 000000000..6df1558e3
--- /dev/null
+++ b/cli/src/lib/claudeBackgroundJob.spec.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from 'vitest'
+import { conflictingBackgroundJob, stopConflictingBackgroundJob, type ClaudeAgentListEntry } from './claudeBackgroundJob.js'
+
+const BG_MATCH: ClaudeAgentListEntry = { id: '06b52258', sessionId: 's1', kind: 'background' }
+const BG_OTHER: ClaudeAgentListEntry = { id: 'aaaa1111', sessionId: 's2', kind: 'background' }
+const INTERACTIVE_MATCH: ClaudeAgentListEntry = { sessionId: 's1', kind: 'interactive', pid: 1 }
+
+describe('conflictingBackgroundJob', () => {
+ it('finds the live background job holding the exact session', () => {
+ expect(conflictingBackgroundJob([BG_OTHER, BG_MATCH], 's1')).toEqual(BG_MATCH)
+ })
+ it('ignores a different session id', () => {
+ expect(conflictingBackgroundJob([BG_OTHER], 's1')).toBeNull()
+ })
+ it('ignores a non-background kind even with the same session id', () => {
+ expect(conflictingBackgroundJob([INTERACTIVE_MATCH], 's1')).toBeNull()
+ })
+ it('ignores an entry with no id', () => {
+ expect(conflictingBackgroundJob([{ sessionId: 's1', kind: 'background' }], 's1')).toBeNull()
+ })
+ it('is null for an empty list', () => {
+ expect(conflictingBackgroundJob([], 's1')).toBeNull()
+ })
+})
+
+describe('stopConflictingBackgroundJob', () => {
+ it('stops the live background job holding the exact session, then waits for it to leave the listing', async () => {
+ const calls: Array<{ args: readonly string[]; timeoutMs: number }> = []
+ let listCount = 0
+ const exec = async (bin: string, args: readonly string[], timeoutMs: number) => {
+ calls.push({ args, timeoutMs })
+ if (args[0] === 'agents') {
+ listCount++
+ // First list: still held. Second list (after stop): gone.
+ return JSON.stringify(listCount === 1 ? [BG_MATCH] : [])
+ }
+ if (args[0] === 'stop') return ''
+ throw new Error(`unexpected exec ${args.join(' ')}`)
+ }
+ await stopConflictingBackgroundJob({ bin: 'claude', sessionId: 's1', exec })
+ expect(calls).toEqual([
+ { args: ['agents', '--json'], timeoutMs: 3_000 },
+ { args: ['stop', '06b52258'], timeoutMs: 3_000 },
+ { args: ['agents', '--json'], timeoutMs: 3_000 },
+ ])
+ })
+
+ it('never stops a background job that is not the exact session being resumed', async () => {
+ const calls: string[][] = []
+ const exec = async (_bin: string, args: readonly string[]) => {
+ calls.push([...args])
+ return args[0] === 'agents' ? JSON.stringify([BG_OTHER]) : ''
+ }
+ await stopConflictingBackgroundJob({ bin: 'claude', sessionId: 's1', exec })
+ expect(calls).toEqual([['agents', '--json']])
+ })
+
+ it('is a no-op when the listing fails (missing subcommand, non-zero exit, timeout)', async () => {
+ const calls: string[][] = []
+ const exec = async (_bin: string, args: readonly string[]) => { calls.push([...args]); return null }
+ await expect(stopConflictingBackgroundJob({ bin: 'claude', sessionId: 's1', exec })).resolves.toBeUndefined()
+ expect(calls).toEqual([['agents', '--json']])
+ })
+
+ it('is a no-op when the listing is not the documented JSON array', async () => {
+ const exec = async (_bin: string, args: readonly string[]) => args[0] === 'agents' ? 'not json' : ''
+ await expect(stopConflictingBackgroundJob({ bin: 'claude', sessionId: 's1', exec })).resolves.toBeUndefined()
+ })
+
+ it('resolves without throwing when the stop call itself fails', async () => {
+ const log: string[] = []
+ const exec = async (_bin: string, args: readonly string[]) =>
+ args[0] === 'agents' ? JSON.stringify([BG_MATCH]) : null
+ await expect(stopConflictingBackgroundJob({ bin: 'claude', sessionId: 's1', exec, log: m => log.push(m) })).resolves.toBeUndefined()
+ expect(log[0]).toContain('could not stop background job 06b52258')
+ })
+
+ it('gives up waiting for the job to leave the listing after its bounded budget, never hanging', async () => {
+ let clock = 0
+ const now = () => clock
+ const sleep = async (ms: number) => { clock += ms }
+ let listCalls = 0
+ const exec = async (_bin: string, args: readonly string[]) => {
+ if (args[0] === 'stop') return ''
+ listCalls++
+ return JSON.stringify([BG_MATCH]) // never leaves the listing
+ }
+ await stopConflictingBackgroundJob({ bin: 'claude', sessionId: 's1', exec, now, sleep, pollBudgetMs: 1_000, pollIntervalMs: 250 })
+ // One list before the stop, then polls while now() < deadline (4 more at 250ms steps to reach 1000).
+ expect(listCalls).toBe(5)
+ expect(clock).toBeGreaterThanOrEqual(1_000)
+ })
+
+ it('passes the launch binary, session env and bin through to every call', async () => {
+ const seen: Array<{ bin: string; env?: NodeJS.ProcessEnv }> = []
+ const env = { CLAUDE_CONFIG_DIR: '/custom' }
+ const exec = async (bin: string, args: readonly string[], _timeoutMs: number, callEnv?: NodeJS.ProcessEnv) => {
+ seen.push({ bin, env: callEnv })
+ return args[0] === 'agents' ? JSON.stringify([]) : ''
+ }
+ await stopConflictingBackgroundJob({ bin: '/opt/claude/claude', sessionId: 's1', env, exec })
+ expect(seen).toEqual([{ bin: '/opt/claude/claude', env }])
+ })
+})
diff --git a/cli/src/lib/claudeBackgroundJob.ts b/cli/src/lib/claudeBackgroundJob.ts
new file mode 100644
index 000000000..9bfd170f8
--- /dev/null
+++ b/cli/src/lib/claudeBackgroundJob.ts
@@ -0,0 +1,99 @@
+/**
+ * Before Harness resumes a Claude Code session in a pane (`claude --resume <sessionId>`), stop any
+ * `claude --bg` background job still holding that SAME session: Claude Code refuses the resume while
+ * one is live ("that session is running in the background (<short>). Run `claude attach …` or
+ * `claude stop …` first"), and the pane fell back to a shell. Claude engine only — see `launch.ts`'s
+ * `resumeArgs`.
+ *
+ * `claude agents --help` (2.1.283): "--all With --json: also include completed background sessions."
+ * Left out, the listing is already live-only — measured locally, a failed job present with `--all`
+ * disappears without it — so this never has to guess which state strings still mean "running" (an
+ * allow-list of today's state strings would silently stop matching once Claude Code shipped a new one).
+ *
+ * Every failure — a `claude` with no `agents`/`stop` subcommand, a listing that errors, output that is
+ * not the JSON array documented — is swallowed into a no-op. A background job this cannot read or stop
+ * must never block the resume it exists to unblock; the resume still runs and reports Claude Code's own
+ * refusal if the job really is in the way.
+ */
+import { execFile } from 'node:child_process'
+import { patientExec } from './patientExec.js'
+
+export interface ClaudeAgentListEntry {
+ id?: string
+ sessionId?: string
+ kind?: string
+ [key: string]: unknown
+}
+
+/** `null` means the call did not answer (missing subcommand, non-zero exit, timeout) — never thrown. */
+export type ClaudeAgentsExec = (bin: string, args: readonly string[], timeoutMs: number, env?: NodeJS.ProcessEnv) => Promise<string | null>
+
+// A spawn that throws synchronously (EMFILE, a bad binary path) is a failed call too, not a rejected resume.
+const defaultExec: ClaudeAgentsExec = (bin, args, timeoutMs, env) => new Promise(resolve => {
+ try {
+ patientExec(execFile)(bin, args, { timeout: timeoutMs, ...(env ? { env } : {}) },
+ (error, stdout) => resolve(error ? null : stdout))
+ } catch {
+ resolve(null)
+ }
+})
+
+/** The one live background job (if any) holding the exact session Harness is about to resume. Never a
+ * session id prefix or a different job's: a wrong match would stop someone else's conversation. */
+export function conflictingBackgroundJob(entries: readonly ClaudeAgentListEntry[], sessionId: string): ClaudeAgentListEntry | null {
+ return entries.find(entry => entry.kind === 'background' && entry.sessionId === sessionId && !!entry.id) ?? null
+}
+
+async function liveBackgroundJobs(bin: string, exec: ClaudeAgentsExec, timeoutMs: number, env?: NodeJS.ProcessEnv): Promise<ClaudeAgentListEntry[]> {
+ const out = await exec(bin, ['agents', '--json'], timeoutMs, env)
+ if (out === null) return []
+ try {
+ const parsed = JSON.parse(out)
+ return Array.isArray(parsed) ? parsed as ClaudeAgentListEntry[] : []
+ } catch {
+ return []
+ }
+}
+
+export interface StopConflictingBackgroundJobOptions {
+ /** The exact Claude binary the resume itself is about to run — never a bare `claude` on PATH, which
+ * could resolve to a different install than the one that owns `~/.claude/jobs`. */
+ bin: string
+ /** The session id Harness is about to pass to `--resume`. */
+ sessionId: string
+ /** The environment the resume launch itself will run with (its `CLAUDE_CONFIG_DIR`, grid/gateway
+ * variables): the job list and stop must be read from the SAME jobs store the resume will see. */
+ env?: NodeJS.ProcessEnv
+ log?: (message: string) => void
+ exec?: ClaudeAgentsExec
+ sleep?: (ms: number) => Promise<void>
+ now?: () => number
+ listTimeoutMs?: number
+ stopTimeoutMs?: number
+ /** The longest this waits for the stopped job to leave the live listing. */
+ pollBudgetMs?: number
+ pollIntervalMs?: number
+}
+
+const defaultSleep = (ms: number) => new Promise<void>(resolve => { const t = setTimeout(resolve, ms); t.unref?.() })
+
+export async function stopConflictingBackgroundJob(options: StopConflictingBackgroundJobOptions): Promise<void> {
+ const {
+ bin, sessionId, env, log = () => {}, exec = defaultExec, sleep = defaultSleep, now = Date.now,
+ listTimeoutMs = 3_000, stopTimeoutMs = 3_000, pollBudgetMs = 5_000, pollIntervalMs = 250,
+ } = options
+ const shortSession = sessionId.slice(0, 8)
+ const job = conflictingBackgroundJob(await liveBackgroundJobs(bin, exec, listTimeoutMs, env), sessionId)
+ if (!job?.id) return
+ const stopped = await exec(bin, ['stop', job.id], stopTimeoutMs, env)
+ if (stopped === null) {
+ log(`[resume] could not stop background job ${job.id} holding session ${shortSession} — resuming anyway`)
+ return
+ }
+ log(`[resume] stopped background job ${job.id} holding session ${shortSession}`)
+ const deadline = now() + pollBudgetMs
+ while (now() < deadline) {
+ if (!conflictingBackgroundJob(await liveBackgroundJobs(bin, exec, listTimeoutMs, env), sessionId)) return
+ await sleep(pollIntervalMs)
+ }
+}
diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.ts
index 1251ab550..08bc8fcf0 100644
--- a/cli/src/lib/restartAgent.spec.ts
+++ b/cli/src/lib/restartAgent.spec.ts
@@ -11,6 +11,7 @@ interface Overrides {
waitForProcess?: RestartAgentDeps['waitForProcess']
buildArgv?: RestartAgentDeps['buildArgv']
prepareResume?: RestartAgentDeps['prepareResume']
+ stopConflictingJob?: RestartAgentDeps['stopConflictingJob']
}
/** Every primitive records its own call, even when overridden — so `calls` always reflects the real
@@ -25,6 +26,7 @@ function deps(over: Overrides = {}): RestartAgentDeps & { calls: string[] } {
return {
calls,
...(over.prepareResume ? { prepareResume: async () => { calls.push('prepareResume'); await over.prepareResume!() } } : {}),
+ ...(over.stopConflictingJob ? { stopConflictingJob: async () => { calls.push('stopConflictingJob'); await over.stopConflictingJob!() } } : {}),
holdOpen: async () => { calls.push('holdOpen'); return holdOpenImpl() },
terminate: async (checkAfterMs) => { calls.push('terminate'); return terminateImpl(checkAfterMs) },
respawn: async (argv) => { calls.push('respawn'); return respawnImpl(argv) },
@@ -56,6 +58,29 @@ describe('restartAgent', () => {
expect(d.calls).toEqual(['holdOpen', 'terminate', 'prepareResume'])
})
+ it('stops a conflicting background job after history preparation and before the resume argv is built', async () => {
+ const stopConflictingJob = vi.fn()
+ const d = deps({ stopConflictingJob })
+ await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)
+ expect(d.calls).toEqual(['holdOpen', 'terminate', 'stopConflictingJob', 'buildArgv', 'respawn', 'waitForProcess'])
+ expect(stopConflictingJob).toHaveBeenCalledTimes(1)
+ })
+
+ it('never checks for a background job on a fresh launch (no session id to resume)', async () => {
+ const stopConflictingJob = vi.fn()
+ const d = deps({ stopConflictingJob, waitForProcess: async () => null })
+ await restartAgent({ engine: 'claude', sessionId: '' }, false, d)
+ expect(stopConflictingJob).not.toHaveBeenCalled()
+ })
+
+ it('does nothing extra for an engine with no background-job check wired (the dep is simply absent)', async () => {
+ const d = deps()
+ expect(d.stopConflictingJob).toBeUndefined()
+ const outcome = await restartAgent({ engine: 'codex', sessionId: 's1' }, false, d)
+ expect(outcome.ok).toBe(true)
+ expect(d.calls).toEqual(['holdOpen', 'terminate', 'buildArgv', 'respawn', 'waitForProcess'])
+ })
+
it('does not prepare a fresh launch or repeat preparation on the fresh fallback', async () => {
const prepareResume = vi.fn()
const d = deps({ prepareResume, waitForProcess: async () => null })
diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.ts
index 9be0cc90a..d5e7d0486 100644
--- a/cli/src/lib/restartAgent.ts
+++ b/cli/src/lib/restartAgent.ts
@@ -102,6 +102,14 @@ export interface RestartAgentDeps {
/** Prepare persisted history only once the old writer is confirmed stopped. A failure must
* preserve the conversation, not enter the fresh-session fallback. */
prepareResume?: () => void | Promise<void>
+ /**
+ * Claude only: stop a `claude --bg` job still holding the session this is about to `--resume`
+ * (`lib/claudeBackgroundJob.ts`). Run once, after history preparation and before the resume
+ * argv is built, so a job that held the jobs store's lock is gone before Claude Code is asked to
+ * reopen it. A failure here must not block the restart it exists to unblock, so it is awaited for
+ * ordering only, never allowed to fail the restart; implementations swallow their own errors.
+ */
+ stopConflictingJob?: () => Promise<void>
buildArgv: (opts: { bypassPermission: boolean; resumeSessionId?: string }) => string[]
/** Why the relaunch [buildArgv] would build is refused on this platform (a Windows batch-file engine whose arguments
* cmd.exe would read, lib/windows/launch.ts), asked before anything is stopped; null when it is not. */
@@ -154,6 +162,8 @@ export async function restartAgent(
}
}
if (!current()) return changed
+ if (resumeSessionId && deps.stopConflictingJob) await deps.stopConflictingJob()
+ if (!current()) return changed
const spawnAndWait = async (withResume: boolean): Promise<ProcessIdentity | null> => {
if (!current()) return null
const argv = deps.buildArgv({
diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.ts
index 2244a5f8a..e5f12d2ae 100644
--- a/cli/src/lib/resumeAgentService.spec.ts
+++ b/cli/src/lib/resumeAgentService.spec.ts
@@ -15,7 +15,8 @@ import { checkPidRuntime } from './deleteAgentFallback.js'
import { checkSessionRuntime, resolvePaneEngineProcess } from './paneEngineProcess.js'
import { windowsAfterExit, windowsPaneLaunch } from './windows/engineStart.js'
import { buildEngineLaunchArgv, dropPermissionFlagIfUnsupported, engineLaunchEnv, refusePermissionFlagIfUnsupported } from './engineLaunch.js'
-import { enginePathOverride } from './engineBin.js'
+import { engineBin, enginePathOverride } from './engineBin.js'
+import { stopConflictingBackgroundJob } from './claudeBackgroundJob.js'
import { installedDsh } from '../dsh/installed.js'
import { createLaunchHelpers } from '../core/agents/launch.js'
import { createLaunchAuthority } from '../core/agents/launchAuthority.js'
@@ -41,7 +42,8 @@ vi.mock('./engineLaunch.js', async importOriginal => ({
dropPermissionFlagIfUnsupported: vi.fn(async (_engine: unknown, choice: unknown) => ({ choice, droppedFlag: null })),
refusePermissionFlagIfUnsupported: vi.fn(async () => null),
}))
-vi.mock('./engineBin.js', () => ({ enginePathOverride: vi.fn(() => undefined) }))
+vi.mock('./engineBin.js', () => ({ enginePathOverride: vi.fn(() => undefined), engineBin: vi.fn((engine: string) => engine) }))
+vi.mock('./claudeBackgroundJob.js', () => ({ stopConflictingBackgroundJob: vi.fn(async () => {}) }))
vi.mock('./engineInstall.js', async original => ({ ...await original<object>(), engineInstallRecipe: () => ({ command: 'fixture-install' }) }))
vi.mock('../dsh/installed.js', () => ({ installedDsh: vi.fn() }))
vi.mock('../engines/transcriptBindings.js', async original => ({ ...await original<object>(), controlTranscriptEvidence: vi.fn() }))
@@ -350,6 +352,52 @@ describe('production resume handler', () => {
expect(buildEngineLaunchArgv).toHaveBeenCalledWith('opencode', expect.objectContaining({ resumeSessionId: saved.sessionId }))
})
+ it('stops a live `claude --bg` job on the exact session before building the resume argv', async () => {
+ rewrite({ engine: 'claude' })
+ expect(await start()).toMatchObject({ ok: true, resumed: true })
+ expect(stopConflictingBackgroundJob).toHaveBeenCalledWith(expect.objectContaining({
+ bin: engineBin('claude'), sessionId: saved.sessionId,
+ }))
+ const stopOrder = vi.mocked(stopConflictingBackgroundJob).mock.invocationCallOrder[0]
+ const argvOrder = vi.mocked(buildEngineLaunchArgv).mock.invocationCallOrder[0]
+ expect(stopOrder).toBeLessThan(argvOrder)
+ })
+
+ it('never checks for a background job on a fresh or fork launch (no resumeSessionId)', async () => {
+ rewrite({ engine: 'claude', sessionId: '' })
+ await start()
+ expect(stopConflictingBackgroundJob).not.toHaveBeenCalled()
+ })
+
+ it('does not check for a background job on a non-Claude engine', async () => {
+ expect(saved.engine).toBe('codex')
+ await start()
+ expect(stopConflictingBackgroundJob).not.toHaveBeenCalled()
+ })
+
+ it('skips the background-job check for a DSH agent: its pane may run on a different host', async () => {
+ rewrite({ engine: 'claude', dsh: { id: 'fixture-dsh', url: 'https://example.test' } as any })
+ vi.mocked(installedDsh).mockReturnValue(true as any)
+ await start()
+ expect(stopConflictingBackgroundJob).not.toHaveBeenCalled()
+ })
+
+ it('still checks for a background job on a captured-native launch, with that launch\'s own environment', async () => {
+ // `native` is the captured launch for every ordinary LOCAL Claude run (launchOverrides.ts), not a
+ // signal the pane is elsewhere — it must not turn this off. `launchEnv` here stands in for what
+ // launchOverrides.ts really produces: `native.environment` (its CLAUDE_CONFIG_DIR) merged in already.
+ rewrite({ engine: 'claude' })
+ const native: NativeLaunch = { token: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', opencodeMajor: null,
+ environment: { CLAUDE_CONFIG_DIR: '/native/claude-home' }, proofs: [], current: vi.fn(() => true),
+ prepareHooks: vi.fn(async () => true), permission: vi.fn(async () => 'supported' as const) }
+ vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: true,
+ overrides: { env: { CLAUDE_CONFIG_DIR: '/native/claude-home' }, extraArgs: [], clearEnv: [], native } })
+ await start()
+ expect(stopConflictingBackgroundJob).toHaveBeenCalledWith(expect.objectContaining({
+ sessionId: saved.sessionId, env: expect.objectContaining({ CLAUDE_CONFIG_DIR: '/native/claude-home' }),
+ }))
+ })
+
it('marks an engine with no startup hook ready off its own process', async () => {
// muse never hooks, so nothing else would ever leave this row `starting` — it would read as
// "Starting" for ever and keep discovery out of the pane.
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
index ed9c12b07..2f52d2480 100644
--- a/cli/src/lib/resumeAgentService.ts
+++ b/cli/src/lib/resumeAgentService.ts
@@ -11,8 +11,9 @@ import type { StoppedAgentStore } from './stoppedAgents.js'
import { resumeStoppedAgent, waitForResumedAgent, resumeChanged, resumeUnconfirmed, RESUME_READINESS_BUDGET_MS } from './resumeStoppedAgent.js'
import { checkPidRuntime } from './deleteAgentFallback.js'
import { checkSessionRuntime, resolvePaneEngineProcess } from './paneEngineProcess.js'
-import { enginePathOverride } from './engineBin.js'
+import { engineBin, enginePathOverride } from './engineBin.js'
import { engineInstallRecipe } from './engineInstall.js'
+import { stopConflictingBackgroundJob } from './claudeBackgroundJob.js'
import { buildEngineLaunchArgv, dropPermissionFlagIfUnsupported, engineLaunchEnv, permissionModeApproves, permissionModeFlags, refusePermissionFlagIfUnsupported } from './engineLaunch.js'
import { workspaceMissing } from './workspaceCheck.js'
import { buildHarnessSessionLabel } from './harnessSessionLabel.js'
@@ -308,6 +309,24 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
console.warn(`[resume] ${sid(saved.agentId)} · ${saved.engine} does not take ${droppedFlag}`
+ ` · resuming in Ask · update ${saved.engine} to get ${saved.permissionMode ?? 'Auto'} back`)
}
+ // Claude Code refuses `--resume` on a session a `claude --bg` job still has open ("that session
+ // is running in the background … run `claude attach …` or `claude stop …` first"). Claude only.
+ // `native` is the captured launch for every ordinary local Claude run (launchOverrides.ts), not
+ // just grid — it is NOT a signal the pane is elsewhere, so it must not gate this off. A DSH
+ // agent's pane is the one case that may run on a different host entirely, whose jobs store this
+ // process cannot see (and must not touch).
+ if (resumeSessionId && saved.engine === 'claude' && !saved.dsh) {
+ // The exact environment the pane is about to get (built below as `paneEnv`): `launchEnv`
+ // already carries a native launch's own CLAUDE_CONFIG_DIR (launchOverrides.ts merges
+ // `native.environment` into it), and `engineLaunchEnv` adds Windows's own-process variables.
+ await stopConflictingBackgroundJob({
+ bin: engineBin(saved.engine), sessionId: resumeSessionId,
+ env: { ...process.env, ...launchEnv, ...engineLaunchEnv(saved.engine, built.overrides.native) },
+ log: message => console.log(`[resume] ${sid(saved.agentId)} ${message}`),
+ })
+ transcript?.verify()
+ if (!current()) return resumeChanged
+ }
const options = {
...(built.overrides.native ? { native: built.overrides.native } : {}),
resumeSessionId,