Skip to content
Merged
15 changes: 15 additions & 0 deletions packages/cli/src/ui/voice/native-audio-recorder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,21 @@ describe('createNativeAudioRecorder', () => {
expect(backend.startRecording).toHaveBeenCalledTimes(1);
});

it('explains mirror registry installs when the native package is missing', async () => {
const recorder = createNativeAudioRecorder({
loadBackend: () => {
throw new Error(
"Cannot find package '@qwen-code/audio-capture' imported from /qwen/dist/cli.js",
);
},
});

await expect(recorder.start()).rejects.toThrow(
/mirror or private registry/,
);
await expect(recorder.start()).rejects.toThrow(/@qwen-code\/audio-capture/);
});

it('allows retry after native stop throws', async () => {
const backend = {
startRecording: vi.fn(),
Expand Down
28 changes: 27 additions & 1 deletion packages/cli/src/ui/voice/native-audio-recorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
// Native silence detection sets a flag we poll for; older addons lack it.
const SILENCE_POLL_INTERVAL_MS = 200;
const debugLogger = createDebugLogger('VOICE_NATIVE_RECORDER');
const AUDIO_CAPTURE_PACKAGE = '@qwen-code/audio-capture';

interface NativeAudioRecorderOptions {
loadBackend?: () =>
Expand Down Expand Up @@ -101,7 +102,7 @@ class NativeAudioRecorder implements VoiceRecorder {
}
} catch (error) {
this.starting = false;
throw error;
throw explainMissingNativePackage(error);
}
}

Expand Down Expand Up @@ -130,6 +131,31 @@ async function loadDefaultBackend(): Promise<NativeAudioCaptureBackend> {
return createNativeAudioCaptureBackend();
}

function explainMissingNativePackage(error: unknown): unknown {
if (!(error instanceof Error) || !isMissingNativePackageError(error)) {
return error;
}

return new Error(
`Native voice capture package '${AUDIO_CAPTURE_PACKAGE}' is missing. ` +
'If Qwen Code was installed from a mirror or private registry, the ' +
'registry may not have synced this optional package. Reinstall from ' +
'https://registry.npmjs.org or make sure the configured registry ' +
`provides ${AUDIO_CAPTURE_PACKAGE}. (${error.message})`,
{ cause: error },
);
}

function isMissingNativePackageError(error: Error): boolean {
return (
error.message.includes(AUDIO_CAPTURE_PACKAGE) &&

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] False-positive error rewrite. packages/audio-capture/src/index.ts:62-70 (loadBinding()) wraps any inner failure from node-gyp-build or prebuild loading with 'Native audio capture addon could not be loaded. Reinstall @qwen-code/audio-capture, ... (' + error.message + ')'. When the inner error is itself a Cannot find module 'node-gyp-build' (e.g. the bundled dep was not copied, or its files are corrupted), the resulting message contains both @qwen-code/audio-capture and Cannot find module, so this substring check passes and the error is rewritten to "package is missing, reinstall from npmjs.org".

That confidently points the operator at the registry mirror when the package is installed and the real root cause is an incomplete bundled node_modules/ tree (precisely the failure mode the bundling added in this PR is supposed to prevent). The original Cannot find module 'node-gyp-build' detail ends up buried in parentheses at the end of the rewritten message.

Suggested change
error.message.includes(AUDIO_CAPTURE_PACKAGE) &&
function isMissingNativePackageError(error: Error): boolean {
const code = (error as NodeJS.ErrnoException).code;
if (code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND') {
return error.message.includes(AUDIO_CAPTURE_PACKAGE);
}
return (
error.message.includes(AUDIO_CAPTURE_PACKAGE) &&
(error.message.startsWith('Cannot find package') ||
error.message.startsWith('Cannot find module'))
);
}

The startsWith guard rejects loadBinding()'s wrapped message (which starts with Native audio capture addon could not be loaded) while still matching the ESM/CJS loader's genuine resolution failures (which start with Cannot find package '@qwen-code/audio-capture' ...).

— qwen3.7-max via Qwen Code /review

(error.message.includes('Cannot find package') ||
error.message.includes('Cannot find module') ||
(error as NodeJS.ErrnoException).code === 'ERR_MODULE_NOT_FOUND' ||
(error as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND')
);
}

export function createNativeAudioRecorder(
options: NativeAudioRecorderOptions = {},
): VoiceRecorder {
Expand Down
83 changes: 81 additions & 2 deletions scripts/prepare-package.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@
*/

import fs from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const defaultRootDir = path.resolve(__dirname, '..');
const nodeRequire = createRequire(import.meta.url);

export function preparePackage({ rootDir = defaultRootDir } = {}) {
const distDir = path.join(rootDir, 'dist');
Expand All @@ -25,7 +27,11 @@ export function preparePackage({ rootDir = defaultRootDir } = {}) {
copyDocumentationFiles(rootDir, distDir);
copyLocales(rootDir, distDir);
copyExtensionExamples(rootDir, distDir);
writeDistPackageJson(rootDir, distDir);
const bundleNativeAudioCapture = copyNativeAudioCapturePackage(
rootDir,
distDir,
);
writeDistPackageJson(rootDir, distDir, { bundleNativeAudioCapture });
printPackageStructure(distDir);
}

Expand Down Expand Up @@ -129,7 +135,77 @@ function copyExtensionExamples(rootDir, distDir) {
}
}

function writeDistPackageJson(rootDir, distDir) {
function copyNativeAudioCapturePackage(rootDir, distDir) {
console.log('Copying native audio capture package...');

const addonSrc = path.join(rootDir, 'packages', 'audio-capture');
const addonDest = path.join(
distDir,
'node_modules',
'@qwen-code',
'audio-capture',
);
const requiredPaths = [
path.join(addonSrc, 'dist'),
path.join(addonSrc, 'prebuilds'),
path.join(addonSrc, 'package.json'),
];

for (const requiredPath of requiredPaths) {
if (!fs.existsSync(requiredPath)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] copyNativeAudioCapturePackage validates that dist/, prebuilds/, and package.json exist as paths, but not that they have usable contents. An empty dist/ (e.g. a stale tsconfig.tsbuildinfo no-opping the addon's tsc build, or a wrong outDir) or an empty prebuilds/ directory passes all three existsSync checks, so bundledDependencies: ['@qwen-code/audio-capture'] is written and a broken addon ships — even under the required (main-repo release) gate. The sibling standalone packaging path already guards against exactly this with hasNativePrebuild() (scripts/create-standalone-package.js:363), which requires an actual .node file. Worse, at runtime an empty dist/ produces an ERR_MODULE_NOT_FOUND whose message contains both @qwen-code/audio-capture and the not-found code, so isMissingNativePackageError matches and the user is told to "reinstall from a mirror/registry" — advice that can't fix a present-but-empty package. Consider validating contents (e.g. the resolved main/entry under dist/ exists, and prebuilds/ contains at least one .node, reusing hasNativePrebuild).

— claude-opus-4-8[1m] via Qwen Code /qreview

console.warn(
`Warning: audio capture package artifact not found at ${requiredPath}`,
);
return false;
}
}

fs.rmSync(addonDest, { recursive: true, force: true });
fs.mkdirSync(addonDest, { recursive: true });

const addonPkg = JSON.parse(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] JSON.parse(fs.readFileSync(..., 'package.json')) has no try/catch. Every other early-return path in copyNativeAudioCapturePackage honors the required contract — warn + return false when not required, throw when required — but a malformed packages/audio-capture/package.json (invalid JSON, truncated file, merge-conflict markers) bypasses all of that and throws a raw SyntaxError unconditionally, crashing npm run prepare:package for every caller regardless of required.

Suggested change
const addonPkg = JSON.parse(
let addonPkg;
try {
addonPkg = JSON.parse(
fs.readFileSync(path.join(addonSrc, 'package.json'), 'utf8'),
);
} catch {
const message = `audio capture package.json is not valid JSON at ${addonSrc}`;
if (required) {
throw new Error(
`Required ${message}. ` +
'Cannot publish package without native voice capture.',
);
}
console.warn(`Warning: ${message}`);
return false;
}

Matches the required handling pattern used on lines 161, 183, and 207 for other artifact failures.

— qwen3.7-max via Qwen Code /review

fs.readFileSync(path.join(addonSrc, 'package.json'), 'utf8'),
);
delete addonPkg.scripts;
delete addonPkg.devDependencies;
fs.writeFileSync(
path.join(addonDest, 'package.json'),
JSON.stringify(addonPkg, null, 2) + '\n',
);

const copyOpts = {
recursive: true,
dereference: true,
verbatimSymlinks: false,
};
fs.cpSync(path.join(addonSrc, 'dist'), path.join(addonDest, 'dist'), {
...copyOpts,
filter: (src) => !/\.test\.(d\.)?[mc]?[jt]s(\.map)?$/.test(src),
});
fs.cpSync(
path.join(addonSrc, 'prebuilds'),
path.join(addonDest, 'prebuilds'),
copyOpts,
);

const nodeGypBuildSrc = path.dirname(
nodeRequire.resolve('node-gyp-build/package.json'),
);
fs.cpSync(
nodeGypBuildSrc,
path.join(addonDest, 'node_modules', 'node-gyp-build'),
copyOpts,
);

console.log('Copied native audio capture package');
return true;
}

function writeDistPackageJson(
rootDir,
distDir,
{ bundleNativeAudioCapture = false } = {},
) {
console.log('Creating package.json for distribution...');

const cliEntryContent = `#!/usr/bin/env node
Expand Down Expand Up @@ -190,6 +266,9 @@ if (result.signal) {
'bundled',
'web-shell',
],
...(bundleNativeAudioCapture
? { bundledDependencies: ['@qwen-code/audio-capture'] }
: {}),
config: rootPackageJson.config,
dependencies: {},
optionalDependencies: {
Expand Down
64 changes: 64 additions & 0 deletions scripts/tests/package-assets.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,39 @@ describe('package asset scripts', () => {
);

expect(distPackageJson.files).toContain('examples');
expect(distPackageJson.bundledDependencies).toContain(
'@qwen-code/audio-capture',
);
expect(distPackageJson.optionalDependencies).toMatchObject({
'@qwen-code/audio-capture': rootPackageJson.version,
});
expect(
existsSync(
path.join(
rootDir,
'dist',
'node_modules',
'@qwen-code',
'audio-capture',
'dist',
'index.js',
),
),
).toBe(true);
expect(
existsSync(
path.join(
rootDir,
'dist',
'node_modules',
'@qwen-code',
'audio-capture',
'node_modules',
'node-gyp-build',
'package.json',
),
),
).toBe(true);
expect(
existsSync(
path.join(rootDir, 'dist', 'examples', 'mcp-server', 'package.json'),
Expand Down Expand Up @@ -107,6 +137,40 @@ describe('package asset scripts', () => {
'packages/cli/src/i18n/locales/en.json',
'{"hello":"world"}\n',
);
writeFile(
rootDir,
'packages/audio-capture/package.json',
JSON.stringify(
{
name: '@qwen-code/audio-capture',
version: '0.17.0',
type: 'module',
main: 'dist/index.js',
dependencies: {
'node-gyp-build': '^4.8.4',
},
scripts: {
install: 'node install.js',
},
devDependencies: {
typescript: '^5.3.3',
},
},
null,
2,
),
);
writeFile(rootDir, 'packages/audio-capture/dist/index.js', '');
writeFile(
rootDir,
'packages/audio-capture/dist/index.test.js',
'throw new Error("should not copy tests");\n',
);
writeFile(
rootDir,
'packages/audio-capture/prebuilds/darwin-arm64/@qwen-code+audio-capture.node',
'fake native addon\n',
);

for (const template of [
'agent',
Expand Down
Loading