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.

12.7 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import fs from 'fs'
import os from 'os'
import path from 'path'
import { WINDOWS_INLINE_PROMPT_ERROR, localAgentCwd, planAgent, resolveBinary, runAgent } from './commit-message'

/**
 * The 2026-08-05 report: "AI commit message" failed on every SSH project with
 *
 *     Error: spawn /Users/enes/.local/bin/claude ENOENT
 *
 * which reads as "claude is not installed" and is not. Node reports a MISSING WORKING DIRECTORY as
 * `spawn <command> ENOENT`, naming the binary rather than the directory — and the directory was an
 * SSH project's cwd, a path that exists on the server and not on the Mac doing the spawning.
 *
 * The agent spawn is local by design (only the git reads route over the ControlMaster, and the diff
 * is inside the prompt by then), so the fix is to not hand it a remote path.
 */
describe('localAgentCwd', () => {
  it('uses the project folder for a LOCAL project', () => {
    expect(localAgentCwd('/Users/enes/code/app', false, '/Users/enes')).toBe('/Users/enes/code/app')
  })

  it('falls back to home for a REMOTE project — that path is on the server', () => {
    expect(localAgentCwd('/root/nodeterm', true, '/Users/enes')).toBe('/Users/enes')
  })

  it('falls back to home for a project with no folder at all', () => {
    // The pre-existing `cwd || os.homedir()` behaviour, kept.
    expect(localAgentCwd('', false, '/Users/enes')).toBe('/Users/enes')
  })
})

describe('runAgent — where the agent is actually spawned', () => {
  afterEach(() => {
    vi.resetModules()
    vi.restoreAllMocks()
  })

  /**
   * Drives the REAL `runAgent` with `child_process.spawn` mocked, so what is asserted is the
   * directory the process would have been started in — the thing the bug was about. The helper
   * test above cannot catch a regression that stops CALLING the helper; this one can.
   */
  async function spawnCwdFor(cwd: string, remote: boolean): Promise<string | undefined> {
    // FIRST, before the mock: this file imports `commit-message` statically for `localAgentCwd`, so
    // without a reset the dynamic import below would hand back that already-loaded instance — the
    // one that closed over the REAL `spawn` at import time. The mock would then be installed and
    // never consulted, and the test would silently run `sh` for real and observe nothing.
    vi.resetModules()
    let seen: string | undefined
    vi.doMock('child_process', async () => {
      const actual = await vi.importActual<typeof import('child_process')>('child_process')
      return {
        ...actual,
        default: actual,
        spawn: (_bin: string, _args: string[], opts: { cwd: string }) => {
          seen = opts.cwd
          // The narrowest fake that lets `spawnAgent`'s promise settle: streams it reads, and a
          // close event carrying a usable message so the run does not take the error path.
          const listeners: Record<string, Array<(...a: unknown[]) => void>> = {}
          const child = {
            stdout: { on: (_e: string, cb: (d: Buffer) => void) => cb(Buffer.from('a message')) },
            stderr: { on: () => {} },
            stdin: { write: () => {}, end: () => {}, on: () => {} },
            kill: () => {},
            on: (e: string, cb: (...a: unknown[]) => void) => {
              ;(listeners[e] ??= []).push(cb)
              if (e === 'close') setTimeout(() => cb(0), 0)
            }
          }
          return child
        }
      }
    })
    // Both imports have to come AFTER `doMock`, and from the SAME fresh registry: `doMock` reloads
    // the whole graph, so a resolver set through the statically-imported module would be written to
    // a different instance than the one the reloaded `commit-message` reads.
    const remoteGit = await import('./remote-ssh/remote-git')
    remoteGit.setGitRemoteResolver(remote ? () => ({}) as never : null)
    const { runAgent } = await import('./commit-message')
    // `sh` rather than the claude/codex branches: `planAgent` resolves a real binary before
    // spawning, and this test is about the cwd, not about what is installed on the test machine.
    await runAgent('prompt', cwd, {
      commitAgent: 'custom',
      commitAgentCommand: 'sh',
      commitPromptExtra: ''
    } as never)
    return seen
  }

  it('spawns in the project folder for a local project', async () => {
    expect(await spawnCwdFor('/tmp', false)).toBe('/tmp')
  })

  it('does NOT spawn in an SSH project’s remote path — that is the ENOENT', async () => {
    // `/root/nodeterm` exists on the server and nowhere on the machine doing the spawning.
    expect(await spawnCwdFor('/root/nodeterm', true)).toBe(os.homedir())
  })
})

