Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/content/1.guide/23.hub-ui-onboard.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const onboarding = createOnboarding({
- `scriptSrc`: `<base>embedded.js`, the URL to inject as `<script type="module">`.
- `disabled` and `installed`: what the host needs to decide whether to inject the script at all (below).

`packages` are package specs as the package manager accepts them. The package manager comes from the lockfile (`npm`, `pnpm`, `yarn`, `bun`, `deno`), `dev: true` adds `-D`, and `cwd` (default `process.cwd()`) is the project that receives the dependency. In a workspace, point `cwd` at the package that runs the dev server. The packages are fixed at creation.
`packages` are package specs as the package manager accepts them. The package manager comes from the lockfile (`npm`, `pnpm`, `yarn`, `bun`, `deno`), `dev: true` adds `-D`, and `cwd` (default `process.cwd()`) is the project that receives the dependency. In a workspace, point `cwd` at the package that runs the dev server. The packages are fixed at creation. An install that runs longer than `installTimeout` (default 5 minutes) is stopped, and the panel asks the user to run the command in a terminal ([DF9009](/errors/DF9009)).

## Confirm the install

Expand Down Expand Up @@ -225,4 +225,4 @@ Frameworks with a `Request => Response` surface (Hono, Nitro, Deno) mount `onboa

## Errors

The Node side reports through `DF9000` to `DF9008`. An install failure or a throwing `onInstalled` also reaches the panel as `{ state: 'error', error: { code, message } }`, with a Retry button. See the [error reference](/errors).
The Node side reports through `DF9000` to `DF9009`. An install failure or a throwing `onInstalled` also reaches the panel as `{ state: 'error', error: { code, message } }`, with a Retry button. See the [error reference](/errors).
22 changes: 22 additions & 0 deletions docs/content/6.errors/DF9009.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
title: 'DF9009: Install Command Timed Out'
description: 'The package manager did not finish in time, so the install was stopped.'
---

## Message

> `{command}` did not finish within `{seconds}` seconds, so it was stopped.

## Cause

The Install button ran the project's package manager, and the package manager did not exit before the time limit. The limit is the `installTimeout` option of `createOnboarding()`. The default is 5 minutes. The onboarding then stopped the process, so the panel does not wait forever.

Usually the package manager hangs. For example, some pnpm 10 versions hang while they resolve some prerelease versions. A slow network or a very large install can also take longer than the limit.

## Fix

Run the command shown in the panel in a terminal to see where the package manager stops. Fix the cause, for example update the package manager, then click Retry. If the install is only slow, pass a larger `installTimeout` to `createOnboarding()`.

## Source

- [`packages/hub-ui-onboard/src/install.ts`](https://github.com/devframes/devframe/blob/main/packages/hub-ui-onboard/src/install.ts): `runInstall` stops the process and throws this when the time limit ends. The status route reports it as `{ state: 'error', error: { code, message } }`.
4 changes: 4 additions & 0 deletions packages/hub-ui-onboard/src/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,9 @@ export const diagnostics = defineDiagnostics({
why: (p: { command: string, minutes: number }) => `Nobody allowed \`${p.command}\` within ${p.minutes} minutes. The install was refused.`,
fix: 'Click Install again and answer in the terminal that runs the dev server. If the answer does not arrive, another program reads that terminal: pass an `onConfirm` function to `createOnboarding()`.',
},
DF9009: {
why: (p: { command: string, seconds: number }) => `\`${p.command}\` did not finish within ${p.seconds} seconds, so it was stopped.`,
fix: 'Run the command in a terminal to see where the package manager stops, then click Install again. If the install is only slow, raise `installTimeout`.',
},
},
})
8 changes: 7 additions & 1 deletion packages/hub-ui-onboard/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { confirmInTerminal } from './terminal-confirm'
export type * from './types'

const STATE_FILE = 'hub-ui-onboard.json'
const DEFAULT_INSTALL_TIMEOUT = 5 * 60 * 1000

