diff --git a/docs/development/lessons.md b/docs/development/lessons.md index ce375d13..02d65b52 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -35,6 +35,8 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Color profile follow-up:** [PR #287's P3 review](https://github.com/ThinkFlowLab/OpenDirector/pull/287#pullrequestreview-5870014881) found that a correct full-size PNG did not prove correct thumbnails: the library JPEG and the asset/history WebP used separate encoders that both omitted ICC. Check every displayed rendition and the actual embedded profile, not only dimensions or successful decoding. Preserve RGB profiles through resizing, but do not attach a non-RGB source profile after converting its channels to RGB. / **颜色配置补充:** 同一素材的全尺寸 PNG 正确,并不能证明素材库 JPEG 和资产/版本历史 WebP 正确。逐条检查显示路径的实际 ICC;缩放保留 RGB 配置,转换通道后不能继续附带非 RGB 源配置。 +- **Windows CLI follow-up:** In PR #323 validation, the Agent saved Unicode successfully, but PowerShell 5.1 shell readback failed when Python used the Windows code page. A saved-object comparison bypasses CLI stdout. Test write and readback in the actual Agent shell with Python UTF-8 mode disabled in the parent environment, and cover BOM-prefixed JSON files produced by PowerShell 5.1. / **Windows CLI 补充:** PR #323 验收中,Agent 正确保存了 Unicode,但 Python 使用 Windows 代码页时,PowerShell 5.1 中的读回失败。应在父进程关闭 Python UTF-8 模式,用真实 Agent Shell 验证写入和读回,并覆盖 PowerShell 5.1 生成的带 BOM JSON 文件。 + ## Baseline failures still need tracking - **Trigger:** A relevant test fails and comparison shows that it also fails on the baseline. diff --git a/packages/core/src/opendirector/agent/cli_transport.py b/packages/core/src/opendirector/agent/cli_transport.py index 1b13373b..20e94939 100644 --- a/packages/core/src/opendirector/agent/cli_transport.py +++ b/packages/core/src/opendirector/agent/cli_transport.py @@ -17,7 +17,7 @@ def environment(work, socket, bridge_env=None): cli_bin = work / '.opendirector-bin' cli_bin.mkdir(exist_ok=True) if os.name == 'nt': - (cli_bin / 'opendirector.cmd').write_text(f'@"{sys.executable}" -m opendirector.cli %*\n') + (cli_bin / 'opendirector.cmd').write_text(f'@"{sys.executable}" -X utf8 -m opendirector.cli %*\n') else: launcher = cli_bin / 'opendirector' launcher.write_text('#!/bin/sh\nexec ' + shlex.join([sys.executable, '-m', 'opendirector.cli']) + ' "$@"\n') diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index d2321b5b..0ad6bea4 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -13,7 +13,7 @@ from uuid import UUID from opendirector.agent.model_gateway import ModelGateway -from opendirector.agent import cli_transport, deepseek +from opendirector.agent import cli_transport, deepseek, windows_powershell from opendirector.agent.cli_discovery import cli_executable from opendirector.agent.context import RunContext from opendirector.agent.citations import search_sources @@ -239,6 +239,8 @@ async def stream(self, run: RunContext, gateway: ToolGateway): config['modelId'] if config else runtime_model, model_url, catalog, bridge_env=bridge_env, **({'native_directory': native_work} if runtime == 'opencode' else {}), **({'input_modalities': config.get('inputModalities', ['text'])} if run.runtime == 'default' else {})) + if runtime == 'opencode': + await windows_powershell.configure_opencode(args[0], native_work, env, Path(temporary)) if thinking != 'auto' and runtime == 'codex': args += ['-c', f'model_reasoning_effort={json.dumps(thinking)}'] elif thinking != 'auto' and runtime == 'claude': diff --git a/packages/core/src/opendirector/agent/windows_powershell.py b/packages/core/src/opendirector/agent/windows_powershell.py new file mode 100644 index 00000000..5ee92e38 --- /dev/null +++ b/packages/core/src/opendirector/agent/windows_powershell.py @@ -0,0 +1,116 @@ +#!python -I +"""Run OpenCode's Windows PowerShell command with UTF-8 native pipelines.""" + +import asyncio +from contextlib import suppress +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys + + +_COMMAND_ENV = 'OPENDIRECTOR_POWERSHELL_COMMAND' +_BOOTSTRAP = r""" +[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) +$OutputEncoding = [Console]::OutputEncoding +. (& { + $source = [Environment]::GetEnvironmentVariable('OPENDIRECTOR_POWERSHELL_COMMAND') + [Environment]::SetEnvironmentVariable('OPENDIRECTOR_POWERSHELL_COMMAND', $null) + # A dot-sourced script can hide the last native command's failure. Check + # inside the script so the shell still exits 1 (or honors an explicit exit). + [scriptblock]::Create($source + [Environment]::NewLine + 'if (-not $?) { exit 1 }') +}) +""" + + +def system_powershell(): + return Path(os.environ['SystemRoot']) / 'System32/WindowsPowerShell/v1.0/powershell.exe' + + +def _select_shell(configured, env): + # OpenCode checks its configured shell (or SHELL), then pwsh, then + # powershell. The remaining Git Bash/cmd fallbacks need no encoding setup. + path = env.get('PATH', '') + preferred = configured or env.get('SHELL') + if preferred and Path(preferred).stem.lower() not in {'nu', 'fish'}: + if Path(preferred).stem.lower() == 'bash': + # OpenCode resolves bare bash through Git for Windows before PATH. + return None + if executable := shutil.which(preferred, path=path): + return Path(executable) + if not shutil.which('pwsh', path=path): + if executable := shutil.which('powershell', path=path): + return Path(executable) + return None + + +async def configure_opencode(binary, cwd, env, directory): + if os.name != 'nt' or 'OPENCODE_CONFIG_CONTENT' not in env: + return + powershell = system_powershell() + if not powershell.is_file(): + return + + # Ask the same OpenCode binary to resolve its config before setting shell. + # This preserves explicit Git Bash/PowerShell 7 choices in user config. + try: + process = await asyncio.create_subprocess_exec( + binary, 'debug', 'config', '--pure', cwd=cwd, env=env, + stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW, + ) + except OSError: + return + try: + raw, _ = await asyncio.wait_for(process.communicate(), 10) + except TimeoutError: + return + finally: + if process.returncode is None: + with suppress(ProcessLookupError): + process.kill() + await process.wait() + + if process.returncode: + return + try: + config = json.loads(raw) + except ValueError: + return + selected = _select_shell(config.get('shell'), env) + if selected is None or selected.resolve() != powershell.resolve(): + return + + env['OPENCODE_CONFIG_CONTENT'] = json.dumps({ + **json.loads(env['OPENCODE_CONFIG_CONTENT']), + 'shell': str(make_launcher(directory)), + }) + + +def make_launcher(directory): + from distlib.scripts import ScriptMaker + + source = Path(__file__) + maker = ScriptMaker(str(source.parent), str(directory)) + maker.force = True + launcher = Path(maker.make(source.name)[0]) + # OpenCode uses the basename to select PowerShell arguments and parsing. + return launcher.replace(directory / 'powershell.exe') + + +def main(): + args = sys.argv[1:] + env = dict(os.environ) + if len(args) >= 2 and args[-2].lower() in {'-command', '-c'} and args[-1] != '-': + env[_COMMAND_ENV] = args[-1] + args[-1] = _BOOTSTRAP + return subprocess.call( + [str(system_powershell()), *args], env=env, creationflags=subprocess.CREATE_NO_WINDOW, + stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, + ) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index f0eb1886..5824189b 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -710,7 +710,11 @@ def query(ctx: typer.Context, kind: str, def read_file(path): - value = json.loads(sys.stdin.read() if str(path) == "-" else path.read_text(encoding="utf-8")) + if str(path) == "-": + source = sys.stdin.buffer.read().decode("utf-8-sig") + else: + source = path.read_text(encoding="utf-8-sig") + value = json.loads(source) if not isinstance(value, dict): raise ValueError("Expected a JSON object.") return value diff --git a/pyproject.toml b/pyproject.toml index c25fa211..8c48e5e9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [ "pydantic>=2.12,<3", "typer>=0.27.3,<0.28", "Pillow>=12,<14", "pillow-heif>=1.8.1,<2", "fonttools==4.68.0", "fastapi>=0.115,<1", "uvicorn>=0.30,<1", "starlette>=1.8,<2", "python-multipart>=0.0.33,<1", + "distlib>=0.4,<1; sys_platform == 'win32'", ] [project.optional-dependencies] diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 280491a3..ce771890 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -10,7 +10,7 @@ import threading import time from types import SimpleNamespace -from uuid import uuid4 +from uuid import UUID, uuid4 from fastapi.testclient import TestClient import httpx @@ -338,10 +338,11 @@ def real_opencode_worker(tmp_path, monkeypatch, request): pytest.skip('Set OPENDIRECTOR_REAL_CLI=1 to run the bundled CLI integration') if native.executable('default') is None: pytest.skip('Bundled OpenCode is not installed') + timeout = 105 if 'windows_unicode_pipeline' in request.node.name else 60 if os.environ.get('OPENDIRECTOR_REAL_CLI_WORKER') != '1': result = subprocess.run([sys.executable, '-m', 'pytest', request.node.nodeid, '-s', '-q'], env={**os.environ, 'OPENDIRECTOR_REAL_CLI_WORKER': '1'}, - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=90) + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace", timeout=timeout + 30) assert result.returncode == 0, result.stdout return False @@ -358,7 +359,7 @@ async def tracked_spawn(*args, **kwargs): await asyncio.Event().wait() return process monkeypatch.setattr(asyncio, 'create_subprocess_exec', tracked_spawn) - def timeout(): + def timed_out(): print('Real OpenCode integration timed out; thread stacks:', file=sys.stderr, flush=True) faulthandler.dump_traceback(file=sys.stderr, all_threads=True) for process, group in reversed(processes): @@ -371,7 +372,7 @@ def timeout(): except OSError as error: print(f'Could not stop CLI process {process.pid}: {error}', file=sys.stderr, flush=True) os._exit(1) - watchdog = threading.Timer(10 if os.environ.get('OPENDIRECTOR_TEST_CLI_STALL') else 60, timeout) + watchdog = threading.Timer(10 if os.environ.get('OPENDIRECTOR_TEST_CLI_STALL') else timeout, timed_out) watchdog.daemon = True watchdog.start() request.addfinalizer(watchdog.cancel) @@ -546,6 +547,178 @@ def model(request): assert ids[0] == ids[1] +@pytest.mark.skipif(os.name != 'nt' or os.environ.get('OPENDIRECTOR_REAL_WINDOWS_PIPELINE') != '1', + reason='Set OPENDIRECTOR_REAL_WINDOWS_PIPELINE=1 to qualify OpenCode on Windows PowerShell 5.1') +@pytest.mark.parametrize('runtime', ['default', 'opencode']) +def test_real_opencode_windows_unicode_pipeline(tmp_path, monkeypatch, real_opencode_worker, runtime, request): + if not real_opencode_worker: + return + from opendirector.agent.windows_powershell import system_powershell + from opendirector.infrastructure.creation_projects import CreationProjects + + monkeypatch.setenv('SHELL', str(system_powershell())) + monkeypatch.delenv('PSModulePath', raising=False) + monkeypatch.setenv('PSExecutionPolicyPreference', 'Restricted') + monkeypatch.setenv('PYTHONUTF8', '0') + monkeypatch.delenv('PYTHONIOENCODING', raising=False) + local = LocalProjects(tmp_path) + configs = ModelConfigs(tmp_path) + config = configs.save('agent', 'http://test.invalid/v1', 'test-model', 'server-only-key') + image = configs.save('image', 'http://test.invalid/v1', 'test-image', '', auth_mode='none') + prompts = ('第一镜:窗边的猫\n第二镜:𠮷 🐈? "推近"', '窗边的猫说:\'再来一次\'\n𠮷 🐈?') + expected_nodes = {} + expected_assets = {} + sessions = [] + tool_commands = [] + requests = [] + + def pipeline(payload, command): + body = json.dumps({'payload': payload}, ensure_ascii=False).replace("'", "''") + return f"'{body}' | opendirector {command} --file -" + + def model(request): + payload = json.loads(request.content) + if not payload.get('tools'): + return httpx.Response(200, headers={'content-type': 'text/event-stream'}, content=( + 'data: {"id":"title","choices":[{"index":0,"delta":{"content":"Storyboard"},"finish_reason":"stop"}]}\n\n' + 'data: [DONE]\n\n')) + messages = payload['messages'] + index = len(requests) + requests.append(messages) + if index % 2 == 0: + content = messages[-1]['content'] + assert 'Use opendirector for project changes.\n' in content + assert 'OutputEncoding' not in json.dumps(messages) + work = content.split('Execution directory: ', 1)[1].splitlines()[0] + command = tool_commands[index // 2] + delta = {'tool_calls': [{'index': 0, 'id': f'write-{index}', 'type': 'function', + 'function': {'name': 'bash', 'arguments': json.dumps({ + 'command': command, 'workdir': work, 'description': 'Save a Chinese storyboard'})}}]} + else: + delta = {'content': 'Saved.'} + chunk = {'id': f'completion-{index}', 'object': 'chat.completion.chunk', 'created': 1, 'model': 'test-model'} + frames = [dict(chunk, choices=[{'index': 0, 'delta': delta, 'finish_reason': None}]), + dict(chunk, choices=[{'index': 0, 'delta': {}, 'finish_reason': 'stop' if index % 2 else 'tool_calls'}])] + return httpx.Response(200, headers={'content-type': 'text/event-stream'}, + content=''.join(f'data: {json.dumps(frame)}\n\n' for frame in frames) + 'data: [DONE]\n\n') + + setup = ( + "$ErrorActionPreference = 'Stop'\n" + "if ($PSVersionTable.PSVersion.Major -ne 5 -or $PSVersionTable.PSVersion.Minor -ne 1) { throw 'Expected 5.1' }\n" + "if ($env:PSExecutionPolicyPreference -ne 'Restricted') { throw 'Expected Restricted' }\n" + "if ($env:PYTHONUTF8 -ne '0' -or (Test-Path Env:PYTHONIOENCODING)) { throw 'Expected legacy Python defaults' }\n" + "[IO.File]::WriteAllText((Join-Path $PWD.Path 'policy-probe.ps1'), 'exit 19')\n" + "try { & .\\policy-probe.ps1; throw 'Expected scripts to be blocked' } " + "catch [System.Management.Automation.PSSecurityException] {}\n" + "$launcher = (Get-Command opendirector).Source\n" + "if ($launcher -ne (Join-Path $PWD.Path '.opendirector-bin\\opendirector.cmd')) { throw 'Wrong launcher' }\n" + "Write-Output \"PS 5.1 Restricted $launcher\"\n" + "opendirector --help\n" + "if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\n" + "$ErrorActionPreference = 'Continue'\n" + "opendirector asset write-text --unknown-option 2>$null\n" + "if ($LASTEXITCODE -ne 2) { throw 'Wrong CLI exit code' }\n" + "$ErrorActionPreference = 'Stop'\n" + ) + if runtime == 'opencode': + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + if native.executable('opencode') is None: + pytest.skip('External OpenCode is not installed') + + class FixtureProvider(BaseHTTPRequestHandler): + def do_POST(self): + body = self.rfile.read(int(self.headers['Content-Length'])) + response = model(httpx.Request('POST', 'http://localhost/v1/chat/completions', content=body)) + self.send_response(response.status_code) + self.send_header('Content-Type', response.headers['content-type']) + self.send_header('Content-Length', str(len(response.content))) + self.end_headers() + self.wfile.write(response.content) + + server = ThreadingHTTPServer(('127.0.0.1', 0), FixtureProvider) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + + def stop_fixture(): + server.shutdown() + server.server_close() + thread.join() + + request.addfinalizer(stop_fixture) + settings = tmp_path / 'config' + monkeypatch.setenv('XDG_CONFIG_HOME', str(settings)) + opencode_config = settings / 'opencode' / 'opencode.json' + opencode_config.parent.mkdir(parents=True) + opencode_config.write_text(json.dumps({ + 'shell': str(system_powershell()), + 'small_model': 'fixture/test-model', + 'provider': {'fixture': {'npm': '@ai-sdk/openai-compatible', 'name': 'Test provider', + 'options': {'baseURL': f'http://127.0.0.1:{server.server_port}/v1', 'apiKey': 'test-key'}, + 'models': {'test-model': {'name': 'Test model'}}}}, + }), encoding='utf-8') + + provider = ChatCompletions(httpx.MockTransport(model)) + with TestClient(create_app(local, chat_provider=provider), headers={ + 'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': str(uuid4())}) as client: + path = project(client) + pid = path.rsplit('/', 1)[-1] + for index, prompt in enumerate(prompts): + spec_id, item_id = str(uuid4()), str(uuid4()) + title = f'窗边的小猫 🐈 {index + 1}' + name = f'分镜 {index + 1}.md' + node = { + 'spec': {'id': spec_id, 'projectId': pid, 'kind': 'image', 'purpose': 'generation', + 'modelConfigId': image['id'], 'prompt': prompt, 'parameters': {'size': '1024x1024'}}, + 'item': {'id': item_id, 'projectId': pid, 'kind': 'image', 'title': title, + 'position': {'x': 0, 'y': 0}, 'width': 512, 'height': 512, + 'binding': {'role': 'generation', 'objectRef': {'id': spec_id}}}, + } + expected_nodes[item_id] = (title, prompt) + expected_assets[name] = prompt.encode() + tool_commands.append( + ('using namespace System.Text\n' if index else '') + setup + + pipeline(node, 'canvas create-generation') + '\n' + + "if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\n" + + pipeline({'name': name, 'text': prompt}, 'asset write-text') + '\n' + + "if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\n" + + "Write-Output 'CLI project snapshot:'\n" + + 'opendirector project show') + turn = {'id': str(uuid4()), 'runtime': runtime, 'modelId': config['id'], + **({'runtimeModel': 'fixture/test-model'} if runtime == 'opencode' else {}), + 'text': f'保存第 {index + 1} 个分镜,暂时不用出图。'} + response = client.post(path + '/assistant/turns', json=turn) + events = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith('data: ')] + assert response.status_code == 200 and events[-1]['error'] is None, events + trace = next(local.root.rglob(f"{turn['id']}.opencode.jsonl")) + event, = [native_event for line in trace.read_text(encoding='utf-8').splitlines() + if (native_event := json.loads(line).get('native', {})).get('type') == 'tool_use'] + sessions.append(event['sessionID']) + shell_call = event['part'] + assert shell_call['state']['input']['command'] == tool_commands[index] + assert shell_call['state']['metadata']['exit'] == 0, shell_call + output = shell_call['state'].get('output', '') + assert 'PS 5.1 Restricted' in output and 'opendirector.cmd' in output and 'Usage:' in output, shell_call + assert output.count('"status": "applied"') == 2, shell_call + _, marker, raw_snapshot = output.partition('CLI project snapshot:') + assert marker, shell_call + reported = json.loads(raw_snapshot) + item = next(item for item in reported['canvasItems'] if item['id'] == item_id) + spec = next(spec for spec in reported['generationSpecs'] if spec['id'] == item['binding']['objectRef']['id']) + assert (item['title'], spec['prompt']) == (title, prompt) + + assert len(requests) == len(prompts) * 2 + assert len(set(sessions)) == 1 + snapshot = CreationProjects(LocalProjects(tmp_path)).snapshot(UUID(pid)) + prompts_by_id = {str(spec.id): spec.prompt for spec in snapshot.generationSpecs} + nodes = {str(item.id): (item.title, prompts_by_id[str(item.binding.objectRef.id)]) + for item in snapshot.canvasItems} + directory = next(local.root.rglob('project.json')).parent + assets = {asset.name: (directory / asset.path).read_bytes() for asset in snapshot.assets} + assert not snapshot.jobs + assert (nodes, assets) == (expected_nodes, expected_assets) + + def test_real_opencode_watchdog_cleans_up_stalled_cli(tmp_path): if os.environ.get('OPENDIRECTOR_REAL_CLI') != '1': pytest.skip('Set OPENDIRECTOR_REAL_CLI=1 to run the bundled CLI integration') diff --git a/tests/test_windows_powershell.py b/tests/test_windows_powershell.py new file mode 100644 index 00000000..2a6d15f1 --- /dev/null +++ b/tests/test_windows_powershell.py @@ -0,0 +1,112 @@ +import codecs +import os +from pathlib import Path +import subprocess +import time + +import pytest +from typer.testing import CliRunner + +from process_helpers import assert_process_exited + +from opendirector import cli +from opendirector.agent import windows_powershell + + +@pytest.mark.parametrize(('source', 'bom'), [ + ('stdin', b''), + ('stdin', codecs.BOM_UTF8), + ('file', b''), + ('file', codecs.BOM_UTF8), + pytest.param('powershell', codecs.BOM_UTF8, + marks=pytest.mark.skipif(os.name != 'nt', reason='Windows PowerShell test')), +]) +def test_json_input_is_utf8_with_optional_bom(tmp_path, monkeypatch, source, bom): + title = '窗边的小猫 𠮷🐈?' + data = '{"payload":{"text":"%s","name":"story.md"}}' % title + received = [] + + def execute(client, kind, payload, versions, preview): + received.append(payload) + return {'status': 'applied'} + + monkeypatch.setattr(cli.Client, 'execute', execute) + if source == 'stdin': + result = CliRunner().invoke(cli.app, ['asset', 'write-text', '--file', '-'], input=bom + data.encode()) + else: + path = tmp_path / 'command.json' + if source == 'powershell': + subprocess.run([str(windows_powershell.system_powershell()), '-NoProfile', + '-ExecutionPolicy', 'Restricted', '-Command', + f"Set-Content -Path command.json -Encoding UTF8 -Value '{data}'"], + cwd=tmp_path, capture_output=True, check=True, timeout=10) + assert path.read_bytes().startswith(bom) + else: + path.write_bytes(bom + data.encode()) + result = CliRunner().invoke(cli.app, ['asset', 'write-text', '--file', str(path)]) + assert result.exit_code == 0, result.exception + assert received == [{'text': title, 'name': 'story.md'}] + + +@pytest.mark.parametrize('source', ['stdin', 'file']) +def test_json_input_rejects_invalid_utf8_before_dispatch(tmp_path, monkeypatch, source): + def execute(*args): + pytest.fail('invalid input reached the project gateway') + + monkeypatch.setattr(cli.Client, 'execute', execute) + data = b'{"payload":{"name":"story.md","text":"\xff"}}' + if source == 'stdin': + result = CliRunner().invoke(cli.app, ['asset', 'write-text', '--file', '-'], input=data) + else: + path = tmp_path / 'command.json' + path.write_bytes(data) + result = CliRunner().invoke(cli.app, ['asset', 'write-text', '--file', str(path)]) + assert result.exit_code == 1 + assert isinstance(result.exception, UnicodeDecodeError) + + +@pytest.mark.skipif(os.name != 'nt', reason='Windows PowerShell test') +def test_powershell_launcher_preserves_command_semantics(tmp_path): + shell = windows_powershell.system_powershell() + wrapped = windows_powershell.make_launcher(tmp_path) + commands = [ + ('using namespace System.Text\n[Encoding]::UTF8.WebName', 0, b'utf-8'), + ('param([string]$x = "two words")\n$x', 0, b'two words'), + ("Write-Output ('猫' * 5000).Length", 0, b'5000'), + ('cmd /d /c exit 23', 1, b''), + ('exit 23', 23, b''), + ("cmd /d /c exit 23\n'He said \"hello\"' # trailing comment", 0, b'He said "hello"'), + ] + for engine in (shell, wrapped): + for script, code, output in commands: + result = subprocess.run([str(engine), '-NoProfile', '-ExecutionPolicy', 'Restricted', + '-Command', script], capture_output=True, timeout=10) + assert (result.returncode, result.stdout.strip()) == (code, output), result.stderr + + +@pytest.mark.skipif(os.name != 'nt', reason='Windows process tree test') +def test_powershell_launcher_cancel_kills_child(tmp_path): + wrapped = windows_powershell.make_launcher(tmp_path) + marker = tmp_path / 'shell.pid' + script = "[IO.File]::WriteAllText('shell.pid', [string]$PID); Start-Sleep 60" + proc = subprocess.Popen([str(wrapped), '-NoProfile', '-Command', script], cwd=tmp_path, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + deadline = time.monotonic() + 10 + while not marker.exists() and proc.poll() is None and time.monotonic() < deadline: + time.sleep(0.05) + pid = int(marker.read_text()) + finally: + if proc.poll() is None: + subprocess.run(['taskkill', '/pid', str(proc.pid), '/f', '/t'], check=True, capture_output=True) + proc.wait(timeout=10) + # taskkill can return before Windows has signaled every descendant handle. + deadline = time.monotonic() + 5 + while True: + try: + assert_process_exited(pid) + break + except AssertionError: + if time.monotonic() >= deadline: + raise + time.sleep(0.05)