From 77651f5a7ba9afddc22705181a4df0b6155cf863 Mon Sep 17 00:00:00 2001 From: EmmaYuan1015 Date: Wed, 28 Oct 2026 14:08:23 +0800 Subject: [PATCH 1/8] Use path.join for EAS configuration file path Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/extension/commands/configEASBuild.ts | 3 ++- .../extension/commands/configEASBuild.test.ts | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/extension/commands/configEASBuild.ts b/src/extension/commands/configEASBuild.ts index 6850902cf..cc10c31ac 100644 --- a/src/extension/commands/configEASBuild.ts +++ b/src/extension/commands/configEASBuild.ts @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for details. import assert = require("assert"); +import * as path from "path"; import * as nls from "vscode-nls"; import { OutputChannelLogger } from "../log/OutputChannelLogger"; import { ErrorHelper } from "../../common/error/errorHelper"; @@ -32,7 +33,7 @@ export class ConfigEASBuild extends ReactNativeCommand { if (isExpo) { const fs = new FileSystem(); - const exists = await fs.exists(`${projectRootPath}/eas.json`); + const exists = await fs.exists(path.join(projectRootPath, "eas.json")); if (exists) { logger.info( localize( diff --git a/test/extension/commands/configEASBuild.test.ts b/test/extension/commands/configEASBuild.test.ts index 74bfd58b9..e70598f3b 100644 --- a/test/extension/commands/configEASBuild.test.ts +++ b/test/extension/commands/configEASBuild.test.ts @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for details. import assert = require("assert"); +import * as path from "path"; import Sinon = require("sinon"); import proxyquire = require("proxyquire"); @@ -90,7 +91,10 @@ suite("configEASBuildCommand", function () { await runCommand(ConfigEASBuild, "/workspace/app", isExpoStub); - assert.strictEqual(existsStub.calledWithExactly("/workspace/app/eas.json"), true); + assert.strictEqual( + existsStub.calledWithExactly(path.join("/workspace/app", "eas.json")), + true, + ); assert.strictEqual(executeStub.called, false); assert.strictEqual( logger.info.args.some((args: string[]) => @@ -100,6 +104,19 @@ suite("configEASBuildCommand", function () { ); }); + test("should normalize the eas.json path when the project root has a trailing separator", async function () { + const projectPath = path.join(path.sep, "workspace", "app with spaces") + path.sep; + const existsStub = Sinon.stub().returns(Promise.resolve(true)); + const executeStub = Sinon.stub().returns(Promise.resolve()); + const isExpoStub = Sinon.stub().returns(Promise.resolve(true)); + const { ConfigEASBuild } = createCommandModule(existsStub, executeStub); + + await runCommand(ConfigEASBuild, projectPath, isExpoStub); + + assert.strictEqual(existsStub.calledWithExactly(path.join(projectPath, "eas.json")), true); + assert.strictEqual(executeStub.called, false); + }); + test("should run eas build configure for Expo projects without eas.json", async function () { const existsStub = Sinon.stub().returns(Promise.resolve(false)); const executeStub = Sinon.stub().returns(Promise.resolve()); From 6c79c8e9cdfbefc283a09c44b4e8c59d6dc3f643 Mon Sep 17 00:00:00 2001 From: EmmaYuan1015 Date: Thu, 29 Oct 2026 10:36:22 +0800 Subject: [PATCH 2/8] Refactor launch Expo Web command and improve test coverage Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/extension/commands/launchExpoWeb.ts | 6 +- test/extension/commands/launchExpoWeb.test.ts | 57 ++++++++++++++++++- 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/src/extension/commands/launchExpoWeb.ts b/src/extension/commands/launchExpoWeb.ts index 4e78737ef..dcbf48ef1 100644 --- a/src/extension/commands/launchExpoWeb.ts +++ b/src/extension/commands/launchExpoWeb.ts @@ -20,7 +20,7 @@ export class launchExpoWeb extends Command { label = "Launch ExpoWeb"; error = ErrorHelper.getInternalError(InternalErrorCode.FailedToLaunchExpoWeb); - async baseFn(launchArgs: any): Promise { + async baseFn(): Promise { assert(this.project); const expoHelper = this.project.getExponentHelper(); logger.info(localize("CheckExpoEnvironment", "Checking Expo project environment.")); @@ -33,12 +33,10 @@ export class launchExpoWeb extends Command { } } -async function runExpoWeb(project: AppLauncher) { +async function runExpoWeb(project: AppLauncher): Promise { const platform = new ExponentPlatform(getRunOptions(project, PlatformType.ExpoWeb), { packager: project.getPackager(), }); - platform; - await platform.beforeStartPackager(); await platform.startPackager(); } diff --git a/test/extension/commands/launchExpoWeb.test.ts b/test/extension/commands/launchExpoWeb.test.ts index 0af6d0eb0..bd3b16293 100644 --- a/test/extension/commands/launchExpoWeb.test.ts +++ b/test/extension/commands/launchExpoWeb.test.ts @@ -83,7 +83,7 @@ suite("launchExpoWebCommand", function () { const command = launchExpoWeb.formInstance(); (command as any).project = project; - await command.baseFn({}); + await command.baseFn(); assert.strictEqual(isExpoManagedAppStub.calledWithExactly(true), true); assert.strictEqual(getRunOptionsStub.called, false); @@ -107,7 +107,7 @@ suite("launchExpoWebCommand", function () { const command = launchExpoWeb.formInstance(); (command as any).project = project; - await command.baseFn({}); + await command.baseFn(); assert.strictEqual(isExpoManagedAppStub.calledWithExactly(true), true); assert.strictEqual( @@ -120,4 +120,57 @@ suite("launchExpoWebCommand", function () { assert.strictEqual(startPackagerStub.calledOnce, true); assert.strictEqual(beforeStartPackagerStub.calledBefore(startPackagerStub), true); }); + + test("should wait for environment preparation before starting the packager", async function () { + const { launchExpoWeb, project, beforeStartPackagerStub, startPackagerStub } = + createCommandModule(true); + const command = launchExpoWeb.formInstance(); + (command as any).project = project; + let completePreparation: (() => void) | undefined; + beforeStartPackagerStub.returns( + new Promise(resolve => { + completePreparation = resolve; + }), + ); + + const execution = command.baseFn(); + await Promise.resolve(); + + assert.strictEqual(beforeStartPackagerStub.calledOnce, true); + assert.strictEqual(startPackagerStub.called, false); + assert(completePreparation); + completePreparation(); + await execution; + + assert.strictEqual(startPackagerStub.calledOnce, true); + }); + + for (const stage of ["environment check", "environment preparation", "packager startup"]) { + test(`should propagate a failure during ${stage}`, async function () { + const { + launchExpoWeb, + project, + isExpoManagedAppStub, + platformConstructorStub, + beforeStartPackagerStub, + startPackagerStub, + } = createCommandModule(true); + const command = launchExpoWeb.formInstance(); + (command as any).project = project; + const failure = new Error(`Failed during ${stage}`); + let failingStub = startPackagerStub; + if (stage === "environment check") { + failingStub = isExpoManagedAppStub; + } else if (stage === "environment preparation") { + failingStub = beforeStartPackagerStub; + } + failingStub.returns(Promise.reject(failure)); + + await assert.rejects(command.baseFn(), (error: unknown) => error === failure); + + assert.strictEqual(platformConstructorStub.called, stage !== "environment check"); + assert.strictEqual(beforeStartPackagerStub.called, stage !== "environment check"); + assert.strictEqual(startPackagerStub.called, stage === "packager startup"); + }); + } }); From b3273dbc92c13ae932bb528e2928f9c07c0cd573 Mon Sep 17 00:00:00 2001 From: EmmaYuan1015 Date: Thu, 29 Oct 2026 11:04:40 +0800 Subject: [PATCH 3/8] Fix EAS CLI resolution for Expo build configuration Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 2 +- src/extension/commands/configEASBuild.ts | 10 +++++----- .../extension/commands/configEASBuild.test.ts | 20 +++++++++---------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 84098e7aa..6b64db98b 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ The full list of commands is: ### Command behavior highlights -- `Expo - Create EAS config file` runs `eas build:configure --platform all` for Expo managed projects. If `eas.json` already exists, the command exits without changing existing config. +- `Expo - Create EAS config file` runs `npx eas-cli build:configure --platform all` from the Expo managed project root, without requiring a global EAS CLI installation. It requires `npx` on your PATH and may download `eas-cli` if it is not installed locally. If `eas.json` already exists, the command exits without changing existing config. - `Publish to Expo Host` (`reactNative.publishToExpHost`) was deprecated and removed. Use Expo EAS workflows (`eas build`, `eas submit`) instead. - `Run EAS Build` initializes local EAS build files by creating `eas.json` and `.eas/workflows/create-production-builds.yml` when they are missing. - `Enable Hermes` lets you choose platform and enable/disable Hermes: diff --git a/src/extension/commands/configEASBuild.ts b/src/extension/commands/configEASBuild.ts index 6850902cf..4b5cf4599 100644 --- a/src/extension/commands/configEASBuild.ts +++ b/src/extension/commands/configEASBuild.ts @@ -6,7 +6,7 @@ import * as nls from "vscode-nls"; import { OutputChannelLogger } from "../log/OutputChannelLogger"; import { ErrorHelper } from "../../common/error/errorHelper"; import { InternalErrorCode } from "../../common/error/internalErrorCode"; -import { CommandExecutor } from "../../common/commandExecutor"; +import { ChildProcess } from "../../common/node/childProcess"; import { FileSystem } from "../../common/node/fileSystem"; import { ReactNativeCommand } from "./util/reactNativeCommand"; @@ -18,7 +18,6 @@ const localize = nls.loadMessageBundle(); const logger = OutputChannelLogger.getMainChannel(); export class ConfigEASBuild extends ReactNativeCommand { - nodeModulesRoot!: string; codeName = "createExpoEASBuildConfigFile"; label = "Config Expo app with EAS build"; error = ErrorHelper.getInternalError(InternalErrorCode.FailedToConfigEASBuild); @@ -46,8 +45,9 @@ export class ConfigEASBuild extends ReactNativeCommand { ); try { - await new CommandExecutor(this.nodeModulesRoot, projectRootPath).execute( - "eas build:configure --platform all", + await new ChildProcess().execToString( + "npx eas-cli build:configure --platform all", + { cwd: projectRootPath }, ); logger.info( @@ -60,7 +60,7 @@ export class ConfigEASBuild extends ReactNativeCommand { logger.error( localize( "NoExistingEASProject", - "Unable to find existing EAS project. Please run 'eas init' firstly to bind your app to EAS project.", + "Unable to find existing EAS project. Please run 'npx eas-cli init' firstly to bind your app to EAS project.", ), ); throw error; diff --git a/test/extension/commands/configEASBuild.test.ts b/test/extension/commands/configEASBuild.test.ts index 74bfd58b9..8b36cdf51 100644 --- a/test/extension/commands/configEASBuild.test.ts +++ b/test/extension/commands/configEASBuild.test.ts @@ -31,16 +31,16 @@ suite("configEASBuildCommand", function () { public exists = existsStub; } - class FakeCommandExecutor { - public execute = executeStub; + class FakeChildProcess { + public execToString = executeStub; } const module = proxyquire.noCallThru()("../../../src/extension/commands/configEASBuild", { "../../common/node/fileSystem": { FileSystem: FakeFileSystem, }, - "../../common/commandExecutor": { - CommandExecutor: FakeCommandExecutor, + "../../common/node/childProcess": { + ChildProcess: FakeChildProcess, }, "../log/OutputChannelLogger": { OutputChannelLogger: { @@ -62,7 +62,6 @@ suite("configEASBuildCommand", function () { ): Promise { const command = commandClass.formInstance(); (command as any).project = createMockProject(projectPath, isExpoStub); - (command as any).nodeModulesRoot = `${projectPath}/node_modules`; await command.baseFn(); } @@ -100,7 +99,7 @@ suite("configEASBuildCommand", function () { ); }); - test("should run eas build configure for Expo projects without eas.json", async function () { + test("should run EAS CLI through npx from the project root without eas.json", async function () { const existsStub = Sinon.stub().returns(Promise.resolve(false)); const executeStub = Sinon.stub().returns(Promise.resolve()); const isExpoStub = Sinon.stub().returns(Promise.resolve(true)); @@ -109,7 +108,10 @@ suite("configEASBuildCommand", function () { await runCommand(ConfigEASBuild, "/workspace/app", isExpoStub); assert.strictEqual( - executeStub.calledWithExactly("eas build:configure --platform all"), + executeStub.calledOnce && + executeStub.calledWithExactly("npx eas-cli build:configure --platform all", { + cwd: "/workspace/app", + }), true, ); assert.strictEqual( @@ -133,9 +135,7 @@ suite("configEASBuildCommand", function () { ); assert.strictEqual( - logger.error.args.some((args: string[]) => - args[0].includes("Unable to find existing EAS project"), - ), + logger.error.args.some((args: string[]) => args[0].includes("npx eas-cli init")), true, ); }); From afa41d36be68831872460868e102a5b85ad943e4 Mon Sep 17 00:00:00 2001 From: EmmaYuan1015 Date: Wed, 4 Nov 2026 10:00:29 +0800 Subject: [PATCH 4/8] Log warnings when development environment detection fails Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/extension/commands/testDevEnvironment.ts | 16 ++++++++++++-- .../commands/testDevEnvironment.test.ts | 22 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/extension/commands/testDevEnvironment.ts b/src/extension/commands/testDevEnvironment.ts index a4eae2a31..8c41282c5 100644 --- a/src/extension/commands/testDevEnvironment.ts +++ b/src/extension/commands/testDevEnvironment.ts @@ -10,6 +10,7 @@ import { RNPackageVersionsToPackageVersion, } from "../../common/projectVersionHelper"; import { AppLauncher } from "../appLauncher"; +import { OutputChannelLogger } from "../log/OutputChannelLogger"; import { RNProjectObserver } from "../rnProjectObserver"; import { runChecks } from "../services/validationService/checker"; import { ValidationCategoryE } from "../services/validationService/checks/types"; @@ -49,7 +50,13 @@ export class TestDevEnvironment extends Command { } const projectObserver = - project && (await this.createRNProjectObserver(project).catch(() => undefined)); + project && + (await this.createRNProjectObserver(project).catch(error => { + OutputChannelLogger.getMainChannel().warning( + `Project detection failed; skipping Windows and macOS checks and package version detection: ${error}`, + ); + return undefined; + })); const shouldCheck = { [ValidationCategoryE.Expo]: @@ -57,7 +64,12 @@ export class TestDevEnvironment extends Command { ?.getPackager() .getExponentHelper() .isExpoManagedApp(false) - .catch(() => false)) || false, + .catch(error => { + OutputChannelLogger.getMainChannel().warning( + `Expo detection failed; skipping Expo checks: ${error}`, + ); + return false; + })) || false, [ValidationCategoryE.Windows]: (projectObserver && projectObserver.isRNWindowsProject) || false, diff --git a/test/extension/commands/testDevEnvironment.test.ts b/test/extension/commands/testDevEnvironment.test.ts index 0187edb5c..4764937fd 100644 --- a/test/extension/commands/testDevEnvironment.test.ts +++ b/test/extension/commands/testDevEnvironment.test.ts @@ -59,6 +59,7 @@ suite("testDevEnvironmentCommand", function () { const commandError = new Error("Failed to test development environment"); const selectProjectStub = Sinon.stub(); const runChecksStub = Sinon.stub().returns(Promise.resolve()); + const warningStub = Sinon.stub(); const getInternalErrorStub = Sinon.stub().returns(commandError); const getReactNativeProjectRootStub = Sinon.stub().returns(projectRoot); const getVersionsStub = Sinon.stub().returns( @@ -118,6 +119,11 @@ suite("testDevEnvironmentCommand", function () { "../rnProjectObserver": { RNProjectObserver: FakeRNProjectObserver, }, + "../log/OutputChannelLogger": { + OutputChannelLogger: { + getMainChannel: () => ({ warning: warningStub }), + }, + }, "../services/validationService/checker": { runChecks: runChecksStub, }, @@ -140,6 +146,7 @@ suite("testDevEnvironmentCommand", function () { commandError, selectProjectStub, runChecksStub, + warningStub, getInternalErrorStub, getReactNativeProjectRootStub, getVersionsStub, @@ -253,6 +260,11 @@ suite("testDevEnvironmentCommand", function () { [validationCategories.Windows]: true, [validationCategories.macOS]: false, }); + Sinon.assert.calledOnce(stubs.warningStub); + Sinon.assert.calledWithExactly( + stubs.warningStub, + "Expo detection failed; skipping Expo checks: Error: Expo detection failed", + ); }); test("should run checks without package versions when version detection fails", async function () { @@ -272,6 +284,11 @@ suite("testDevEnvironmentCommand", function () { }, ]); assert.strictEqual(stubs.convertVersionsStub.called, false); + Sinon.assert.calledOnce(stubs.warningStub); + Sinon.assert.calledWithExactly( + stubs.warningStub, + "Project detection failed; skipping Windows and macOS checks and package version detection: Error: Version detection failed", + ); }); test("should run checks without package versions when observer creation fails", async function () { @@ -291,6 +308,11 @@ suite("testDevEnvironmentCommand", function () { }, ]); assert.strictEqual(stubs.convertVersionsStub.called, false); + Sinon.assert.calledOnce(stubs.warningStub); + Sinon.assert.calledWithExactly( + stubs.warningStub, + "Project detection failed; skipping Windows and macOS checks and package version detection: Error: Observer creation failed", + ); }); test("should propagate validation execution errors", async function () { From cc0d3a685e98c978d8924efa6c4eb3da7080c43c Mon Sep 17 00:00:00 2001 From: ZhiyanJia Date: Wed, 4 Nov 2026 10:55:11 +0800 Subject: [PATCH 5/8] Fix React Native Doctor interaction using a terminal task --- src/extension/commands/rnDoctor.ts | 69 +++-- test/extension/commands/rnDoctor.test.ts | 309 ++++++++++++----------- 2 files changed, 213 insertions(+), 165 deletions(-) diff --git a/src/extension/commands/rnDoctor.ts b/src/extension/commands/rnDoctor.ts index 91831b2ae..85259bfe8 100644 --- a/src/extension/commands/rnDoctor.ts +++ b/src/extension/commands/rnDoctor.ts @@ -2,40 +2,71 @@ // Licensed under the MIT license. See LICENSE file in the project root for details. import assert = require("assert"); +import { randomBytes } from "crypto"; +import * as vscode from "vscode"; import { ErrorHelper } from "../../common/error/errorHelper"; import { InternalErrorCode } from "../../common/error/internalErrorCode"; import { CommandExecutor } from "../../common/commandExecutor"; -import { OutputChannelLogger } from "../log/OutputChannelLogger"; -import { OutputVerifier, PatternToFailure } from "../../common/outputVerifier"; +import { HostPlatform } from "../../common/hostPlatform"; import { AppLauncher } from "../appLauncher"; import { ReactNativeCommand } from "./util/reactNativeCommand"; export class rnDoctor extends ReactNativeCommand { - private static RUN_DOCTOR_SUCCESS_PATTERNS: string[] = ["run doctor succeeded"]; - private static RUN_DOCTOR_FAILURE_PATTERNS: PatternToFailure[] = [ - { - pattern: "Failed to run doctor", - errorCode: InternalErrorCode.FailedToRunRNDoctor, - }, - ]; codeName = "doctor"; label = "React Native Doctor"; - nodeModulesRoot!: string; error = ErrorHelper.getInternalError(InternalErrorCode.FailedToRunRNDoctor); async baseFn(): Promise { assert(this.project); const projectRootPath = this.project.getPackager().getProjectPath(); - const logger = OutputChannelLogger.getChannel("ReactNativeRunDoctor", true); const nodeModulesRoot: string = AppLauncher.getNodeModulesRootByProjectPath(projectRootPath); - const commandExecutor = new CommandExecutor(nodeModulesRoot, projectRootPath, logger); - const res = commandExecutor.spawnReactCommand("doctor"); + const commandExecutor = new CommandExecutor(nodeModulesRoot, projectRootPath); + const cli = HostPlatform.getNpmCliCommand(commandExecutor.selectReactNativeCLI()); + const taskId = randomBytes(16).toString("hex"); + const task = new vscode.Task( + { type: "react-native", command: this.codeName, taskId }, + this.project.getWorkspaceFolder(), + this.label, + "React Native", + new vscode.ShellExecution(cli, ["doctor"], { cwd: projectRootPath }), + [], + ); + task.presentationOptions = { + reveal: vscode.TaskRevealKind.Always, + focus: true, + panel: vscode.TaskPanelKind.Dedicated, + }; - const output = new OutputVerifier( - () => Promise.resolve(rnDoctor.RUN_DOCTOR_SUCCESS_PATTERNS), - () => Promise.resolve(rnDoctor.RUN_DOCTOR_FAILURE_PATTERNS), - "run doctor", - ).process(res); - await output; + const subscriptions: vscode.Disposable[] = []; + try { + await new Promise((resolve, reject) => { + subscriptions.push( + vscode.tasks.onDidEndTaskProcess(event => { + if (event.execution.task.definition.taskId !== taskId) { + return; + } + if (event.exitCode === 0) { + resolve(); + } else { + reject( + ErrorHelper.getInternalError( + InternalErrorCode.CommandFailed, + `${cli} doctor`, + event.exitCode, + ), + ); + } + }), + vscode.tasks.onDidEndTask(event => { + if (event.execution.task.definition.taskId === taskId) { + reject(this.error); + } + }), + ); + void vscode.tasks.executeTask(task).then(undefined, reject); + }); + } finally { + subscriptions.forEach(subscription => subscription.dispose()); + } } } diff --git a/test/extension/commands/rnDoctor.test.ts b/test/extension/commands/rnDoctor.test.ts index 9776fac79..9c7caddb0 100644 --- a/test/extension/commands/rnDoctor.test.ts +++ b/test/extension/commands/rnDoctor.test.ts @@ -2,187 +2,204 @@ // Licensed under the MIT license. See LICENSE file in the project root for details. import assert = require("assert"); +import * as path from "path"; +import * as vscode from "vscode"; import Sinon = require("sinon"); import proxyquire = require("proxyquire"); suite("rnDoctorCommand", function () { - const projectRootPath = "test-project"; - const nodeModulesRoot = "test-node-modules"; - const failedToRunDoctorErrorCode = 126; - - function createCommandModule() { - const commandError = new Error("React Native doctor failed"); - const logger = { - info: Sinon.stub(), - error: Sinon.stub(), - warning: Sinon.stub(), - debug: Sinon.stub(), - }; - const spawnResult = { process: {} }; - const spawnReactCommandStub = Sinon.stub().returns(spawnResult); - const commandExecutorConstructorStub = Sinon.stub(); - const outputVerifierConstructorStub = Sinon.stub(); - const processStub = Sinon.stub().returns(Promise.resolve()); - const getChannelStub = Sinon.stub().returns(logger); - const getNodeModulesRootStub = Sinon.stub().returns(nodeModulesRoot); - const getInternalErrorStub = Sinon.stub().returns(commandError); - - class FakeReactNativeCommand { - public project: any; - + function createCommandModule(suffix = ".cmd") { + const projectRoot = path.resolve("test project"); + const nodeModulesRoot = path.resolve("shared dependencies"); + const cli = path.resolve("custom cli folder", "react-native"); + const workspaceFolder = { name: "test workspace" }; + const commandError = new Error("Doctor failed"); + const getInternalError = Sinon.stub().returns(commandError); + const getNodeModulesRoot = Sinon.stub().returns(nodeModulesRoot); + const executorConstructor = Sinon.stub(); + const selectCLI = Sinon.stub().returns(cli); + const getNpmCliCommand = Sinon.stub().returns(`${cli}${suffix}`); + const shellConstructor = Sinon.stub(); + const taskConstructor = Sinon.stub(); + const executeTask = Sinon.stub().returns(Promise.resolve()); + const processDispose = Sinon.stub(); + const taskDispose = Sinon.stub(); + let processHandler: (event: vscode.TaskProcessEndEvent) => void; + let taskHandler: (event: vscode.TaskEndEvent) => void; + + class FakeCommand { static formInstance(): any { return new this(); } } - - class FakeCommandExecutor { - constructor(...args: any[]) { - commandExecutorConstructorStub(...args); + class FakeExecutor { + constructor(...args: unknown[]) { + executorConstructor(...args); } - - public spawnReactCommand = spawnReactCommandStub; + selectReactNativeCLI = selectCLI; } - - class FakeOutputVerifier { - constructor(...args: any[]) { - outputVerifierConstructorStub(...args); + class FakeTask { + constructor(public definition: vscode.TaskDefinition, ...args: unknown[]) { + taskConstructor(definition, ...args); + } + } + class FakeShellExecution { + constructor(...args: unknown[]) { + shellConstructor(...args); } - - public process = processStub; } const module = proxyquire.noCallThru()("../../../src/extension/commands/rnDoctor", { - "../../common/commandExecutor": { - CommandExecutor: FakeCommandExecutor, - }, - "../../common/error/errorHelper": { - ErrorHelper: { - getInternalError: getInternalErrorStub, + vscode: { + Task: FakeTask, + ShellExecution: FakeShellExecution, + TaskRevealKind: { Always: 1 }, + TaskPanelKind: { Dedicated: 2 }, + tasks: { + executeTask, + onDidEndTaskProcess: (handler: typeof processHandler) => { + processHandler = handler; + return { dispose: processDispose }; + }, + onDidEndTask: (handler: typeof taskHandler) => { + taskHandler = handler; + return { dispose: taskDispose }; + }, }, }, + "../../common/commandExecutor": { CommandExecutor: FakeExecutor }, + "../../common/hostPlatform": { HostPlatform: { getNpmCliCommand } }, + "../../common/error/errorHelper": { ErrorHelper: { getInternalError } }, "../../common/error/internalErrorCode": { - InternalErrorCode: { - FailedToRunRNDoctor: failedToRunDoctorErrorCode, - }, - }, - "../../common/outputVerifier": { - OutputVerifier: FakeOutputVerifier, + InternalErrorCode: { FailedToRunRNDoctor: 126, CommandFailed: 101 }, }, "../appLauncher": { - AppLauncher: { - getNodeModulesRootByProjectPath: getNodeModulesRootStub, - }, - }, - "../log/OutputChannelLogger": { - OutputChannelLogger: { - getChannel: getChannelStub, - }, - }, - "./util/reactNativeCommand": { - ReactNativeCommand: FakeReactNativeCommand, + AppLauncher: { getNodeModulesRootByProjectPath: getNodeModulesRoot }, }, + "./util/reactNativeCommand": { ReactNativeCommand: FakeCommand }, }) as typeof import("../../../src/extension/commands/rnDoctor"); - - const project = { - getPackager: Sinon.stub().returns({ - getProjectPath: Sinon.stub().returns(projectRootPath), - }), + const command = module.rnDoctor.formInstance(); + (command as any).project = { + getPackager: () => ({ getProjectPath: () => projectRoot }), + getWorkspaceFolder: () => workspaceFolder, }; - + // VS Code can serialize tasks, so events need not contain the original Task object. + const execution = (own: boolean) => ({ + task: { definition: own ? { ...executeTask.firstCall.args[0].definition } : {} }, + }); return { - rnDoctor: module.rnDoctor, - project, + command, commandError, - logger, - spawnResult, - spawnReactCommandStub, - commandExecutorConstructorStub, - outputVerifierConstructorStub, - processStub, - getChannelStub, - getNodeModulesRootStub, - getInternalErrorStub, + projectRoot, + nodeModulesRoot, + cli, + workspaceFolder, + getInternalError, + getNodeModulesRoot, + executorConstructor, + getNpmCliCommand, + shellConstructor, + taskConstructor, + executeTask, + processDispose, + taskDispose, + endProcess: (exitCode?: number, own = true) => + processHandler({ + execution: execution(own), + exitCode, + } as vscode.TaskProcessEndEvent), + endTask: (own = true) => + taskHandler({ execution: execution(own) } as vscode.TaskEndEvent), }; } - async function runCommand(stubs: ReturnType): Promise { - const command = stubs.rnDoctor.formInstance(); - (command as any).project = stubs.project; - await command.baseFn(); - return command; + for (const suffix of [".cmd", ""]) { + test(`should focus an interactive task using the selected CLI (${ + suffix || "Unix" + })`, async function () { + const s = createCommandModule(suffix); + const result = s.command.baseFn(); + assert.strictEqual(s.command.codeName, "doctor"); + assert.strictEqual(s.command.label, "React Native Doctor"); + assert.strictEqual(s.getNodeModulesRoot.calledWithExactly(s.projectRoot), true); + assert.strictEqual( + s.executorConstructor.calledWithExactly(s.nodeModulesRoot, s.projectRoot), + true, + ); + assert.strictEqual(s.getNpmCliCommand.calledWithExactly(s.cli), true); + assert.deepStrictEqual(s.shellConstructor.firstCall.args, [ + `${s.cli}${suffix}`, + ["doctor"], + { cwd: s.projectRoot }, + ]); + assert.strictEqual(s.taskConstructor.firstCall.args[1], s.workspaceFolder); + assert.strictEqual(s.taskConstructor.firstCall.args[2], "React Native Doctor"); + assert.deepStrictEqual(s.executeTask.firstCall.args[0].presentationOptions, { + reveal: 1, + focus: true, + panel: 2, + }); + s.endProcess(0); + await result; + assert.strictEqual(s.processDispose.calledOnce, true); + assert.strictEqual(s.taskDispose.calledOnce, true); + }); } - test("should expose the registered command metadata", async function () { - const stubs = createCommandModule(); - - const command = await runCommand(stubs); - - assert.strictEqual(command.codeName, "doctor"); - assert.strictEqual(command.label, "React Native Doctor"); - assert.strictEqual(command.error, stubs.commandError); - assert.strictEqual( - stubs.getInternalErrorStub.calledWithExactly(failedToRunDoctorErrorCode), - true, - ); - }); - - test("should execute React Native doctor from the project root", async function () { - const stubs = createCommandModule(); - - await runCommand(stubs); - - assert.strictEqual(stubs.getNodeModulesRootStub.calledWithExactly(projectRootPath), true); - assert.strictEqual( - stubs.getChannelStub.calledWithExactly("ReactNativeRunDoctor", true), - true, - ); - assert.strictEqual( - stubs.commandExecutorConstructorStub.calledWithExactly( - nodeModulesRoot, - projectRootPath, - stubs.logger, - ), - true, - ); - assert.strictEqual(stubs.spawnReactCommandStub.calledWithExactly("doctor"), true); - assert.strictEqual(stubs.processStub.calledWithExactly(stubs.spawnResult), true); + test("should wait for Doctor and ignore unrelated task events", async function () { + const s = createCommandModule(); + let completed = false; + const result = s.command.baseFn().then(() => { + completed = true; + }); + s.endProcess(1, false); + s.endTask(false); + await Promise.resolve(); + assert.strictEqual(completed, false); + s.endProcess(0); + s.endTask(); + await result; }); - test("should configure doctor output verification patterns", async function () { - const stubs = createCommandModule(); - - await runCommand(stubs); - - assert.strictEqual(stubs.outputVerifierConstructorStub.calledOnce, true); - const [generateSuccessPatterns, generateFailurePatterns, operationName] = - stubs.outputVerifierConstructorStub.firstCall.args; + for (const exitCode of [1, undefined]) { + test(`should report unsuccessful termination (${String(exitCode)})`, async function () { + const s = createCommandModule(); + const result = s.command.baseFn(); + const rejection = assert.rejects(() => result, s.commandError); + s.endProcess(exitCode); + await rejection; + assert.strictEqual( + s.getInternalError.calledWithExactly(101, `${s.cli}.cmd doctor`, exitCode), + true, + ); + assert.strictEqual(s.processDispose.calledOnce, true); + assert.strictEqual(s.taskDispose.calledOnce, true); + }); + } - assert.strictEqual(operationName, "run doctor"); - assert.deepStrictEqual(await generateSuccessPatterns(), ["run doctor succeeded"]); - assert.deepStrictEqual(await generateFailurePatterns(), [ - { - pattern: "Failed to run doctor", - errorCode: failedToRunDoctorErrorCode, - }, - ]); + test("should handle task termination without a process result", async function () { + const s = createCommandModule(); + const result = s.command.baseFn(); + const rejection = assert.rejects(() => result, s.commandError); + s.endTask(); + await rejection; + assert.strictEqual(s.processDispose.calledOnce, true); + assert.strictEqual(s.taskDispose.calledOnce, true); }); - test("should propagate output verification errors", async function () { - const error = new Error("doctor output verification failed"); - const stubs = createCommandModule(); - stubs.processStub.returns(Promise.reject(error)); - - await assert.rejects(() => runCommand(stubs), error); + test("should propagate startup failures and dispose listeners", async function () { + const s = createCommandModule(); + const error = new Error("Cannot start task"); + s.executeTask.returns(Promise.reject(error)); + await assert.rejects(() => s.command.baseFn(), error); + assert.strictEqual(s.processDispose.calledOnce, true); + assert.strictEqual(s.taskDispose.calledOnce, true); }); - test("should require a project before running React Native doctor", async function () { - const stubs = createCommandModule(); - const command = stubs.rnDoctor.formInstance(); - - await assert.rejects(() => command.baseFn(), assert.AssertionError); - - assert.strictEqual(stubs.getChannelStub.called, false); - assert.strictEqual(stubs.spawnReactCommandStub.called, false); - assert.strictEqual(stubs.processStub.called, false); + test("should require a project", async function () { + const s = createCommandModule(); + (s.command as any).project = undefined; + await assert.rejects(() => s.command.baseFn(), assert.AssertionError); + assert.strictEqual(s.executeTask.called, false); }); }); From 59913c18289c830c5041e932fcc0de5325894115 Mon Sep 17 00:00:00 2001 From: ZhiyanJia Date: Tue, 10 Nov 2026 14:53:27 +0800 Subject: [PATCH 6/8] fix: clear stale Metro process references to allow restart --- src/common/packager.ts | 85 +++++++++--- test/extension/packager.test.ts | 221 ++++++++++++++++++++++++++++++++ 2 files changed, 291 insertions(+), 15 deletions(-) diff --git a/src/common/packager.ts b/src/common/packager.ts index 25cf675d2..60af4601d 100644 --- a/src/common/packager.ts +++ b/src/common/packager.ts @@ -212,8 +212,10 @@ export class Packager { } public async start(resetCache: boolean = false): Promise { + this.clearExitedPackagerProcess(); this.packagerStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STARTING); let executedStartPackagerCmd = false; + let startedProcess: ChildProcess | undefined; let rnVersion: string; let reactEnv = {}; if (!(await this.isRunning())) { @@ -307,9 +309,15 @@ export class Packager { ).spawnExpoPackager(["--web"]); } - this.packagerProcess = packagerSpawnResult.spawnedProcess; - - packagerSpawnResult.outcome.catch(() => {}); // We ignore all outcome errors + const spawnedProcess = packagerSpawnResult.spawnedProcess; + this.packagerProcess = startedProcess = spawnedProcess; + void packagerSpawnResult.outcome.then( + () => this.clearPackagerProcess(spawnedProcess), + error => { + this.logger.debug(String(error)); + this.clearPackagerProcess(spawnedProcess); + }, + ); } if (await this.stopWithlowNode(reactEnv)) { @@ -319,7 +327,7 @@ export class Packager { ); } await this.verifiyTSVersion(); - await this.awaitStart(); + await this.awaitStart(startedProcess); if (executedStartPackagerCmd) { this.logger.info(localize("PackagerStarted", "Packager started.")); this.packagerStatus = PackagerStatus.PACKAGER_STARTED; @@ -356,6 +364,7 @@ export class Packager { } public async stop(silent: boolean = false): Promise { + this.clearExitedPackagerProcess(); this.packagerStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STOPPING); let successfullyStopped = false; @@ -379,6 +388,9 @@ export class Packager { successfullyStopped = true; } } else { + if (this.packagerProcess) { + await this.killPackagerProcess(); + } if (!silent) { this.logger.warning( ErrorHelper.getWarning( @@ -389,11 +401,6 @@ export class Packager { successfullyStopped = true; } this.setPackagerStopStateUI(); - void vscode.commands.executeCommand( - "setContext", - CONTEXT_VARIABLES_NAMES.IS_RN_PACKAGER_RUNNING, - false, - ); return successfullyStopped; } @@ -507,17 +514,39 @@ export class Packager { }); } - private async awaitStart(retryCount = 60, delay = 3000): Promise { + private async awaitStart( + packagerProcess?: ChildProcess, + retryCount = 60, + delay = 3000, + ): Promise { + const failure = localize("CouldNotStartPackager", "Could not start the packager."); + const checkProcess = () => { + if ( + packagerProcess && + (this.packagerProcess !== packagerProcess || + ("exitCode" in packagerProcess && packagerProcess.exitCode !== null) || + ("signalCode" in packagerProcess && packagerProcess.signalCode !== null)) + ) { + throw new Error(failure); + } + }; try { await PromiseUtil.retryAsync( - () => this.isRunning(), + async () => { + checkProcess(); + const running = await this.isRunning(); + checkProcess(); + return running; + }, running => running, retryCount, delay, - localize("CouldNotStartPackager", "Could not start the packager."), + failure, ); } catch (error) { - this.setPackagerStopStateUI(); + if (!this.packagerProcess || this.packagerProcess === packagerProcess) { + this.setPackagerStopStateUI(); + } throw error; } } @@ -672,6 +701,29 @@ export class Packager { private setPackagerStopStateUI() { this.packagerStatus = PackagerStatus.PACKAGER_STOPPED; this.packagerStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STOPPED); + void vscode.commands.executeCommand( + "setContext", + CONTEXT_VARIABLES_NAMES.IS_RN_PACKAGER_RUNNING, + false, + ); + } + + private clearExitedPackagerProcess(): void { + const packagerProcess = this.packagerProcess; + if ( + packagerProcess && + (("exitCode" in packagerProcess && packagerProcess.exitCode !== null) || + ("signalCode" in packagerProcess && packagerProcess.signalCode !== null)) + ) { + this.clearPackagerProcess(packagerProcess); + } + } + + private clearPackagerProcess(packagerProcess: ChildProcess): void { + if (this.packagerProcess === packagerProcess) { + this.packagerProcess = undefined; + this.setPackagerStopStateUI(); + } } private async killPackagerProcess(): Promise { @@ -681,10 +733,13 @@ export class Packager { this.projectPath, ); + const packagerProcess = this.packagerProcess; await new CommandExecutor(nodeModulesRoot, this.projectPath, this.logger).killReactPackager( - this.packagerProcess, + packagerProcess, ); - this.packagerProcess = undefined; + if (packagerProcess) { + this.clearPackagerProcess(packagerProcess); + } if ( await new ExponentHelper(this.workspacePath, this.projectPath).isExpoManagedApp(false) ) { diff --git a/test/extension/packager.test.ts b/test/extension/packager.test.ts index f174cd151..8617abc24 100644 --- a/test/extension/packager.test.ts +++ b/test/extension/packager.test.ts @@ -4,7 +4,14 @@ import * as path from "path"; import * as os from "os"; import { promises as fs } from "fs"; +import { ChildProcess } from "child_process"; +import { EventEmitter } from "events"; +import { PassThrough } from "stream"; +import * as vscode from "vscode"; import { Packager } from "../../src/common/packager"; +import { ISpawnResult } from "../../src/common/node/childProcess"; +import { PackagerStatus } from "../../src/extension/packagerStatusIndicator"; +import { CONTEXT_VARIABLES_NAMES } from "../../src/common/contextVariablesNames"; import { CommandExecutor } from "../../src/common/commandExecutor"; import { ProjectVersionHelper } from "../../src/common/projectVersionHelper"; import { AppLauncher } from "../../src/extension/appLauncher"; @@ -18,6 +25,220 @@ import assert = require("assert"); import * as sinon from "sinon"; suite("packager", function () { + suite("process lifecycle", function () { + class MetroProcess extends EventEmitter implements ChildProcess { + stdin = new PassThrough(); + stdout = new PassThrough(); + stderr = new PassThrough(); + stdio: ChildProcess["stdio"] = [this.stdin, this.stdout, this.stderr]; + killed = false; + pid = 12345; + connected = false; + exitCode: number | null = null; + signalCode: string | null = null; + kill = sinon.spy(); + send = sinon.stub().returns(false); + disconnect = sinon.spy(); + ref = sinon.spy(); + unref = sinon.spy(); + } + + let packager: Packager; + let running: boolean; + let stubs: Sinon.SinonStub[]; + let spawnStub: Sinon.SinonStub; + let killStub: Sinon.SinonStub; + let contextStub: Sinon.SinonStub; + let nextProcess: ReturnType; + let startupError: Error | undefined; + + function createProcess() { + const child = new MetroProcess(); + let resolveOutcome!: () => void; + let rejectOutcome!: (error: Error) => void; + const result: ISpawnResult = { + spawnedProcess: child, + stdin: child.stdin, + stdout: child.stdout, + stderr: child.stderr, + outcome: new Promise((resolve, reject) => { + resolveOutcome = resolve; + rejectOutcome = reject; + }), + }; + return { child, result, resolveOutcome, rejectOutcome }; + } + + setup(function () { + const projectPath = path.resolve(__dirname, "..", "resources"); + running = false; + startupError = undefined; + packager = new Packager(projectPath, projectPath, Packager.DEFAULT_PORT); + stubs = [ + sinon.stub(packager, "isRunning", async () => running), + sinon + .stub(ProjectVersionHelper, "getReactNativeVersions") + .returns(Promise.resolve({ reactNativeVersion: "0.87.1" })), + sinon + .stub(Object.getPrototypeOf(packager), "monkeyPatchOpnForRNPackager") + .returns(Promise.resolve()), + sinon + .stub(Object.getPrototypeOf(packager), "stopWithlowNode") + .returns(Promise.resolve(false)), + sinon + .stub(Object.getPrototypeOf(packager), "verifiyTSVersion") + .returns(Promise.resolve()), + sinon.stub(packager, "getPackagerArgs").returns(Promise.resolve([])), + sinon.stub(AppLauncher, "getNodeModulesRootByProjectPath").returns(projectPath), + sinon + .stub(ExponentHelper.prototype, "isExpoManagedApp") + .returns(Promise.resolve(false)), + ]; + spawnStub = sinon.stub(CommandExecutor.prototype, "spawnReactPackager", () => { + if (startupError) { + nextProcess.child.exitCode = 1; + nextProcess.rejectOutcome(startupError); + } else { + running = true; + } + return nextProcess.result; + }); + killStub = sinon.stub(CommandExecutor.prototype, "killReactPackager", async () => { + running = false; + }); + contextStub = sinon.stub(vscode.commands, "executeCommand").returns(Promise.resolve()); + stubs.push(spawnStub, killStub, contextStub); + }); + + teardown(function () { + stubs.reverse().forEach(stub => stub.restore()); + packager.getStatusIndicator().dispose(); + }); + + function spawn(process: ReturnType): void { + nextProcess = process; + startupError = undefined; + } + + test("restarts after an externally terminated Metro process", async function () { + const first = createProcess(); + spawn(first); + await packager.start(); + assert.strictEqual(packager.getPackagerStatus(), PackagerStatus.PACKAGER_STARTED); + + running = false; + first.child.signalCode = "SIGTERM"; + first.rejectOutcome(new Error("Metro terminated externally")); + await Promise.resolve(); + + assert.strictEqual(packager.getPackagerStatus(), PackagerStatus.PACKAGER_STOPPED); + assert( + contextStub.calledWith( + "setContext", + CONTEXT_VARIABLES_NAMES.IS_RN_PACKAGER_RUNNING, + false, + ), + ); + const second = createProcess(); + spawn(second); + await packager.start(); + assert.strictEqual(spawnStub.callCount, 2); + assert.strictEqual(packager.getPackagerStatus(), PackagerStatus.PACKAGER_STARTED); + }); + + test("restarts after Metro exits successfully", async function () { + const first = createProcess(); + spawn(first); + await packager.start(); + running = false; + first.child.exitCode = 0; + first.resolveOutcome(); + await Promise.resolve(); + + assert.strictEqual(packager.getPackagerStatus(), PackagerStatus.PACKAGER_STOPPED); + spawn(createProcess()); + await packager.start(); + assert.strictEqual(spawnStub.callCount, 2); + }); + + test("reports startup failure and allows retry after fixing a configuration error", async function () { + const failed = createProcess(); + spawn(failed); + startupError = new Error("METRO_CONFIG_REPRO"); + + await assert.rejects(packager.start()); + assert.strictEqual(packager.getPackagerStatus(), PackagerStatus.PACKAGER_STOPPED); + spawn(createProcess()); + await packager.start(); + assert.strictEqual(spawnStub.callCount, 2); + assert.strictEqual(packager.getPackagerStatus(), PackagerStatus.PACKAGER_STARTED); + }); + + test("allows stop then start after Metro exits before its outcome is delivered", async function () { + const first = createProcess(); + spawn(first); + await packager.start(); + running = false; + first.child.exitCode = 1; + + assert.strictEqual(await packager.stop(true), true); + assert.strictEqual(killStub.called, false); + spawn(createProcess()); + await packager.start(); + assert.strictEqual(spawnStub.callCount, 2); + }); + + test("a delayed outcome from an exited process does not clear a replacement process", async function () { + const first = createProcess(); + spawn(first); + await packager.start(); + running = false; + first.child.exitCode = 1; + + const second = createProcess(); + spawn(second); + await packager.start(); + first.rejectOutcome(new Error("Delayed exit notification")); + await Promise.resolve(); + + assert.strictEqual(packager.getPackagerStatus(), PackagerStatus.PACKAGER_STARTED); + await packager.stop(true); + assert.strictEqual(killStub.firstCall.args[0], second.child); + }); + + test("preserves normal stop and restart behavior", async function () { + const first = createProcess(); + spawn(first); + await packager.start(); + assert.strictEqual(await packager.stop(true), true); + assert.strictEqual(killStub.firstCall.args[0], first.child); + assert.strictEqual(packager.getPackagerStatus(), PackagerStatus.PACKAGER_STOPPED); + spawn(createProcess()); + await packager.start(); + assert.strictEqual(spawnStub.callCount, 2); + }); + + test("stops an owned process even when its status endpoint is unavailable", async function () { + const first = createProcess(); + spawn(first); + await packager.start(); + running = false; + await packager.stop(true); + assert.strictEqual(killStub.firstCall.args[0], first.child); + spawn(createProcess()); + await packager.start(); + assert.strictEqual(spawnStub.callCount, 2); + }); + + test("does not terminate a packager started outside the extension", async function () { + running = true; + await packager.start(); + assert.strictEqual(await packager.stop(true), false); + assert.strictEqual(spawnStub.called, false); + assert.strictEqual(killStub.called, false); + }); + }); + suite("Windows Metro paths", function () { const projectPath = "d:\\workspace\\app"; const nodeModulesRoot = "d:\\workspace"; From e74b12f65c68789ac8b0e52795583eb2960c0b4f Mon Sep 17 00:00:00 2001 From: ZhiyanJia Date: Tue, 10 Nov 2026 15:24:44 +0800 Subject: [PATCH 7/8] fix: handle comments when inserting debug configurations --- src/common/launchJsonCompletionHelper.ts | 34 ++--- .../launchJsonCompletionHelper.test.ts | 131 ++++++++++++++++++ 2 files changed, 140 insertions(+), 25 deletions(-) create mode 100644 test/extension/launchJsonCompletionHelper.test.ts diff --git a/src/common/launchJsonCompletionHelper.ts b/src/common/launchJsonCompletionHelper.ts index ea6481c00..5a8a71b37 100644 --- a/src/common/launchJsonCompletionHelper.ts +++ b/src/common/launchJsonCompletionHelper.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. -import { DebugConfiguration, TextDocument, Position, Range } from "vscode"; +import type { DebugConfiguration, TextDocument, Position } from "vscode"; import { createScanner, parse, SyntaxKind } from "jsonc-parser"; export type PositionOfCursor = "InsideEmptyArray" | "BeforeItem" | "AfterItem"; @@ -57,31 +57,15 @@ export class LaunchJsonCompletionHelper { document: TextDocument, position: Position, ): boolean { - const line = document.lineAt(position.line); - // Get text from start of line until the cursor. - const currentLine = document.getText(new Range(line.range.start, position)); - if (currentLine.trim().endsWith(",")) { - return true; + const textBeforeCursor = document.getText().slice(0, document.offsetAt(position)); + const scanner = createScanner(textBeforeCursor, true); + let previousToken = SyntaxKind.EOF; + let token = scanner.scan(); + while (token !== SyntaxKind.EOF) { + previousToken = token; + token = scanner.scan(); } - // If there are other characters, then don't bother. - if (currentLine.trim().length !== 0) { - return false; - } - - // Keep walking backwards until we hit a non-comma character or a comm character. - let startLineNumber = position.line - 1; - while (startLineNumber > 0) { - const lineText = document.lineAt(startLineNumber).text; - if (lineText.trim().endsWith(",")) { - return true; - } - // If there are other characters, then don't bother. - if (lineText.trim().length !== 0) { - return false; - } - startLineNumber -= 1; - } - return false; + return previousToken === SyntaxKind.CommaToken; } private static isConfigurationArrayEmpty(document: TextDocument): boolean { diff --git a/test/extension/launchJsonCompletionHelper.test.ts b/test/extension/launchJsonCompletionHelper.test.ts new file mode 100644 index 000000000..38d2cc877 --- /dev/null +++ b/test/extension/launchJsonCompletionHelper.test.ts @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for details. + +import assert = require("assert"); +import type { DebugConfiguration, Position, TextDocument } from "vscode"; +import { parse, ParseError } from "jsonc-parser"; +import { LaunchJsonCompletionHelper } from "../../src/common/launchJsonCompletionHelper"; + +suite("LaunchJsonCompletionHelper", function () { + const config: DebugConfiguration = { + name: "New configuration", + type: "reactnativedirect", + request: "attach", + }; + const existing = JSON.stringify({ ...config, name: "Existing configuration" }); + + function fixture(beforeCursor: string, afterCursor: string) { + const text = beforeCursor + afterCursor; + const lines = beforeCursor.split("\n"); + const position = { + line: lines.length - 1, + character: lines[lines.length - 1].length, + } as Position; + const document: Pick = { + getText: () => text, + offsetAt: () => beforeCursor.length, + }; + return { document: document as TextDocument, position }; + } + + const separators = [ + { name: "same-line comma", text: ", ", hasComma: true }, + { name: "comma before blank lines", text: ",\n\n ", hasComma: true }, + { name: "comma before a line comment", text: ",\n// staging\n ", hasComma: true }, + { + name: "comma before a trailing line comment", + text: ", // staging\n ", + hasComma: true, + }, + { + name: "comma before a multiline block comment", + text: ",\n/* staging\nconfiguration */\n ", + hasComma: true, + }, + { + name: "comma before mixed comments and whitespace", + text: ",\r\n// staging\r\n\r\n/* another configuration */\r\n ", + hasComma: true, + }, + { name: "no comma", text: "\n ", hasComma: false }, + { + name: "line comment ending with a comma but no separator", + text: "\n// staging,\n ", + hasComma: false, + }, + { + name: "block comment containing a comma but no separator", + text: "\n/* staging, */\n ", + hasComma: false, + }, + ]; + + for (const { name, text, hasComma } of separators) { + test(`should insert valid JSONC after ${name}`, function () { + const beforeCursor = `{"version":"0.2.0","configurations":[${existing}${text}`; + const afterCursor = "\n]}"; + const { document, position } = fixture(beforeCursor, afterCursor); + assert.strictEqual( + LaunchJsonCompletionHelper.isCommaImmediatelyBeforeCursor(document, position), + hasComma, + ); + const cursorPosition = + LaunchJsonCompletionHelper.getCursorPositionInConfigurationsArray( + document, + position, + ); + assert.strictEqual(cursorPosition, "AfterItem"); + const inserted = LaunchJsonCompletionHelper.getTextForInsertion( + config, + cursorPosition, + hasComma ? "BeforeCursor" : undefined, + ); + const errors: ParseError[] = []; + const result = parse(beforeCursor + inserted + afterCursor, errors, { + allowTrailingComma: true, + }); + assert.deepStrictEqual(errors, []); + assert.deepStrictEqual(result.configurations, [JSON.parse(existing), config]); + }); + } + + test("should ignore tokens after the cursor on the same line", function () { + const { document, position } = fixture(`{"configurations":[${existing}, `, `${existing}]}`); + assert.strictEqual( + LaunchJsonCompletionHelper.isCommaImmediatelyBeforeCursor(document, position), + true, + ); + }); + + test("should not treat a comma inside a string as a separator", function () { + const { document, position } = fixture('{"name":"staging," ', "}"); + assert.strictEqual( + LaunchJsonCompletionHelper.isCommaImmediatelyBeforeCursor(document, position), + false, + ); + }); + + for (const beforeItem of [false, true]) { + test(`should preserve insertion ${ + beforeItem ? "before an item" : "in an empty array" + }`, function () { + const beforeCursor = '{"configurations":[ /* staging */ '; + const afterCursor = beforeItem ? `${existing}]}` : "]}"; + const { document, position } = fixture(beforeCursor, afterCursor); + const cursorPosition = + LaunchJsonCompletionHelper.getCursorPositionInConfigurationsArray( + document, + position, + ); + assert.strictEqual(cursorPosition, beforeItem ? "BeforeItem" : "InsideEmptyArray"); + const inserted = LaunchJsonCompletionHelper.getTextForInsertion(config, cursorPosition); + const errors: ParseError[] = []; + const result = parse(beforeCursor + inserted + afterCursor, errors); + assert.deepStrictEqual(errors, []); + assert.deepStrictEqual( + result.configurations, + beforeItem ? [config, JSON.parse(existing)] : [config], + ); + }); + } +}); From 6e09b169100ba9ee2f4e0cb1dfe36a6f22f22e84 Mon Sep 17 00:00:00 2001 From: ZhiyanJia Date: Wed, 11 Nov 2026 10:49:34 +0800 Subject: [PATCH 8/8] fix: specify Android device for Expo Go installation --- src/common/installHelper.ts | 6 +++--- src/extension/android/adb.ts | 9 +++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/common/installHelper.ts b/src/common/installHelper.ts index 68380ab5b..292f50cb9 100644 --- a/src/common/installHelper.ts +++ b/src/common/installHelper.ts @@ -22,19 +22,19 @@ export async function installAndroidApplication(project: AppLauncher, appPath: s `Found ${targets.length} online emulators, installing application on ${targets[0].id}. \n`, ); try { - await adbHelper.installApplicationToEmulator(appPath); + await adbHelper.installApplicationToEmulator(appPath, targets[0].id); } catch { throw new Error(`Failed to install application: ${appPath}.`); } } else { logger.logStream(`Installing application on ${targets[0].id}. \n`); try { - await adbHelper.installApplicationToEmulator(appPath); + await adbHelper.installApplicationToEmulator(appPath, targets[0].id); } catch { throw new Error(`Failed to install application: ${appPath}.`); } - logger.logStream(`Install Android application is completed. \n`); } + logger.logStream(`Install Android application is completed. \n`); } export async function installiOSApplication(project: AppLauncher, appPath: string) { diff --git a/src/extension/android/adb.ts b/src/extension/android/adb.ts index 2fc99fbdd..4903f9ffa 100644 --- a/src/extension/android/adb.ts +++ b/src/extension/android/adb.ts @@ -267,8 +267,13 @@ export class AdbHelper { ]); } - public installApplicationToEmulator(appPath: string): Promise { - return this.childProcess.execFileToString("adb", ["install", appPath]); + public installApplicationToEmulator(appPath: string, deviceId: string): Promise { + return this.childProcess.execFileToString(this.adbExecutable, [ + "-s", + deviceId, + "install", + appPath, + ]); } public executeQuery(deviceId: string, args: string[]): Promise {