From 83bbed0221d5722ab6344371cb1f4b5a36b2a5d3 Mon Sep 17 00:00:00 2001 From: Lihua <1017343802@qq.com> Date: Wed, 25 Nov 2026 03:53:23 -0800 Subject: [PATCH 1/2] Suppress Windows console windows for console-subsystem children Windows allocates a visible conhost window for every console-subsystem child of a parent without a console, so the node, python and git helpers spawned throughout a goal start flash black windows on console-less hosts, and the detached usage observer intermittently surfaces ERROR_NO_DATA (0x800700E8) when its child exits before reading stdin. Add a shared no_console_creationflags() helper (CREATE_NO_WINDOW on Windows, 0 elsewhere) and apply it at the launch sites the CLI, goal/turn, quota and validation paths execute. Keep the detached observer's DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP flags and make its pipe-closed stdin write race non-fatal. TypeScript hosts that spawn python or loopx CLI children set windowsHide: true, matching the existing host_process and zcode_goal_mode precedent. Non-Windows behavior is byte-for-byte unchanged; the helper is imported lazily so cold import contracts stay cold. Fixes #9430 Signed-off-by: Lihua <1017343802@qq.com> --- loopx/control_plane/agents/workspace_guard.py | 6 + .../capabilities/explore_research_terminal.ts | 1 + .../coordination/nokv_jsonl_transport.ts | 2 +- .../coordination/shadow_drain_files.ts | 1 + loopx/control_plane/effect_runtime.py | 4 + loopx/control_plane/goals/planning_batch.py | 3 + .../heartbeat/installed_prompt_update.py | 5 +- loopx/control_plane/quota/scheduler_ack.py | 3 + loopx/control_plane/runtime/node_probe.py | 6 + .../runtime/validation_command.py | 3 +- loopx/control_plane/state_recovery_io.py | 5 +- loopx/control_plane/status/goal_source.py | 5 +- .../todos/completion_validation.py | 2 + .../codex_execution_preparation.py | 3 + .../control_plane/turn_driver/codex_stdio.py | 3 + .../turn_driver/command_validation.py | 3 + .../turn_driver/host_process_transport.py | 3 + loopx/entrypoint.py | 4 +- loopx/extensions/process_runtime.py | 15 + loopx/pi_goal_mode/loopx-goal.ts | 2 + loopx/registry.py | 4 + loopx/usage_ping.py | 21 +- tests/extensions/test_process_runtime.py | 24 + tests/test_child_console_suppression.py | 482 ++++++++++++++++++ 24 files changed, 601 insertions(+), 9 deletions(-) create mode 100644 tests/test_child_console_suppression.py diff --git a/loopx/control_plane/agents/workspace_guard.py b/loopx/control_plane/agents/workspace_guard.py index c0cd9452fc..22f0d26982 100644 --- a/loopx/control_plane/agents/workspace_guard.py +++ b/loopx/control_plane/agents/workspace_guard.py @@ -39,6 +39,8 @@ def _is_same_or_child_path(path: Path, root: Path) -> bool: def _git_command_output(path: Path, *args: str) -> str | None: + from ...extensions.process_runtime import no_console_creationflags + try: result = subprocess.run( ["git", "-C", str(path), *args], @@ -47,6 +49,7 @@ def _git_command_output(path: Path, *args: str) -> str | None: stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=1.5, + creationflags=no_console_creationflags(), ) except (OSError, subprocess.TimeoutExpired): return None @@ -134,11 +137,14 @@ def _capture_local_goal_workspace( def _git_origin_is_absent(path: Path) -> bool: """Only Git's missing-key result permits local fallback; errors do not.""" + from ...extensions.process_runtime import no_console_creationflags + try: result = subprocess.run( ["git", "-C", str(path), "config", "--get", "remote.origin.url"], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=1.5, + creationflags=no_console_creationflags(), ) except (OSError, subprocess.TimeoutExpired): return False diff --git a/loopx/control_plane/capabilities/explore_research_terminal.ts b/loopx/control_plane/capabilities/explore_research_terminal.ts index 913acea760..70580d1db5 100644 --- a/loopx/control_plane/capabilities/explore_research_terminal.ts +++ b/loopx/control_plane/capabilities/explore_research_terminal.ts @@ -56,6 +56,7 @@ export class ResearchTerminalEvidenceHost { } this.child = spawn(python, ["-m", "loopx.capabilities.explore.research_snapshot_host"], { stdio: ["pipe", "pipe", "pipe"], env: {...process.env, PYTHONPATH: fileURLToPath(new URL("../../../", import.meta.url))}, + windowsHide: true, }); this.exited = new Promise(resolve => this.child!.once("close", () => resolve())); this.child.on("error", () => {}); this.child.stdin.on("error", () => {}); this.child.stderr.resume(); diff --git a/loopx/control_plane/coordination/nokv_jsonl_transport.ts b/loopx/control_plane/coordination/nokv_jsonl_transport.ts index 5a784a4d4b..1797186977 100644 --- a/loopx/control_plane/coordination/nokv_jsonl_transport.ts +++ b/loopx/control_plane/coordination/nokv_jsonl_transport.ts @@ -144,7 +144,7 @@ export class NoKVJsonLinesTransport implements NoKVBlobTransport { positiveSafeInteger(this.requestTimeoutMs, "NoKV helper request timeout"); positiveSafeInteger(this.maxResponseBytes, "NoKV helper max response bytes"); const factory = options.process_factory ?? ((command, args, spawnOptions) => - spawn(command, args, { ...spawnOptions, stdio: ["pipe", "pipe", "pipe"] })); + spawn(command, args, { ...spawnOptions, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })); const [command, ...args] = options.argv; try { this.child = factory(command!, args, { diff --git a/loopx/control_plane/coordination/shadow_drain_files.ts b/loopx/control_plane/coordination/shadow_drain_files.ts index 93d8099e4d..4925d9aa9c 100644 --- a/loopx/control_plane/coordination/shadow_drain_files.ts +++ b/loopx/control_plane/coordination/shadow_drain_files.ts @@ -103,6 +103,7 @@ export class DrainKernelLockHost { if (!this.child) { this.child = spawn(this.python, ["-m", "loopx.control_plane.coordination.shadow_lock_host"], { stdio: ["pipe", "pipe", "pipe"], env: {...process.env, PYTHONPATH: fileURLToPath(new URL("../../../", import.meta.url))}, + windowsHide: true, }); this.exited = new Promise(resolve => this.child!.once("close", () => resolve())); this.child.on("error", () => {}); // The closed reply stream reports an unavailable host. diff --git a/loopx/control_plane/effect_runtime.py b/loopx/control_plane/effect_runtime.py index f03bf53c4a..ae1c1abc2b 100644 --- a/loopx/control_plane/effect_runtime.py +++ b/loopx/control_plane/effect_runtime.py @@ -1209,6 +1209,9 @@ def _start_runtime(*, fingerprint: str, info_path: Path) -> _RuntimeInfo: # is an unlinked temporary file, so it cannot deadlock the child on a # full pipe and it leaves no stale path behind. with tempfile.TemporaryFile() as startup_stderr: + # Keep cold import paths (loopx.contract) free of the process transport. + from ..extensions.process_runtime import no_console_creationflags + try: process = subprocess.Popen( _runtime_command( @@ -1218,6 +1221,7 @@ def _start_runtime(*, fingerprint: str, info_path: Path) -> _RuntimeInfo: ), env=environment, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=startup_stderr, start_new_session=os.name != "nt", close_fds=True, + creationflags=no_console_creationflags(), # The host outlives the command that started it. On Windows # a live child whose working directory is the caller's # directory keeps that directory (and its ancestors) from diff --git a/loopx/control_plane/goals/planning_batch.py b/loopx/control_plane/goals/planning_batch.py index 94a1284a0c..02512073e7 100644 --- a/loopx/control_plane/goals/planning_batch.py +++ b/loopx/control_plane/goals/planning_batch.py @@ -701,6 +701,8 @@ def inspect_state(self) -> PlanningFrontierSnapshot: } def _call(self, *args: str) -> dict[str, object]: + from ...extensions.process_runtime import no_console_creationflags + process = subprocess.run( [*self.cli, *args], cwd=self.cwd, @@ -708,6 +710,7 @@ def _call(self, *args: str) -> dict[str, object]: text=True, capture_output=True, timeout=120, + creationflags=no_console_creationflags(), ) try: result = json.loads(process.stdout) diff --git a/loopx/control_plane/heartbeat/installed_prompt_update.py b/loopx/control_plane/heartbeat/installed_prompt_update.py index e659b939a8..e354ef34bf 100644 --- a/loopx/control_plane/heartbeat/installed_prompt_update.py +++ b/loopx/control_plane/heartbeat/installed_prompt_update.py @@ -187,11 +187,14 @@ def update_with_prompts(payload: dict, *, registry: Path, runtime_root: str | No command += ["--runtime-root", runtime_root] command += ["automation-prompts", "sync-installed", "--codex-home", str(home), "--plan-file", str(plan_file), "--execute"] + from loopx.extensions.process_runtime import no_console_creationflags + try: # Do not accidentally import a checkout through the parent's PYTHONPATH. env = {key: value for key, value in os.environ.items() if key != "PYTHONPATH"} result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace", env=env, - timeout=timeout_seconds, cwd=directory) + timeout=timeout_seconds, cwd=directory, + creationflags=no_console_creationflags()) report = json.loads(result.stdout) if not isinstance(report, dict) or "results" not in report: raise ValueError("new runtime returned no prompt migration result") diff --git a/loopx/control_plane/quota/scheduler_ack.py b/loopx/control_plane/quota/scheduler_ack.py index f78de83ff3..c5ea022848 100644 --- a/loopx/control_plane/quota/scheduler_ack.py +++ b/loopx/control_plane/quota/scheduler_ack.py @@ -225,6 +225,8 @@ def _run_native_followup( / "heartbeat_followup_cli.ts" ), ] + from ...extensions.process_runtime import no_console_creationflags + try: completed = subprocess.run( command, @@ -234,6 +236,7 @@ def _run_native_followup( text=True, encoding="utf-8", timeout=30, + creationflags=no_console_creationflags(), ) except (OSError, subprocess.TimeoutExpired) as exc: raise RuntimeError("native scheduler follow-up command failed") from exc diff --git a/loopx/control_plane/runtime/node_probe.py b/loopx/control_plane/runtime/node_probe.py index 983c0e0416..d9c485af69 100644 --- a/loopx/control_plane/runtime/node_probe.py +++ b/loopx/control_plane/runtime/node_probe.py @@ -112,6 +112,11 @@ def recommended_action(self) -> str | None: def probe_node(*, timeout: float = STARTUP_READY_TIMEOUT_SECONDS) -> NodeProbe: + # Pure callers import this module cold; the process transport stays + # unselected until a probe actually launches a child (see + # tests/test_process_runtime_loading.py). + from ...extensions.process_runtime import no_console_creationflags + executable = shutil.which("node") if executable is None: return NodeProbe(NodeProbeOutcome.MISSING) @@ -121,6 +126,7 @@ def probe_node(*, timeout: float = STARTUP_READY_TIMEOUT_SECONDS) -> NodeProbe: completed = subprocess.run( [executable, "--version"], check=False, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, + creationflags=no_console_creationflags(), ) except subprocess.TimeoutExpired: return NodeProbe(NodeProbeOutcome.TIMED_OUT, executable) diff --git a/loopx/control_plane/runtime/validation_command.py b/loopx/control_plane/runtime/validation_command.py index c38be9afb1..9bc266b111 100644 --- a/loopx/control_plane/runtime/validation_command.py +++ b/loopx/control_plane/runtime/validation_command.py @@ -14,7 +14,7 @@ # Keep the historical exports and caller patch points, but select the OS # transport only when used. Decisions and deadlines remain with the caller. -_PROCESS_RUNTIME_EXPORTS = ("terminate_process_tree",) +_PROCESS_RUNTIME_EXPORTS = ("no_console_creationflags", "terminate_process_tree") def __getattr__(name: str) -> Any: @@ -195,6 +195,7 @@ def _direct_validation(argv: list[str], workspace: Path, timeout_seconds: int) - stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=os.name == "posix", + creationflags=_export("no_console_creationflags")(), ) as process: try: # Output is transient and never part of the public receipt. diff --git a/loopx/control_plane/state_recovery_io.py b/loopx/control_plane/state_recovery_io.py index 731565ba9e..74cd449b49 100644 --- a/loopx/control_plane/state_recovery_io.py +++ b/loopx/control_plane/state_recovery_io.py @@ -86,13 +86,16 @@ def _runtime(method: str, request: dict[str, Any]) -> dict[str, Any]: def _audit_owners(request: dict[str, Any]) -> dict[str, Any]: + from ..extensions.process_runtime import no_console_creationflags + command = [_node_executable(), "--no-warnings", "--max-old-space-size=512", "--experimental-sqlite", "--experimental-strip-types", *node_typescript_flags(), str(Path(__file__).with_name("state_recovery_worker.ts"))] try: completed = subprocess.run(command, input=json.dumps(request), text=True, encoding="utf-8", - capture_output=True, timeout=_OWNER_TIMEOUT_SECONDS, check=False) + capture_output=True, timeout=_OWNER_TIMEOUT_SECONDS, check=False, + creationflags=no_console_creationflags()) except subprocess.TimeoutExpired as exc: # subprocess.run kills and waits for this child only, never the daemon. raise StateRecoveryError("recovery_owner_timeout") from exc diff --git a/loopx/control_plane/status/goal_source.py b/loopx/control_plane/status/goal_source.py index 25746ea128..6f4e7c8a5a 100644 --- a/loopx/control_plane/status/goal_source.py +++ b/loopx/control_plane/status/goal_source.py @@ -71,8 +71,11 @@ def _text(value, field, limit=4096): def _run(argv, *, env=None): + from ...extensions.process_runtime import no_console_creationflags + # Diagnostics can contain private paths; callers must not return stderr. - result = subprocess.run(argv, env=env, capture_output=True, check=True, timeout=25) + result = subprocess.run(argv, env=env, capture_output=True, check=True, timeout=25, + creationflags=no_console_creationflags()) if len(result.stdout) > _MAX_BYTES: raise ValueError("Source read exceeds the display limit") return result.stdout.decode("utf-8") diff --git a/loopx/control_plane/todos/completion_validation.py b/loopx/control_plane/todos/completion_validation.py index 23c16fd303..fe25aa8fe8 100644 --- a/loopx/control_plane/todos/completion_validation.py +++ b/loopx/control_plane/todos/completion_validation.py @@ -97,6 +97,7 @@ def _workspace_failure(label: str, *, status: str, summary: str) -> dict[str, An def _git_workspace_is_clean(path: Path) -> bool | None: """Return clean/dirty without exposing local paths or command output.""" + from ...extensions.process_runtime import no_console_creationflags try: result = subprocess.run( @@ -106,6 +107,7 @@ def _git_workspace_is_clean(path: Path) -> bool | None: stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=2, + creationflags=no_console_creationflags(), ) except (OSError, subprocess.TimeoutExpired): return None diff --git a/loopx/control_plane/turn_driver/codex_execution_preparation.py b/loopx/control_plane/turn_driver/codex_execution_preparation.py index 1751200f79..d7ab2c1d07 100644 --- a/loopx/control_plane/turn_driver/codex_execution_preparation.py +++ b/loopx/control_plane/turn_driver/codex_execution_preparation.py @@ -138,10 +138,13 @@ def compact_execution_preparation_request( def _default_runner( command: Sequence[str], *, cwd: Path, timeout: float, ) -> subprocess.CompletedProcess[str]: + from ...extensions.process_runtime import no_console_creationflags + completed = subprocess.run( list(command), cwd=str(cwd), capture_output=True, text=False, timeout=timeout, check=False, + creationflags=no_console_creationflags(), ) # The receipt is protocol data and must decode exactly. Stderr is only # diagnostic output from the launcher; an unrelated invalid byte there diff --git a/loopx/control_plane/turn_driver/codex_stdio.py b/loopx/control_plane/turn_driver/codex_stdio.py index 700a0ccf5a..7397fd814e 100644 --- a/loopx/control_plane/turn_driver/codex_stdio.py +++ b/loopx/control_plane/turn_driver/codex_stdio.py @@ -72,6 +72,8 @@ def spawn( ) -> StdioNativeGoalTransport: if not command: raise ValueError("command must be non-empty") + from ...extensions.process_runtime import no_console_creationflags + process = subprocess.Popen( list(command), cwd=cwd, @@ -82,6 +84,7 @@ def spawn( text=True, encoding="utf-8", bufsize=1, + creationflags=no_console_creationflags(), ) return cls(process, response_timeout_sec=response_timeout_sec) diff --git a/loopx/control_plane/turn_driver/command_validation.py b/loopx/control_plane/turn_driver/command_validation.py index 3280cfc276..656c825450 100644 --- a/loopx/control_plane/turn_driver/command_validation.py +++ b/loopx/control_plane/turn_driver/command_validation.py @@ -127,6 +127,8 @@ def validate( _plan: Mapping[str, Any], result: Mapping[str, Any], ) -> Mapping[str, Any]: + from ...extensions.process_runtime import no_console_creationflags + try: completed = subprocess.run( normalized, @@ -137,6 +139,7 @@ def validate( stderr=subprocess.DEVNULL, timeout=max(1.0, timeout_seconds), check=False, + creationflags=no_console_creationflags(), ) except (OSError, subprocess.TimeoutExpired): return { diff --git a/loopx/control_plane/turn_driver/host_process_transport.py b/loopx/control_plane/turn_driver/host_process_transport.py index 9a2309a580..3a7d5941fb 100644 --- a/loopx/control_plane/turn_driver/host_process_transport.py +++ b/loopx/control_plane/turn_driver/host_process_transport.py @@ -338,6 +338,8 @@ def run_host_process( launch_deadline = time.monotonic() + launch_budget if launch_guard is not None else None launch_arguments = (["--guarded-launch", str((time.time() + launch_budget) * 1000)] if launch_guard is not None else []) + from ...extensions.process_runtime import no_console_creationflags + with ExitStack() as containment: windows_job = None if sys.platform == "win32": @@ -360,6 +362,7 @@ def run_host_process( errors="strict", start_new_session=True, env=bridge_environment, + creationflags=no_console_creationflags(), ) assert proc.stdin is not None and proc.stdout is not None result: dict[str, Any] | None = None diff --git a/loopx/entrypoint.py b/loopx/entrypoint.py index 3c2bf912b2..e096e48bd2 100644 --- a/loopx/entrypoint.py +++ b/loopx/entrypoint.py @@ -150,7 +150,9 @@ def main(argv: list[str] | None = None) -> int: # Windows execv does not propagate the replaced process's status. # Wait for the typed owner so rejected writes remain CLI failures. import subprocess - return subprocess.call(native_argv) + + from .extensions.process_runtime import no_console_creationflags + return subprocess.call(native_argv, creationflags=no_console_creationflags()) os.execv(native_argv[0], native_argv) from .cli_runtime import main as runtime_main diff --git a/loopx/extensions/process_runtime.py b/loopx/extensions/process_runtime.py index 43c11cd9b1..aa1296fa29 100644 --- a/loopx/extensions/process_runtime.py +++ b/loopx/extensions/process_runtime.py @@ -19,6 +19,21 @@ _PROCESS_GROUP_STOP_TIMEOUT_SECONDS = 1.0 +def no_console_creationflags() -> int: + """Creation flags that stop a console-subsystem child from opening a console. + + Windows allocates a visible console host window for every console-subsystem + child of a parent that has no console, so short-lived helpers such as node, + python or git flash a black window on console-less hosts. CREATE_NO_WINDOW + suppresses that allocation without touching handle inheritance or stdio. + The constant only exists on Windows; every other platform reports 0, which + is subprocess's default and leaves behavior unchanged. + """ + if os.name != "nt": + return 0 + return int(getattr(subprocess, "CREATE_NO_WINDOW", 0)) + + def write_process_stdin_before_deadline( process: subprocess.Popen[str], text: str, *, deadline: float, cancel_and_reap: Callable[[], None], diff --git a/loopx/pi_goal_mode/loopx-goal.ts b/loopx/pi_goal_mode/loopx-goal.ts index 051d1c4254..4743661bcd 100644 --- a/loopx/pi_goal_mode/loopx-goal.ts +++ b/loopx/pi_goal_mode/loopx-goal.ts @@ -65,6 +65,7 @@ async function runLoopxCli(args: string[], directory: string): Promise { cwd: directory, timeout: LOOPX_CLI_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, + windowsHide: true, }); return stdout; } @@ -208,6 +209,7 @@ async function runLoopxTaskLeaseCli( cwd: directory, timeout: LOOPX_CLI_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, + windowsHide: true, }); return { stdout, returncode: 0 }; } catch (error) { diff --git a/loopx/registry.py b/loopx/registry.py index 25e0777dae..ea05b8fc53 100644 --- a/loopx/registry.py +++ b/loopx/registry.py @@ -144,6 +144,9 @@ def unavailable() -> dict[str, Any]: } def run_git(*args: str, cwd: Path = probe_dir) -> subprocess.CompletedProcess[str] | None: + # Select the OS transport only when a probe actually launches a child. + from .extensions.process_runtime import no_console_creationflags + # A probe that times out must retire everything it started. `run` kills # only the leader, so a Git that fanned out into a helper, a hook or a # remote would outlive the deadline on every later status read. @@ -159,6 +162,7 @@ def run_git(*args: str, cwd: Path = probe_dir) -> subprocess.CompletedProcess[st start_new_session=os.name == "posix", creationflags=( int(getattr(subprocess, "CREATE_NEW_PROCESS_GROUP")) + | no_console_creationflags() if os.name == "nt" else 0 ), ) diff --git a/loopx/usage_ping.py b/loopx/usage_ping.py index 9b468e8de2..9f4c427f3f 100644 --- a/loopx/usage_ping.py +++ b/loopx/usage_ping.py @@ -132,9 +132,12 @@ def _command() -> list[str]: def control(action: str, path: Path | None = None, **fields: Any) -> dict[str, Any]: + from .extensions.process_runtime import no_console_creationflags + try: result = subprocess.run(_command(), input=json.dumps(_request(action, path or state_path(), **fields)), - capture_output=True, text=True, encoding="utf-8", timeout=4, check=False) + capture_output=True, text=True, encoding="utf-8", timeout=4, check=False, + creationflags=no_console_creationflags()) except (OSError, subprocess.TimeoutExpired, UnicodeError): raise UsageSettingsUnavailable() from None try: @@ -278,5 +281,17 @@ def _detach(request: dict[str, Any], *, command: list[str] | None = None) -> Non kwargs["start_new_session"] = True child = subprocess.Popen(command or _command(), **kwargs) assert child.stdin is not None - child.stdin.write(json.dumps(request).encode()) - child.stdin.close() + try: + child.stdin.write(json.dumps(request).encode()) + child.stdin.close() + except OSError: + # A detached child that exits before reading (for example a suppressed + # or busy observer) closes its stdin pipe first; Windows then fails the + # parent's write with ERROR_NO_DATA ("The pipe is being closed", the + # 0x800700E8 detach failure in issue #9430). The observation is already + # best-effort, so the race must stay non-fatal instead of surfacing as + # a launch error. Closing the write end is idempotent enough for GC. + try: + child.stdin.close() + except OSError: + pass diff --git a/tests/extensions/test_process_runtime.py b/tests/extensions/test_process_runtime.py index 5b4dc67549..689da98f26 100644 --- a/tests/extensions/test_process_runtime.py +++ b/tests/extensions/test_process_runtime.py @@ -879,3 +879,27 @@ def test_run_capped_process_retains_stderr_backwards_compatibly() -> None: assert result.returncode == 1 assert result.stdout == b"ok" assert b"boom trace" in result.stderr + + +def test_no_console_creationflags_is_zero_off_windows() -> None: + if os.name == "nt": + pytest.skip("host is Windows; covered by the emulated-non-Windows case") + assert process_runtime.no_console_creationflags() == 0 + + +def test_no_console_creationflags_reports_create_no_window_on_windows( + monkeypatch: pytest.MonkeyPatch, +) -> None: + with monkeypatch.context() as patched: + patched.setattr(os, "name", "nt") + patched.setattr(subprocess, "CREATE_NO_WINDOW", 0x08000000, raising=False) + assert process_runtime.no_console_creationflags() == 0x08000000 + + +def test_no_console_creationflags_stays_zero_without_the_constant( + monkeypatch: pytest.MonkeyPatch, +) -> None: + with monkeypatch.context() as patched: + patched.setattr(os, "name", "nt") + patched.delattr(subprocess, "CREATE_NO_WINDOW", raising=False) + assert process_runtime.no_console_creationflags() == 0 diff --git a/tests/test_child_console_suppression.py b/tests/test_child_console_suppression.py new file mode 100644 index 0000000000..5d04d451f3 --- /dev/null +++ b/tests/test_child_console_suppression.py @@ -0,0 +1,482 @@ +"""Console-suppression spawn options for Windows console-less hosts (issue #9430). + +Windows allocates a visible conhost window for every console-subsystem child of +a parent without a console. These tests never require Windows: each one inspects +the options handed to the spawn call and asserts the computed creationflags +(0 on POSIX, CREATE_NO_WINDOW under an emulated Windows ``os.name``). The +emulation rebinds only the ``os`` name each site reads, so ``pathlib`` keeps +resolving POSIX paths on this host. The visible window and pipe behavior itself +is owned by CI's Windows lanes and interactive Windows verification, not by +these host-agnostic assertions. +""" +from __future__ import annotations + +import io +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest + +import loopx.entrypoint as entrypoint_module +import loopx.usage_ping as usage_ping +from loopx import registry as registry_module +from loopx.control_plane import effect_runtime as effect_runtime_module +from loopx.control_plane import state_recovery_io as state_recovery_module +from loopx.control_plane.agents import workspace_guard as workspace_guard_module +from loopx.control_plane.effect_runtime import EffectRuntimeStartupError +from loopx.control_plane.effect_runtime import _start_runtime as start_runtime +from loopx.control_plane.goals import planning_batch as planning_batch_module +from loopx.control_plane.heartbeat import installed_prompt_update as prompt_update_module +from loopx.control_plane.quota import scheduler_ack as scheduler_ack_module +from loopx.control_plane.runtime import node_probe as node_probe_module +from loopx.control_plane.runtime import validation_command as validation_command_module +from loopx.control_plane.state_recovery_io import _audit_owners as audit_owners +from loopx.control_plane.status import goal_source as goal_source_module +from loopx.control_plane.todos import completion_validation as completion_module +from loopx.control_plane.turn_driver import codex_execution_preparation as preparation_module +from loopx.control_plane.turn_driver import codex_stdio as codex_stdio_module +from loopx.control_plane.turn_driver import command_validation as command_validation_module +from loopx.control_plane.turn_driver import host_process_transport as host_transport_module +import loopx.extensions.process_runtime as process_runtime_module +from loopx.extensions.process_runtime import no_console_creationflags + +WINDOWS_CREATE_NO_WINDOW = 0x08000000 +WINDOWS_CREATE_NEW_PROCESS_GROUP = 0x200 +WINDOWS_DETACHED_PROCESS = 0x8 + + +class WindowsNameOnly: + """Report the Windows platform name while delegating everything else to os.""" + + def __getattr__(self, name: str) -> Any: + return getattr(os, name) + + name = "nt" + + +@pytest.fixture() +def windows_spawn_constants(monkeypatch: pytest.MonkeyPatch) -> None: + """Provide the Windows creation-flag constants on any host.""" + monkeypatch.setattr(subprocess, "CREATE_NO_WINDOW", WINDOWS_CREATE_NO_WINDOW, raising=False) + monkeypatch.setattr( + subprocess, "CREATE_NEW_PROCESS_GROUP", WINDOWS_CREATE_NEW_PROCESS_GROUP, raising=False) + monkeypatch.setattr(subprocess, "DETACHED_PROCESS", WINDOWS_DETACHED_PROCESS, raising=False) + + +def emulate_windows_spawn( + monkeypatch: pytest.MonkeyPatch, + *site_modules: Any, + constants: bool = True, +) -> None: + """Make the helper and the named site modules observe ``os.name == 'nt'``.""" + proxy = WindowsNameOnly() + monkeypatch.setattr(process_runtime_module, "os", proxy) + for module in site_modules: + monkeypatch.setattr(module, "os", proxy) + if constants: + monkeypatch.setattr( + subprocess, "CREATE_NO_WINDOW", WINDOWS_CREATE_NO_WINDOW, raising=False) + monkeypatch.setattr( + subprocess, "CREATE_NEW_PROCESS_GROUP", WINDOWS_CREATE_NEW_PROCESS_GROUP, + raising=False) + monkeypatch.setattr( + subprocess, "DETACHED_PROCESS", WINDOWS_DETACHED_PROCESS, raising=False) + + +class Captured: + """Record the options handed to one spawn call.""" + + def __init__(self, stdout: str = '{"ok": true}') -> None: + self.stdout = stdout + self.kwargs: dict[str, object] | None = None + + def record(self, *_args: object, **kwargs: object) -> subprocess.CompletedProcess[str]: + self.kwargs = kwargs + return subprocess.CompletedProcess(list(_args), 0, self.stdout, "") + + +def test_node_probe_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured(stdout="v22.22.3\n") + monkeypatch.setattr(node_probe_module.shutil, "which", lambda _name: str(tmp_path / "node")) + monkeypatch.setattr(node_probe_module.subprocess, "run", captured.record) + assert node_probe_module.probe_node().ready + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + with monkeypatch.context() as patched: + emulate_windows_spawn(patched) + assert node_probe_module.probe_node().ready + assert captured.kwargs["creationflags"] == WINDOWS_CREATE_NO_WINDOW + + +def test_usage_ping_control_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + monkeypatch.setattr(usage_ping.shutil, "which", lambda _name: sys.executable) + monkeypatch.setattr(usage_ping.subprocess, "run", captured.record) + assert usage_ping.control("status", tmp_path / "usage-ping.json") == {"ok": True} + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_usage_ping_detached_child_keeps_windows_detachment_flags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + monkeypatch.setattr(usage_ping, "_environment_suppressed", lambda *_a, **_k: False) + monkeypatch.setattr(usage_ping.shutil, "which", lambda _name: sys.executable) + emulate_windows_spawn(monkeypatch, usage_ping) + + class Child: + def __init__(self, *_args: object, **kwargs: object) -> None: + captured.record(*_args, **kwargs) + self.stdin = io.BytesIO() + + monkeypatch.setattr(usage_ping.subprocess, "Popen", Child) + usage_ping._detach({"action": "observe", "path": str(tmp_path)}) + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == ( + WINDOWS_DETACHED_PROCESS | WINDOWS_CREATE_NEW_PROCESS_GROUP + ) + assert "start_new_session" not in captured.kwargs + + +def test_usage_ping_detached_child_closing_its_pipe_stays_best_effort( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """A child that exits first closes the pipe; that race is not a launch error.""" + monkeypatch.setattr(usage_ping, "_environment_suppressed", lambda *_a, **_k: False) + monkeypatch.setattr(usage_ping.shutil, "which", lambda _name: sys.executable) + + class ClosingStdin: + def write(self, _data: bytes) -> int: + raise OSError(232, "The pipe is being closed") + + def close(self) -> None: + raise BrokenPipeError + + class Child: + stdin = ClosingStdin() + + def __init__(self, *_args: object, **_kwargs: object) -> None: + pass + + monkeypatch.setattr(usage_ping.subprocess, "Popen", Child) + usage_ping._detach({"action": "observe", "path": str(tmp_path)}) + + +def test_effect_runtime_host_popen_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + + class ExitedHost: + def __init__(self, *_args: object, **kwargs: object) -> None: + captured.record(*_args, **kwargs) + + def poll(self) -> int: + return 1 + + def terminate(self) -> None: + raise AssertionError("an exited host needs no termination") + + monkeypatch.setattr(effect_runtime_module, "_acquire_start_lock", lambda *a, **k: None) + monkeypatch.setattr(effect_runtime_module, "_read_info", lambda *a, **k: None) + monkeypatch.setattr(effect_runtime_module, "_node_executable", lambda: sys.executable) + monkeypatch.setattr(effect_runtime_module, "_runtime_environment", lambda _token: {}) + monkeypatch.setattr(effect_runtime_module.subprocess, "Popen", ExitedHost) + with pytest.raises(EffectRuntimeStartupError): + start_runtime(fingerprint="a" * 32, info_path=tmp_path / "runtime" / "info.json") + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + with monkeypatch.context() as patched: + emulate_windows_spawn(patched, effect_runtime_module) + with pytest.raises(EffectRuntimeStartupError): + start_runtime(fingerprint="a" * 32, info_path=tmp_path / "runtime2" / "info.json") + assert captured.kwargs["creationflags"] == WINDOWS_CREATE_NO_WINDOW + + +def test_registry_git_probe_combines_process_group_with_no_console( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + emulate_windows_spawn(monkeypatch, registry_module) + + class GitProbe: + def __init__(self, *_args: object, **kwargs: object) -> None: + captured.record(*_args, **kwargs) + self.returncode = 0 + + def communicate(self, timeout: float | None = None) -> tuple[str, str]: + return "", "" + + monkeypatch.setattr(registry_module, "_definitely_outside_git_worktree", lambda _p: False) + monkeypatch.setattr(registry_module.subprocess, "Popen", GitProbe) + registry_module._registry_git_probe(tmp_path / "registry.json") + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == ( + WINDOWS_CREATE_NEW_PROCESS_GROUP | WINDOWS_CREATE_NO_WINDOW + ) + + +def test_scheduler_ack_native_followup_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + monkeypatch.setattr(scheduler_ack_module, "_node_executable", lambda: sys.executable) + monkeypatch.setattr(scheduler_ack_module.subprocess, "run", captured.record) + result = scheduler_ack_module._run_native_followup( + runtime_root=tmp_path, before={}, host_facts={}, use_current_hint=False, + reason_summary=None, + ) + assert result == {"ok": True} + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_direct_validation_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + + class ValidatorProcess: + pid = 1111 + + def __init__(self, *_args: object, **kwargs: object) -> None: + captured.record(*_args, **kwargs) + self.returncode = 0 + + def __enter__(self) -> "ValidatorProcess": + return self + + def __exit__(self, *_exc: object) -> None: + return None + + def communicate(self, timeout: float | None = None) -> tuple[bytes, bytes]: + return b"", b"" + + monkeypatch.setattr(validation_command_module.subprocess, "Popen", ValidatorProcess) + exit_code = validation_command_module._direct_validation( + [sys.executable, "-c", "pass"], tmp_path, 5, + ) + assert exit_code == 0 + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_stdio_native_goal_transport_spawn_passes_no_console_creationflags( + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + + class HostProcess: + pid = 4242 + + def __init__(self, *_args: object, **kwargs: object) -> None: + captured.record(*_args, **kwargs) + self.stdin = io.StringIO() + self.stdout = io.StringIO("") + self.returncode = 0 + + def poll(self) -> int: + return 0 + + def wait(self, timeout: float | None = None) -> int: + return 0 + + def terminate(self) -> None: + return None + + def kill(self) -> None: + return None + + monkeypatch.setattr(codex_stdio_module.subprocess, "Popen", HostProcess) + transport = codex_stdio_module.StdioNativeGoalTransport.spawn( + [sys.executable, "-c", "pass"], cwd=str(Path.cwd()), + ) + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + transport.process.stdin.close() + transport.process.stdout.close() + + +def test_codex_execution_preparation_runner_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + + def record(command: object, **kwargs: object) -> subprocess.CompletedProcess[bytes]: + captured.record(command, **kwargs) + return subprocess.CompletedProcess(command, 0, b"{}", b"") + + monkeypatch.setattr(preparation_module.subprocess, "run", record) + result = preparation_module._default_runner( + [sys.executable, "-c", "pass"], cwd=tmp_path, timeout=1.0, + ) + assert result.returncode == 0 + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_turn_command_validator_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + monkeypatch.setattr(command_validation_module.subprocess, "run", captured.record) + validate = command_validation_module.build_loopx_turn_command_validator( + [sys.executable, "-c", "pass"], project=tmp_path, timeout_seconds=1.0, + ) + assert validate({}, {})["status"] == "passed" + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_planning_batch_cli_call_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + monkeypatch.setattr(planning_batch_module.subprocess, "run", captured.record) + backend = planning_batch_module.CliPlanningBatchBackend( + cli=[sys.executable], cwd=tmp_path, env=dict(os.environ), + packet_reader=lambda: {}, project="p", + ) + assert backend._call("status") == {"ok": True} + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_goal_source_run_passes_no_console_creationflags( + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + + def record(argv: object, **kwargs: object) -> subprocess.CompletedProcess[bytes]: + captured.record(argv, **kwargs) + return subprocess.CompletedProcess(argv, 0, b"text", b"") + + monkeypatch.setattr(goal_source_module.subprocess, "run", record) + assert goal_source_module._run([sys.executable, "-c", "pass"]) == "text" + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_completion_validation_git_status_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured(stdout="") + monkeypatch.setattr(completion_module.subprocess, "run", captured.record) + assert completion_module._git_workspace_is_clean(tmp_path) is True + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +@pytest.mark.parametrize("probe", ["output", "origin"]) +def test_workspace_guard_git_probes_pass_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, probe: str, +) -> None: + captured = Captured() + + def record(command: object, **kwargs: object) -> subprocess.CompletedProcess[str]: + captured.record(command, **kwargs) + return subprocess.CompletedProcess(command, 1, "", "") + + monkeypatch.setattr(workspace_guard_module.subprocess, "run", record) + if probe == "output": + assert workspace_guard_module._git_command_output(tmp_path, "rev-parse", "HEAD") is None + else: + assert workspace_guard_module._git_origin_is_absent(tmp_path) is True + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_state_recovery_audit_owners_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + monkeypatch.setattr(state_recovery_module, "_node_executable", lambda: sys.executable) + monkeypatch.setattr(state_recovery_module.subprocess, "run", captured.record) + assert audit_owners({"path": str(tmp_path)}) == {"ok": True} + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_installed_prompt_reconciliation_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured(stdout='{"ok": true, "results": []}') + monkeypatch.setattr(prompt_update_module, "snapshot", + lambda **_k: {"ok": True, "entries": [{"name": "managed"}]}) + import loopx.upgrade as upgrade_module + + monkeypatch.setattr(upgrade_module, "codex_home", lambda: tmp_path / "codex-home") + monkeypatch.setattr(prompt_update_module.subprocess, "run", captured.record) + updated = prompt_update_module.update_with_prompts( + {}, registry=tmp_path / "registry.json", runtime_root=None, + timeout_seconds=5, runtime_update=lambda _payload, timeout_seconds: {"ok": True}, + ) + assert updated["upgrade_complete"] is True + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_run_host_process_bridge_passes_no_console_creationflags( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + + class BridgeProcess: + pid = 8484 + + def __init__(self, *_args: object, **kwargs: object) -> None: + captured.record(*_args, **kwargs) + self.stdin = io.StringIO() + self.stdout = (line for line in ('{"kind": "result", "outcome": "exited"}\n',)) + self.returncode = 0 + + def poll(self) -> int: + return 0 + + def wait(self, timeout: float | None = None) -> int: + return 0 + + def terminate(self) -> None: + return None + + def kill(self) -> None: + return None + + monkeypatch.setattr(host_transport_module, "_node_executable", lambda: sys.executable) + monkeypatch.setattr(host_transport_module.subprocess, "Popen", BridgeProcess) + observation = host_transport_module.run_host_process( + [sys.executable, "-c", "pass"], project=tmp_path, input_text="", timeout_seconds=1.0, + ) + assert observation.get("outcome") == "exited" + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == no_console_creationflags() + + +def test_entrypoint_windows_native_followup_call_passes_no_console_creationflags( + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = Captured() + monkeypatch.delenv("LOOPX_KUNLUNCODE_OUTER_CONTROLLER", raising=False) + monkeypatch.setattr(entrypoint_module.shutil, "which", lambda _name: sys.executable) + emulate_windows_spawn(monkeypatch, entrypoint_module) + monkeypatch.setattr( + subprocess, "call", lambda *_args, **kwargs: (captured.record(*_args, **kwargs), 0)[1] + ) + monkeypatch.setattr( + sys, "argv", + ["loopx", "quota", "scheduler-ack-current", + "--scheduler-host-facts-chunk", "chunk", "--turn-instance-id", "turn"], + ) + assert entrypoint_module.main(None) == 0 + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == WINDOWS_CREATE_NO_WINDOW From b35624d7b332760a588f20737a5d49992aaea5be Mon Sep 17 00:00:00 2001 From: Lihua <1017343802@qq.com> Date: Fri, 27 Nov 2026 20:47:45 -0800 Subject: [PATCH 2/2] fix(windows): keep the console when the parent already owns one The foreground follow-up (`loopx quota scheduler-ack-current`) launches the scheduler without redirecting its streams, so the scheduler's receipt is printed on the console the user is reading. On a parent attached to a console, CREATE_NO_WINDOW detaches the child from that console: the review measured the nine receipt lines vanish from PowerShell while every child write still reported success. Windows allocates a new console for a child only when the parent has none, so that is now the only case in which the flag is returned. A child of an attached process inherits its console and opens no window, and the helper reports 0, which leaves every spawn site exactly on its previous behavior. A host that cannot answer the console query counts as attached: the query only refines the options and must never break a spawn. Both outcomes now land on cells the review measured on Windows: attached without the flag keeps the receipt, console-less with the flag opens no window. Signed-off-by: Lihua <1017343802@qq.com> --- loopx/extensions/process_runtime.py | 39 +++++++- tests/extensions/test_process_runtime.py | 25 +++++ tests/test_child_console_suppression.py | 117 +++++++++++++++++++++-- 3 files changed, 173 insertions(+), 8 deletions(-) diff --git a/loopx/extensions/process_runtime.py b/loopx/extensions/process_runtime.py index aa1296fa29..07efab8de2 100644 --- a/loopx/extensions/process_runtime.py +++ b/loopx/extensions/process_runtime.py @@ -19,6 +19,31 @@ _PROCESS_GROUP_STOP_TIMEOUT_SECONDS = 1.0 +def _console_attached(kernel32: Any) -> bool: + """Report whether the calling process owns a Win32 console. + + Either query succeeding means a console is attached. A process without one + fails both, and treating any success as attached keeps the answer on the + safe side: the only cost of a wrong "attached" is an unsuppressed window. + """ + return bool(kernel32.GetConsoleCP()) or bool(kernel32.GetConsoleWindow()) + + +def _parent_has_console() -> bool: + """Report whether this process owns a console; an unanswerable query is yes.""" + try: + import ctypes + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetConsoleCP.restype = ctypes.c_uint + kernel32.GetConsoleWindow.restype = ctypes.c_void_p + except (AttributeError, ImportError, OSError): + # The console query only refines the spawn options, so a host that + # cannot answer it keeps the child's behavior exactly as it was. + return True + return _console_attached(kernel32) + + def no_console_creationflags() -> int: """Creation flags that stop a console-subsystem child from opening a console. @@ -26,11 +51,21 @@ def no_console_creationflags() -> int: child of a parent that has no console, so short-lived helpers such as node, python or git flash a black window on console-less hosts. CREATE_NO_WINDOW suppresses that allocation without touching handle inheritance or stdio. - The constant only exists on Windows; every other platform reports 0, which - is subprocess's default and leaves behavior unchanged. + + The flag is returned only when this process has no console, because that is + the only case in which Windows would allocate a new one. A child of a + process attached to a console inherits that console and never opens a + window; passing the flag there would instead detach the child from the + console its output is being read from, and the child's writes to an + inherited stdout would vanish without an error. + + Every other platform reports 0, which is subprocess's default and leaves + behavior unchanged. """ if os.name != "nt": return 0 + if _parent_has_console(): + return 0 return int(getattr(subprocess, "CREATE_NO_WINDOW", 0)) diff --git a/tests/extensions/test_process_runtime.py b/tests/extensions/test_process_runtime.py index 689da98f26..18c1c47fcf 100644 --- a/tests/extensions/test_process_runtime.py +++ b/tests/extensions/test_process_runtime.py @@ -893,13 +893,38 @@ def test_no_console_creationflags_reports_create_no_window_on_windows( with monkeypatch.context() as patched: patched.setattr(os, "name", "nt") patched.setattr(subprocess, "CREATE_NO_WINDOW", 0x08000000, raising=False) + patched.setattr(process_runtime, "_parent_has_console", lambda: False) assert process_runtime.no_console_creationflags() == 0x08000000 +def test_no_console_creationflags_stays_zero_while_attached_to_a_console( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A child of an attached process inherits its console; the flag would only + # detach the child from the console its receipt is read on. + with monkeypatch.context() as patched: + patched.setattr(os, "name", "nt") + patched.setattr(subprocess, "CREATE_NO_WINDOW", 0x08000000, raising=False) + patched.setattr(process_runtime, "_parent_has_console", lambda: True) + assert process_runtime.no_console_creationflags() == 0 + + +def test_no_console_creationflags_survives_an_unanswerable_console_query( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The query must never break a spawn: unknown means the default behavior. + with monkeypatch.context() as patched: + patched.setattr(os, "name", "nt") + patched.setattr(subprocess, "CREATE_NO_WINDOW", 0x08000000, raising=False) + patched.setitem(sys.modules, "ctypes", None) + assert process_runtime.no_console_creationflags() == 0 + + def test_no_console_creationflags_stays_zero_without_the_constant( monkeypatch: pytest.MonkeyPatch, ) -> None: with monkeypatch.context() as patched: patched.setattr(os, "name", "nt") patched.delattr(subprocess, "CREATE_NO_WINDOW", raising=False) + patched.setattr(process_runtime, "_parent_has_console", lambda: False) assert process_runtime.no_console_creationflags() == 0 diff --git a/tests/test_child_console_suppression.py b/tests/test_child_console_suppression.py index 5d04d451f3..d7ec4abdc2 100644 --- a/tests/test_child_console_suppression.py +++ b/tests/test_child_console_suppression.py @@ -3,11 +3,12 @@ Windows allocates a visible conhost window for every console-subsystem child of a parent without a console. These tests never require Windows: each one inspects the options handed to the spawn call and asserts the computed creationflags -(0 on POSIX, CREATE_NO_WINDOW under an emulated Windows ``os.name``). The -emulation rebinds only the ``os`` name each site reads, so ``pathlib`` keeps -resolving POSIX paths on this host. The visible window and pipe behavior itself -is owned by CI's Windows lanes and interactive Windows verification, not by -these host-agnostic assertions. +(0 on POSIX and on a Windows host attached to a console; CREATE_NO_WINDOW under +an emulated Windows ``os.name`` on a host without one). The emulation rebinds +only the ``os`` name each site reads, so ``pathlib`` keeps resolving POSIX paths +on this host, and it answers the parent-console query directly. The visible +window and pipe behavior itself is owned by CI's Windows lanes and interactive +Windows verification, not by these host-agnostic assertions. """ from __future__ import annotations @@ -16,6 +17,7 @@ import subprocess import sys from pathlib import Path +from types import SimpleNamespace from typing import Any import pytest @@ -70,10 +72,18 @@ def emulate_windows_spawn( monkeypatch: pytest.MonkeyPatch, *site_modules: Any, constants: bool = True, + console_attached: bool = False, ) -> None: - """Make the helper and the named site modules observe ``os.name == 'nt'``.""" + """Make the helper and the named site modules observe ``os.name == 'nt'``. + + ``console_attached`` selects the host the spawn runs from: a console-less + host (the default, the case issue #9430 reports) or one attached to a + console, as when the user runs the command in PowerShell or cmd. + """ proxy = WindowsNameOnly() monkeypatch.setattr(process_runtime_module, "os", proxy) + monkeypatch.setattr( + process_runtime_module, "_parent_has_console", lambda: console_attached) for module in site_modules: monkeypatch.setattr(module, "os", proxy) if constants: @@ -480,3 +490,98 @@ def test_entrypoint_windows_native_followup_call_passes_no_console_creationflags assert entrypoint_module.main(None) == 0 assert captured.kwargs is not None assert captured.kwargs["creationflags"] == WINDOWS_CREATE_NO_WINDOW + + +@pytest.mark.parametrize( + ("platform_name", "console_attached", "expected"), + [ + ("posix", False, 0), + ("nt", False, WINDOWS_CREATE_NO_WINDOW), + ("nt", True, 0), + ], +) +def test_no_console_creationflags_follows_the_parent_console( + monkeypatch: pytest.MonkeyPatch, platform_name: str, console_attached: bool, + expected: int, +) -> None: + """The flag is returned for a console-less Windows host and nothing else.""" + monkeypatch.setattr(subprocess, "CREATE_NO_WINDOW", WINDOWS_CREATE_NO_WINDOW, raising=False) + monkeypatch.setattr(process_runtime_module, "os", SimpleNamespace(name=platform_name)) + monkeypatch.setattr( + process_runtime_module, "_parent_has_console", lambda: console_attached) + assert no_console_creationflags() == expected + + +@pytest.mark.parametrize( + ("code_page", "window", "attached"), + [(0, 0, False), (65001, 0, True), (0, 0x1234, True), (437, 0x1234, True)], +) +def test_console_attached_accepts_either_win32_query( + code_page: int, window: int, attached: bool, +) -> None: + """A console-less process fails both queries; either success means attached.""" + kernel32 = SimpleNamespace( + GetConsoleCP=lambda: code_page, GetConsoleWindow=lambda: window) + assert process_runtime_module._console_attached(kernel32) is attached + + +def _run_entrypoint_native_followup( + monkeypatch: pytest.MonkeyPatch, captured: Captured, +) -> int: + monkeypatch.delenv("LOOPX_KUNLUNCODE_OUTER_CONTROLLER", raising=False) + monkeypatch.setattr(entrypoint_module.shutil, "which", lambda _name: sys.executable) + monkeypatch.setattr( + subprocess, "call", lambda *_args, **kwargs: (captured.record(*_args, **kwargs), 0)[1]) + monkeypatch.setattr( + sys, "argv", + ["loopx", "quota", "scheduler-ack-current", + "--scheduler-host-facts-chunk", "chunk", "--turn-instance-id", "turn"], + ) + return entrypoint_module.main(None) + + +def test_entrypoint_windows_native_followup_keeps_the_console_receipt_when_attached( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A user running the follow-up in PowerShell or cmd still reads its receipt. + + The scheduler child writes its receipt to an inherited stdout. Attached to a + console, the child inherits that console and the receipt is printed; the + creation flags stay 0 and the streams are not redirected. Passing + CREATE_NO_WINDOW here would detach the child from the console and the + receipt would vanish while every write still reported success. + """ + captured = Captured() + emulate_windows_spawn(monkeypatch, entrypoint_module, console_attached=True) + assert _run_entrypoint_native_followup(monkeypatch, captured) == 0 + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == 0 + assert "stdout" not in captured.kwargs + assert "stderr" not in captured.kwargs + assert captured.kwargs.get("capture_output") is None + + +def test_entrypoint_windows_native_followup_is_suppressed_on_a_consoleless_host( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The same call from a host without a console still suppresses the window.""" + captured = Captured() + emulate_windows_spawn(monkeypatch, entrypoint_module, console_attached=False) + assert _run_entrypoint_native_followup(monkeypatch, captured) == 0 + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == WINDOWS_CREATE_NO_WINDOW + + +def test_consoleless_host_receipt_arrives_through_a_redirected_pipe( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """A redirected child keeps its receipt: the pipe, not a console, carries it.""" + captured = Captured() + monkeypatch.setattr(usage_ping, "_environment_suppressed", lambda *_a, **_k: False) + monkeypatch.setattr(usage_ping.shutil, "which", lambda _name: sys.executable) + emulate_windows_spawn(monkeypatch, usage_ping, console_attached=False) + monkeypatch.setattr(usage_ping.subprocess, "run", captured.record) + assert usage_ping.control("status", tmp_path / "usage-ping.json") == {"ok": True} + assert captured.kwargs is not None + assert captured.kwargs["creationflags"] == WINDOWS_CREATE_NO_WINDOW + assert captured.kwargs["capture_output"] is True