/** `devframes` → `/devframes/`, same rule as `normalizeHubBase` in `@devframes/hub`. */
function normalizeBase(base: string): string {
Expand Down Expand Up @@ -128,7 +129,12 @@ export function createOnboarding(options: CreateOnboardingOptions): Onboarding {
const base = normalizeBase(options.base ?? '/__devframes/')
const cwd = options.cwd ?? process.cwd()
const stateFile = join(options.stateDir ?? join(cwd, 'node_modules/.devframe'), STATE_FILE)
const plan = { cwd, packages: options.packages, dev: options.dev ?? true }
const plan = {
cwd,
packages: options.packages,
dev: options.dev ?? true,
timeout: options.installTimeout ?? DEFAULT_INSTALL_TIMEOUT,
}
const branding = options.branding ?? {}
const messages = {
...defaultMessages(branding.productName?.trim() || 'Devframes'),
Expand Down
50 changes: 47 additions & 3 deletions packages/hub-ui-onboard/src/install.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ResolvedCommand } from 'package-manager-detector'
import type { Result } from 'tinyexec'
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import process from 'node:process'
Expand All @@ -10,6 +11,8 @@ export interface InstallPlan {
cwd: string
packages: string[]
dev: boolean
/** Stop the install after this many milliseconds. */
timeout: number
}

/** The `add` command for the project's package manager, `npm` when none is detected. */
Expand All @@ -28,19 +31,40 @@ export async function resolveInstallCommand(plan: InstallPlan): Promise<Resolved

/**
* Run the install and make sure that each named package landed in
* `<cwd>/node_modules`. Throws a `DF9001` / `DF9002` diagnostic on failure.
* `<cwd>/node_modules`. Throws a `DF9001` / `DF9002` / `DF9009` diagnostic on failure.
*/
export async function runInstall(plan: InstallPlan, command: ResolvedCommand): Promise<void> {
const result = await exec(command.command, command.args, {
const commandLine = [command.command, ...command.args].join(' ')
const child = exec(command.command, command.args, {
// `CI` keeps every package manager non-interactive: nobody can answer a prompt here.
nodeOptions: {
cwd: plan.cwd,
env: { ...process.env, CI: '1' },
},
})
// A hung package manager never exits. Stop it and fail at once: a child
// process can keep the output pipes open after the kill. The kill can also
// end the install with an exit code first, so the timeout error wins.
let timer: ReturnType<typeof setTimeout> | undefined
let killed: Promise<void> | undefined
const timedOut = new Promise<undefined>((resolve) => {
timer = setTimeout(() => {
killed = killTree(child)
void killed.then(() => resolve(undefined))
}, plan.timeout)
})
const result = await Promise.race([child, timedOut]).finally(() => clearTimeout(timer))
// `result` is `undefined` only when the timeout won the race.
if (killed || !result) {
await killed
throw diagnostics.DF9009({
command: commandLine,
seconds: Math.round(plan.timeout / 1000),
})
}
if (result.exitCode !== 0) {
throw diagnostics.DF9001({
command: [command.command, ...command.args].join(' '),
command: commandLine,
exitCode: result.exitCode,
stderr: result.stderr.trim().slice(-2048),
})
Expand All @@ -51,6 +75,26 @@ export async function runInstall(plan: InstallPlan, command: ResolvedCommand): P
}
}

/**
* Kill the install with everything it started. On Windows, tinyexec runs a
* package manager's `.cmd` shim through `cmd.exe`, and a kill does not reach
* child processes, so `taskkill /T /F` ends the whole tree.
*/
async function killTree(child: Result): Promise<void> {
const pid = child.process?.pid
if (process.platform === 'win32' && pid !== undefined) {
const result = await exec('taskkill', [
'/pid',
String(pid),
'/T',
'/F',
]).then(r => r, () => undefined)
if (result?.exitCode === 0)
return
}
child.kill()
}

/**
* `true` when every named package is already in `<cwd>/node_modules`, so the
* onboarding has nothing to install. Path, URL and alias specs cannot be
Expand Down
6 changes: 6 additions & 0 deletions packages/hub-ui-onboard/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ export interface CreateOnboardingOptions {
stateDir?: string
/** Install as a devDependency. Default: `true`. */
dev?: boolean
/**
* Stop the install when it runs longer than this many milliseconds, and
* show an error that asks the user to run the command in a terminal.
* Default: `300_000` (5 minutes).
*/
installTimeout?: number
branding?: OnboardingBranding
messages?: Partial<OnboardingMessages>
/**
Expand Down
35 changes: 35 additions & 0 deletions packages/hub-ui-onboard/test/install.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import process from 'node:process'
import { afterEach, describe, expect, it } from 'vitest'
import { runInstall } from '../src/install'

const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0))
rmSync(dir, { recursive: true, force: true, maxRetries: 10 })
})

describe('runInstall', () => {
it('stops a package manager that hangs', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'onboard-install-'))
dirs.push(cwd)
// Stands in for a hung package manager; a grandchild keeps the pipes open for 3 s.
const script = 'require("child_process").spawn(process.execPath, ["-e", "setTimeout(() => {}, 3000)"], { stdio: "inherit" }); setInterval(() => {}, 1000)'
const started = Date.now()
await expect(runInstall(
{
cwd,
packages: ['foo'],
dev: true,
timeout: 300,
},
{
command: process.execPath,
args: ['-e', script],
},
)).rejects.toMatchObject({ code: 'DF9009' })
expect(Date.now() - started).toBeLessThan(5000)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface CreateOnboardingOptions {
cwd?: string;
stateDir?: string;
dev?: boolean;
installTimeout?: number;
branding?: OnboardingBranding;
messages?: Partial<OnboardingMessages>;
onInstalled?: () => void | OnboardingHandler | Promise<void | OnboardingHandler>;
Expand Down
Loading