/**
 * `resolveBinary` decides which CLI "AI commit message" and "Name with AI" spawn. It was POSIX-only
 * in two ways at once on Windows: `startsWith('/')` never recognised an absolute path there, and the
 * hardcoded fallbacks are extensionless POSIX paths that no Windows install can match.
 */
describe('resolveBinary', () => {
  let dir: string

  beforeEach(() => {
    dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-resolve-bin-'))
  })
  afterEach(() => {
    fs.rmSync(dir, { recursive: true, force: true })
  })

  it('accepts an absolute path that exists, and rejects one that does not', () => {
    // The regression: on Windows this argument is `C:\…`, which `startsWith('/')` never matched, so
    // an absolute custom command fell through to the bare-name branch and was rejected there for
    // containing `:` and `\`.
    const bin = path.join(dir, 'agent.exe')
    fs.writeFileSync(bin, '', { mode: 0o755 })
    expect(resolveBinary(bin)).toBe(bin)
    expect(resolveBinary(path.join(dir, 'absent.exe'))).toBeNull()
  })

  it('refuses a relative path — only a bare name or an absolute path may be spawned', () => {
    // Anything that is not a bare binary name stays well out of injection territory.
    expect(resolveBinary('../../evil')).toBeNull()
    expect(resolveBinary('sub/dir/agent')).toBeNull()
    expect(resolveBinary('agent; rm -rf /')).toBeNull()
  })

  it('answers null for a bare name that is nowhere', () => {
    expect(resolveBinary('nt-definitely-not-installed')).toBeNull()
  })
})

describe.skipIf(process.platform !== 'win32')('runAgent — Windows npm shim', () => {
  let dir: string

  beforeEach(() => {
    dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-commit-shim-'))
  })
  afterEach(() => {
    fs.rmSync(dir, { recursive: true, force: true })
  })

  it('keeps a hostile prompt as one argument without interpreting it as cmd syntax', async () => {
    const cmd = path.join(dir, 'fake agent.cmd')
    const script = path.join(dir, 'fake-agent.js')
    const touched = path.join(dir, 'should-not-exist.txt')
    fs.writeFileSync(
      script,
      "process.stdout.write(Buffer.from(process.argv[2] ?? '', 'utf8').toString('base64'))\n"
    )
    fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
    const prompt = `message & echo pwned > "${touched}"`

    vi.resetModules()
    vi.doUnmock('child_process')
    const { runAgent } = await import('./commit-message')
    const result = await runAgent(prompt, dir, {
      commitAgent: 'custom',
      commitAgentCommand: `"${cmd}" "{prompt}"`,
      commitExtraPrompt: ''
    } as never)

    expect(result).toEqual({
      ok: true,
      message: Buffer.from(prompt, 'utf8').toString('base64')
    })
    expect(fs.existsSync(touched)).toBe(false)
  })

  it('preserves multiline Unicode stdin as a byte stream through the cmd shim', async () => {
    const cmd = path.join(dir, 'stdin agent.cmd')
    const script = path.join(dir, 'stdin-agent.js')
    fs.writeFileSync(
      script,
      [
        'const chunks = []',
        "process.stdin.on('data', (chunk) => chunks.push(chunk))",
        "process.stdin.on('end', () => process.stdout.write(Buffer.concat(chunks).toString('base64')))"
      ].join('\n')
    )
    fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
    const prompt = 'first line\r\nsegunda linha: café 日本語\nlast line'

    vi.resetModules()
    vi.doUnmock('child_process')
    const { runAgent } = await import('./commit-message')
    const result = await runAgent(prompt, dir, {
      commitAgent: 'custom',
      commitAgentCommand: `"${cmd}"`,
      commitExtraPrompt: ''
    } as never)

    expect(result).toEqual({
      ok: true,
      message: Buffer.from(prompt, 'utf8').toString('base64')
    })
  })
})

