Merge pull request #147 from omdsh-dev/fix/node-pty-load-failure-repair

fix: node-pty 加载失败降级为终端修复提示,不再拖垮 server(#140)
This commit is contained in:
Atlas Zeng
2026-08-17 00:06:20 +08:00
committed by GitHub
parent a0918496f3
commit 8d9ab1cd2f
19 changed files with 956 additions and 134 deletions
+205
View File
@@ -0,0 +1,205 @@
/**
* pty-deps unit tests (issue #140, plugin side): lazy node-pty loading,
* profile/plugin-root discovery, and the pasteable repair command — the
* degraded mode the terminal tab enters when node-pty cannot load, instead
* of the whole plugin (and `dsh web`) failing to boot.
*/
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, dirname } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
buildRepairCommand,
depsStatus,
DSH_NODE_PTY_RANGE,
findPluginRoot,
findProfileDir,
loadNodePty,
loadRequiredNodePty,
nodePtyLoadCause,
resetNodePtyCache,
} from '../src/pty-deps.ts'
import { SidebarError } from '../src/wire.ts'
/** A throw-only require: node-pty missing or its native binding broken. */
const failingRequire = (): never => { throw new Error('Cannot find package node-pty') }
describe('loadNodePty', () => {
beforeEach(() => { resetNodePtyCache() })
it('loads the real node-pty module in this repository', () => {
const mod = loadNodePty()
expect(mod).not.toBeNull()
expect(typeof mod?.spawn).toBe('function')
})
it('returns null and records the cause when the require throws', () => {
expect(loadNodePty(failingRequire)).toBeNull()
expect((nodePtyLoadCause() as Error).message).toBe('Cannot find package node-pty')
})
it('caches the first outcome (a later working require does not override)', () => {
expect(loadNodePty(failingRequire)).toBeNull()
expect(loadNodePty(() => ({ spawn: () => undefined }))).toBeNull()
resetNodePtyCache()
expect(loadNodePty(() => ({ spawn: () => undefined }))).not.toBeNull()
})
it('loadRequiredNodePty throws the canonical degraded-mode error', () => {
loadNodePty(failingRequire)
let thrown: unknown
try {
loadRequiredNodePty()
} catch (error) {
thrown = error
}
expect(thrown).toBeInstanceOf(SidebarError)
expect((thrown as SidebarError).code).toBe('pty-deps-missing')
expect((thrown as SidebarError).status).toBe(503)
})
})
describe('buildRepairCommand', () => {
let root: string
let pluginRoot: string
let profileDir: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'pty-deps-'))
pluginRoot = join(root, 'plugin')
profileDir = join(root, 'profiles', 'web')
mkdirSync(join(pluginRoot, 'scripts'), { recursive: true })
mkdirSync(profileDir, { recursive: true })
writeFileSync(join(pluginRoot, 'scripts', 'install.sh'), '#!/usr/bin/env bash\n')
writeFileSync(join(pluginRoot, 'scripts', 'install.ps1'), '# ps1\n')
})
afterEach(() => { rmSync(root, { recursive: true, force: true }) })
it('posix: bash installer with --repair and the detected profile', () => {
const { command, note } = buildRepairCommand({ pluginRoot, profileDir, platform: 'darwin' })
expect(command).toBe(`bash "${join(pluginRoot, 'scripts', 'install.sh')}" --repair --profile "web"`)
expect(note).toBeUndefined()
})
it('posix: omits --profile when the profile could not be detected', () => {
const { command } = buildRepairCommand({ pluginRoot, profileDir: null, platform: 'linux' })
expect(command).toBe(`bash "${join(pluginRoot, 'scripts', 'install.sh')}" --repair`)
})
it('win32: powershell -ExecutionPolicy Bypass with -Repair and -Profile', () => {
const { command } = buildRepairCommand({ pluginRoot, profileDir, platform: 'win32' })
const expected = join(pluginRoot, 'scripts', 'install.ps1')
expect(command).toBe(`powershell -ExecutionPolicy Bypass -File "${expected}" -Repair -Profile "web"`)
})
it('falls back to the dsh plugin command when the plugin scripts are unavailable', () => {
const bareRoot = join(root, 'bare')
mkdirSync(bareRoot)
const { command, note } = buildRepairCommand({ pluginRoot: bareRoot, profileDir, platform: 'darwin' })
expect(command).toBe('dsh plugin --profile "web" install')
expect(note).toContain('allowBuilds')
})
it('falls back to the dsh plugin command (default web) when nothing is detectable', () => {
const { command } = buildRepairCommand({ pluginRoot: null, profileDir: null, platform: 'darwin' })
expect(command).toBe('dsh plugin --profile "web" install')
})
})
describe('findProfileDir / findPluginRoot', () => {
let root: string
let moduleFile: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'pty-deps-'))
// A fake plugin module deep inside the profile's pnpm node_modules.
const pkgRoot = join(root, 'profiles', 'web', 'node_modules', '.pnpm', 'dsh-better-sidebar@0.0.0', 'node_modules', 'dsh-better-sidebar')
const libDir = join(pkgRoot, 'lib')
mkdirSync(libDir, { recursive: true })
writeFileSync(join(root, 'profiles', 'web', 'package.json'), JSON.stringify({ name: 'dsh-profile-web' }))
writeFileSync(join(root, 'profiles', 'web', 'pnpm-workspace.yaml'), '')
writeFileSync(join(pkgRoot, 'package.json'), JSON.stringify({ name: 'dsh-better-sidebar' }))
moduleFile = join(libDir, 'index.js')
writeFileSync(moduleFile, '')
})
afterEach(() => { rmSync(root, { recursive: true, force: true }) })
it('walks up from the plugin module to the profile root (pnpm-workspace.yaml)', () => {
expect(findProfileDir(moduleFile)).toBe(realpathSync(join(root, 'profiles', 'web')))
})
it('walks up to the plugin package root by package.json name', () => {
expect(findPluginRoot(moduleFile)).toBe(realpathSync(join(root, 'profiles', 'web', 'node_modules', '.pnpm', 'dsh-better-sidebar@0.0.0', 'node_modules', 'dsh-better-sidebar')))
})
it('falls back to $DSH_HOME/profiles/web when no ancestor looks like a profile', () => {
const home = join(root, 'home')
const web = join(home, 'profiles', 'web')
mkdirSync(web, { recursive: true })
writeFileSync(join(web, 'package.json'), JSON.stringify({ name: 'dsh-profile-web' }))
writeFileSync(join(web, 'pnpm-workspace.yaml'), '')
// A bare module path with no profile-like ancestor (the walk-up must miss).
const bareModule = join(root, 'elsewhere', 'lib', 'index.js')
mkdirSync(dirname(bareModule), { recursive: true })
writeFileSync(bareModule, '')
const previous = process.env.DSH_HOME
process.env.DSH_HOME = home
try {
expect(findProfileDir(bareModule)).toBe(realpathSync(web))
} finally {
if (previous === undefined) delete process.env.DSH_HOME
else process.env.DSH_HOME = previous
}
})
})
describe('depsStatus', () => {
let root: string
let moduleFile: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'pty-deps-'))
const pkgRoot = join(root, 'profiles', 'web', 'node_modules', '.pnpm', 'dsh-better-sidebar@0.0.0', 'node_modules', 'dsh-better-sidebar')
mkdirSync(join(pkgRoot, 'scripts'), { recursive: true })
mkdirSync(join(pkgRoot, 'lib'), { recursive: true })
writeFileSync(join(root, 'profiles', 'web', 'package.json'), JSON.stringify({ name: 'dsh-profile-web' }))
writeFileSync(join(root, 'profiles', 'web', 'pnpm-workspace.yaml'), '')
writeFileSync(join(pkgRoot, 'package.json'), JSON.stringify({ name: 'dsh-better-sidebar' }))
writeFileSync(join(pkgRoot, 'scripts', 'install.sh'), '#!/usr/bin/env bash\n')
moduleFile = join(pkgRoot, 'lib', 'index.js')
writeFileSync(moduleFile, '')
resetNodePtyCache()
})
afterEach(() => {
rmSync(root, { recursive: true, force: true })
resetNodePtyCache()
})
it('reports ok:true when node-pty loads', () => {
expect(depsStatus({ fromFile: moduleFile })).toEqual({ ok: true })
})
it('reports the cause, the repair command and the profile when the load fails', () => {
loadNodePty(failingRequire)
const status = depsStatus({ fromFile: moduleFile })
expect(status.ok).toBe(false)
if (status.ok) throw new Error('unreachable')
expect(status.cause).toBe('Cannot find package node-pty')
const script = realpathSync(join(root, 'profiles', 'web', 'node_modules', '.pnpm', 'dsh-better-sidebar@0.0.0', 'node_modules', 'dsh-better-sidebar', 'scripts', 'install.sh'))
expect(status.command).toBe(`bash "${script}" --repair --profile "web"`)
expect(status.profile).toBe('web')
})
})
describe('DSH sync contract', () => {
it('the declared node-pty range stays identical to DSH core (dsh-subprocess-local ^1.1.0)', () => {
expect(DSH_NODE_PTY_RANGE).toBe('^1.1.0')
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {
dependencies: Record<string, string>
}
expect(pkg.dependencies['node-pty']).toBe(DSH_NODE_PTY_RANGE)
})
})
+82
View File
@@ -0,0 +1,82 @@
/**
* TerminalDepsBanner tests (issue #140): the degraded-mode banner the
* terminal tab shows when node-pty fails to load. It must render the
* failure title, the PASTEABLE repair command (bash / cmd / PowerShell),
* a copy button that writes the command to the clipboard with a transient
* "Copied" feedback, and a retry button.
*
* The banner is tested directly (like PluginListBody): it is a pure
* presentational component, so server-side renderToString covers the
* static content and createRoot + act() covers the copy click.
*/
// @vitest-environment jsdom
import { describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { renderToString } from 'react-dom/server'
import { createRoot } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import * as primitives from '@deepseek-ai/dsh-client-ui-primitives'
import { TerminalDepsBanner } from '../src/client/TerminalView.tsx'
// The act() environment flag (React 18.2 reads it before flushing effects).
;(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true
const deps = {
ok: false as const,
cause: 'Cannot find package node-pty',
command: 'bash "/Users/u/.dsh/profiles/web/node_modules/.pnpm/dsh-better-sidebar@0.0.0/node_modules/dsh-better-sidebar/scripts/install.sh" --repair --profile "web"',
profile: 'web',
}
describe('TerminalDepsBanner (render)', () => {
it('renders the failure title, the pasteable command and the actions', () => {
const html = renderToString(createElement(TerminalDepsBanner, { deps, onRetry: () => {} }))
// The jsdom locale is en-US, so the en dictionary applies.
expect(html).toContain('Terminal dependency node-pty failed to load')
// renderToString HTML-escapes the quotes inside the command block.
expect(html).toContain(deps.command.replaceAll('"', '&quot;'))
expect(html).toContain('Copy')
expect(html).toContain('Retry')
// The profile the command targets is shown next to the hint.
expect(html).toContain('detected profile: web')
})
})
describe('TerminalDepsBanner copy click (interactive)', () => {
it('clicking Copy writes the repair command and flashes "Copied"', async () => {
vi.spyOn(primitives, 'writeClipboard').mockResolvedValue(true)
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const onRetry = vi.fn()
act(() => {
root.render(createElement(TerminalDepsBanner, { deps, onRetry }))
})
const copyButton = container.querySelector('button[aria-label="Copy"]') as HTMLButtonElement
expect(copyButton).not.toBeNull()
expect(copyButton.textContent).toBe('Copy')
await act(async () => { copyButton.click() })
expect(primitives.writeClipboard).toHaveBeenCalledWith(deps.command)
expect(copyButton.textContent).toBe('Copied')
act(() => { root.unmount() })
container.remove()
vi.restoreAllMocks()
})
it('clicking Retry fires the callback (the view reconnects)', async () => {
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const onRetry = vi.fn()
act(() => {
root.render(createElement(TerminalDepsBanner, { deps, onRetry }))
})
const buttons = [...container.querySelectorAll('button')] as HTMLButtonElement[]
const retry = buttons.find(button => button.textContent === 'Retry')
expect(retry).toBeDefined()
await act(async () => { retry!.click() })
expect(onRetry).toHaveBeenCalledTimes(1)
act(() => { root.unmount() })
container.remove()
})
})