describe('AI naming account + error output', () => {
  it('treats a CLI auth error printed to stdout as a failure, not an answer', async () => {
    const { isCliErrorOutput } = await import('./commit-message')
    expect(isCliErrorOutput('Failed to authenticate: OAuth session expired')).toBe(true)
    expect(isCliErrorOutput('Invalid API key · Please run /login')).toBe(true)
    expect(isCliErrorOutput('API Error: 401 {"type":"error"}')).toBe(true)
    expect(isCliErrorOutput('Refactor Auth Flow')).toBe(false)
  })

  it('runs under the account config dir with shadowing auth vars stripped', async () => {
    const { claudeAccountEnv } = await import('./commit-message')
    const env = claudeAccountEnv(
      { PATH: '/bin', ANTHROPIC_API_KEY: 'k', CLAUDE_CODE_OAUTH_TOKEN: 't' },
      '/data/claude-accounts/a1'
    )
    expect(env.CLAUDE_CONFIG_DIR).toBe('/data/claude-accounts/a1')
    expect(env.ANTHROPIC_API_KEY).toBeUndefined()
    expect(env.CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined()
    expect(env.PATH).toBe('/bin')
  })
})

/**
 * `{prompt}` inlines the prompt as one argv element. On Windows an npm `.cmd` shim refuses a CR/LF
 * argument outright and every CLI is capped by CreateProcess's command-line length, so that plan is
 * refused with a sentence up front; `{promptFile}` (a private temp file's path) works everywhere.
 */
describe('planAgent — {prompt} / {promptFile}', () => {
  let dir: string
  const custom = (cmd: string) => ({ commitAgent: 'custom', commitAgentCommand: cmd }) as never
  const PROMPT = 'Write a commit message.\nStaged diff:\n+ x'

  beforeEach(() => {
    dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-plan-'))
  })
  afterEach(() => {
    fs.rmSync(dir, { recursive: true, force: true })
  })

  const bin = (name: string): string => {
    const p = path.join(dir, name)
    fs.writeFileSync(p, '')
    return p
  }

  it('writes {promptFile} as a private file, substitutes its path, and cleanup removes it', () => {
    const agent = bin('agent')
    const plan = planAgent(custom(`${agent} --file {promptFile}`), PROMPT, { tmpDir: dir })
    if ('error' in plan) throw new Error(plan.error)
    expect(plan.stdin).toBeNull()
    expect(plan.args[0]).toBe('--file')
    const file = plan.args[1]
    expect(path.dirname(path.dirname(file))).toBe(dir)
    expect(fs.readFileSync(file, 'utf8')).toBe(PROMPT)
    if (process.platform !== 'win32') expect(fs.statSync(file).mode & 0o777).toBe(0o600)
    plan.cleanup?.()
    expect(fs.existsSync(path.dirname(file))).toBe(false)
  })

  it('keeps POSIX {prompt} inline and the default on stdin, unchanged', () => {
    const agent = bin('agent')
    expect(planAgent(custom(`${agent} -p {prompt}`), PROMPT, { platform: 'linux' })).toEqual({
      bin: agent,
      args: ['-p', PROMPT],
      stdin: null
    })
    expect(planAgent(custom(`${agent} -p`), PROMPT, { platform: 'darwin' })).toEqual({
      bin: agent,
      args: ['-p'],
      stdin: PROMPT
    })
  })

  it('refuses {prompt} for a .cmd shim on win32 with an actionable sentence', () => {
    const shim = bin('mycli.cmd')
    expect(planAgent(custom(`${shim} {prompt}`), PROMPT, { platform: 'win32' })).toEqual({
      error: WINDOWS_INLINE_PROMPT_ERROR
    })
  })

  it('refuses {prompt} past the Windows command-line limit even for an .exe', () => {
    const exe = bin('agent.exe')
    const long = 'x'.repeat(40_000)
    expect(planAgent(custom(`${exe} {prompt}`), long, { platform: 'win32' })).toEqual({
      error: WINDOWS_INLINE_PROMPT_ERROR
    })
    expect(planAgent(custom(`${exe} {prompt}`), 'short', { platform: 'win32' })).toMatchObject({
      args: ['short']
    })
  })

  it('serves {promptFile} on win32 for the same .cmd shim', () => {
    const shim = bin('mycli.cmd')
    const plan = planAgent(custom(`${shim} --file {promptFile}`), PROMPT, { platform: 'win32', tmpDir: dir })
    expect('error' in plan).toBe(false)
    if (!('error' in plan)) plan.cleanup?.()
  })

  it.skipIf(process.platform === 'win32')('runAgent hands the file to a real CLI and removes it after', async () => {
    const before = new Set(fs.readdirSync(os.tmpdir()).filter((n) => n.startsWith('nt-prompt-')))
    const r = await runAgent('Fix the parser', dir, custom('cat {promptFile}'))
    expect(r).toEqual({ ok: true, message: 'Fix the parser' })
    const after = fs.readdirSync(os.tmpdir()).filter((n) => n.startsWith('nt-prompt-') && !before.has(n))
    expect(after).toEqual([])
  })
})