diff --git a/.github/workflows/build-props-lib-tests.yml b/.github/workflows/build-props-lib-tests.yml index 1898a010a6..1f67065c74 100644 --- a/.github/workflows/build-props-lib-tests.yml +++ b/.github/workflows/build-props-lib-tests.yml @@ -1,6 +1,7 @@ # Headless tests for the repo's dependency on GitHub.Copilot.SDK's MSBuild # contract (tests/build_props/ci/CopilotSdkContract.Tests.ps1): the reviewed SDK -# version, and the CI-only CopilotSkipCliDownload default in Directory.Build.props. +# version, the CI-only CopilotSkipCliDownload default in Directory.Build.props, and +# the offline fallback in src/Reactor.Cli/CopilotRuntime.targets. # # This workflow exists because nothing else can catch that contract breaking. The # ordinary matrix runs with the native CLI download already skipped, so it stays @@ -19,6 +20,8 @@ on: # A GitHub.Copilot.SDK version bump can change or drop the MSBuild contract # Directory.Build.props depends on, and no other job would notice. - 'Directory.Packages.props' + - 'src/Reactor.Cli/CopilotRuntime.targets' + - 'src/Reactor.Cli/Reactor.Cli.csproj' - 'tests/build_props/ci/**' - '.github/workflows/build-props-lib-tests.yml' pull_request: @@ -27,6 +30,8 @@ on: # A GitHub.Copilot.SDK version bump can change or drop the MSBuild contract # Directory.Build.props depends on, and no other job would notice. - 'Directory.Packages.props' + - 'src/Reactor.Cli/CopilotRuntime.targets' + - 'src/Reactor.Cli/Reactor.Cli.csproj' - 'tests/build_props/ci/**' - '.github/workflows/build-props-lib-tests.yml' diff --git a/CHANGELOG.md b/CHANGELOG.md index f0418794eb..b7eea025fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -297,6 +297,15 @@ Conventions for contributors: ### Fixed +- `mur` builds from source without network access. When the Copilot runtime download + fails, the build skips it with warning `REACTORCLI001` instead of failing with `MSB3923`. + `mur loc translate` no longer needs the bundled runtime either, which the release builds + of `mur` never included: it uses the full path in `COPILOT_CLI_PATH` or a Copilot CLI + installed with `winget install GitHub.Copilot`. If it has no runtime, or the runtime + fails to start, it reports that once with how to fix it, instead of failing every batch. + `COPILOT_CLI_PATH` must now be a full path. `mur doctor` shows which runtime the command + uses (issue #1133). + - A pooled `TextBlock`, `Border`, `Grid`, `StackPanel`, `Image` or other non-Button control no longer keeps the previous renter's `.WithFlyout(...)` flyout. On any control, including a `Button`, dropping `.WithFlyout(...)` on an update now removes the flyout instead of leaving it @@ -306,6 +315,7 @@ Conventions for contributors: `.WithFlyout(element)`, with no code fix (`REACTOR_MOD_002` on a control the pool doesn't recycle). Builds using `TreatWarningsAsErrors` may need to move those writes to `.WithFlyout(...)` (issue #1753). + - `bootstrap.ps1` preserves the downloaded Copilot runtime's dot-files when packing `mur`, instead of failing Release packaging with NU5119 (issue #1507). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f12252b3d5..ef109ec476 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -103,7 +103,9 @@ Keep credentials in your user NuGet config. The script never writes them to the - Point the download at a mirror of the release files with the `CopilotCliReleaseBaseUrl` MSBuild property or the `COPILOT_CLI_DOWNLOAD_BASE_URL` environment variable. - Use a binary you downloaded yourself with `CopilotCliBinaryPath`. -`CopilotSkipCliDownload=true` also gets the build going, but only to compile. It leaves out the native binary, and `mur loc translate` and the two Copilot SDK samples need that binary at run time. CI sets it because CI never runs those paths. +`src/Reactor.Cli` doesn't need either one to build. If it can't download the runtime, it skips it with warning `REACTORCLI001` (the `MSB3923` warning before it gives the reason) and builds anyway. All of `mur` works; `mur loc translate` then uses the full path in `COPILOT_CLI_PATH` or a Copilot CLI you install with `winget install GitHub.Copilot`, and `mur doctor` shows which one. Pass `-p:CopilotSkipCliDownload=false` to make a failed download an error again. `CopilotRuntimeProbeTimeoutSeconds` (default 30) bounds the check. + +`CopilotSkipCliDownload=true` also gets the build going, but only to compile. It leaves out the native binary, so `mur loc translate` falls back the same way, and the two Copilot SDK samples need that binary or their own fallback at run time. CI sets it because CI never runs those paths. ### After `git pull` diff --git a/Directory.Build.props b/Directory.Build.props index 6562269f87..d9a40ce566 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -149,18 +149,24 @@ src/Reactor.Cli `mur loc translate` constructs CopilotTranslationProvider (TranslateCommand.cs), - which does `new CopilotClient()` and StartAsync() - against the native binary. + which starts a CopilotClient against the native + binary. samples/apps/widget-creator generation pipeline samples/apps/demo-script-tool generation pipeline - Skipping the download locally therefore makes `mur loc translate` and both samples - fail at run time, with an error that points at the missing binary rather than at the - property that removed it. When the download itself is what is failing, redirect it - instead with the SDK's CopilotCliReleaseBaseUrl property (or the + Without the binary, `mur loc translate` falls back to COPILOT_CLI_PATH or an installed + Copilot CLI and otherwise fails with a message that says how to fix it + (Loc/CopilotRuntimeLocator.cs, issue #1133). widget-creator has a similar run-time + fallback; demo-script-tool has none, so skipping the download locally makes it fail at + run time with an error that points at the missing binary rather than at the property + that removed it. When the download itself is what is failing, + redirect it instead with the SDK's CopilotCliReleaseBaseUrl property (or the COPILOT_CLI_DOWNLOAD_BASE_URL environment variable), or point CopilotCliBinaryPath at a pre-downloaded binary. Anyone can still override CopilotSkipCliDownload explicitly when they genuinely only need a compile. + + src/Reactor.Cli builds even without that: src/Reactor.Cli/CopilotRuntime.targets skips + the download with warning REACTORCLI001 when the release host is unreachable. --> true diff --git a/bootstrap.ps1 b/bootstrap.ps1 index e42e3b533e..477f1bb9d5 100644 --- a/bootstrap.ps1 +++ b/bootstrap.ps1 @@ -540,6 +540,20 @@ Invoke-ReactorWithRestoreEnvironment ` if ($cliPackExit -ne 0) { Fail 'dotnet pack failed for Reactor.Cli' } Write-Ok "Packed Microsoft.UI.Reactor.Cli -> $feed" +# When the Copilot runtime download fails, the pack still succeeds with warning +# REACTORCLI001 (issue #1133). Say so here, where it can't scroll past unnoticed. +$cliPackage = Join-Path $feed "Microsoft.UI.Reactor.Cli.$cliLocalVersion.nupkg" +if (Test-Path -LiteralPath $cliPackage) { + Add-Type -AssemblyName System.IO.Compression.FileSystem + $zip = [IO.Compression.ZipFile]::OpenRead($cliPackage) + try { $hasRuntime = [bool]($zip.Entries.FullName -match '/runtimes/[^/]+/native/copilot\.exe$') } finally { $zip.Dispose() } + if (-not $hasRuntime) { + Write-Host ' [warn] mur was packed without the Copilot runtime (see REACTORCLI001 above).' -ForegroundColor Yellow + Write-Host ' `mur loc translate` will use COPILOT_CLI_PATH or an installed Copilot CLI' -ForegroundColor Yellow + Write-Host ' (winget install GitHub.Copilot); rerun bootstrap with network access to bundle it.' -ForegroundColor Yellow + } +} + # --------------------------------------------------------------------------- # 3. Install / update the global tool # --------------------------------------------------------------------------- diff --git a/docs/_pipeline/templates/mur-cli.md.dt b/docs/_pipeline/templates/mur-cli.md.dt index d77b858b3b..2ef5849979 100644 --- a/docs/_pipeline/templates/mur-cli.md.dt +++ b/docs/_pipeline/templates/mur-cli.md.dt @@ -144,6 +144,18 @@ You can also set it with the `COPILOT_MODEL` environment variable. Each translation is marked as an AI draft that needs review. See [Localization](localization.md) for the full workflow. +`mur loc translate` also needs the Copilot runtime. The `mur` in the release +skill kit doesn't include it, and neither does a `mur` you build from source +without network access. For those, install the Copilot CLI with +`winget install GitHub.Copilot`. The command looks for a runtime in this order: + +1. The full path in `COPILOT_CLI_PATH`, if that variable is set. +2. The runtime bundled with `mur`. +3. A Copilot CLI installed with WinGet or by the GitHub CLI. + +An installed CLI must be a version that works with the runtime `mur` was built +for. `mur doctor` shows which runtime the command uses. + ## Help for AI agents | Command | What it does | @@ -166,7 +178,7 @@ with an error when you run them anywhere else. | `mur pack-local` | Pack the framework from your working tree into `/local-nupkgs/`. Options: `--version` (default `0.0.0-local`), `--configuration` (default `Debug`). | | `mur clean-local` | Remove the local packages, their NuGet cache entries, and old local templates. | | `mur upgrade` | After `git pull`: pack the framework again, install the template pack if it is missing, and refresh the agent plugin and the Visual Studio extension. Options: `--skip-plugin`, `--skip-vs-extension`. | -| `mur doctor` | Check the .NET SDK, `mur`, the local packages, the template pack, and the agent plugin. Add `--verbose` for more detail. | +| `mur doctor` | Check the .NET SDK, `mur`, the local packages, the template pack, the Copilot runtime that `mur loc translate` uses, and the agent plugin. Add `--verbose` for more detail. | `mur upgrade` does not update `mur` itself, because a running program can't replace its own file. Run `./bootstrap.ps1` again for that. diff --git a/docs/guide/mur-cli.md b/docs/guide/mur-cli.md index 5bdff0455a..c915511e75 100644 --- a/docs/guide/mur-cli.md +++ b/docs/guide/mur-cli.md @@ -134,6 +134,18 @@ You can also set it with the `COPILOT_MODEL` environment variable. Each translation is marked as an AI draft that needs review. See [Localization](localization.md) for the full workflow. +`mur loc translate` also needs the Copilot runtime. The `mur` in the release +skill kit doesn't include it, and neither does a `mur` you build from source +without network access. For those, install the Copilot CLI with +`winget install GitHub.Copilot`. The command looks for a runtime in this order: + +1. The full path in `COPILOT_CLI_PATH`, if that variable is set. +2. The runtime bundled with `mur`. +3. A Copilot CLI installed with WinGet or by the GitHub CLI. + +An installed CLI must be a version that works with the runtime `mur` was built +for. `mur doctor` shows which runtime the command uses. + ## Help for AI agents | Command | What it does | @@ -156,7 +168,7 @@ with an error when you run them anywhere else. | `mur pack-local` | Pack the framework from your working tree into `/local-nupkgs/`. Options: `--version` (default `0.0.0-local`), `--configuration` (default `Debug`). | | `mur clean-local` | Remove the local packages, their NuGet cache entries, and old local templates. | | `mur upgrade` | After `git pull`: pack the framework again, install the template pack if it is missing, and refresh the agent plugin and the Visual Studio extension. Options: `--skip-plugin`, `--skip-vs-extension`. | -| `mur doctor` | Check the .NET SDK, `mur`, the local packages, the template pack, and the agent plugin. Add `--verbose` for more detail. | +| `mur doctor` | Check the .NET SDK, `mur`, the local packages, the template pack, the Copilot runtime that `mur loc translate` uses, and the agent plugin. Add `--verbose` for more detail. | `mur upgrade` does not update `mur` itself, because a running program can't replace its own file. Run `./bootstrap.ps1` again for that. diff --git a/samples/apps/widget-creator/Services/CopilotSdkClient.cs b/samples/apps/widget-creator/Services/CopilotSdkClient.cs index 94fa6f0c0c..2053eb1f6b 100644 --- a/samples/apps/widget-creator/Services/CopilotSdkClient.cs +++ b/samples/apps/widget-creator/Services/CopilotSdkClient.cs @@ -50,11 +50,11 @@ async Task GetClientAsync(CancellationToken ct) { if (_client is not null) return _client; var options = new CopilotClientOptions(); - // The SDK's default stdio transport looks ONLY for a CLI bundled next to - // the app (runtimes//native/copilot.exe) and does not consult - // COPILOT_CLI_PATH. When the app was built without a bundled CLI (e.g. - // CopilotSkipCliDownload=true on a restricted network), resolve one at - // run time and pass it explicitly so generation still works. + // Without an explicit path the SDK uses COPILOT_CLI_PATH, then the CLI bundled next + // to the app (runtimes//native). When the app was built without a bundled CLI (e.g. + // CopilotSkipCliDownload=true on a restricted network), resolve one at run time and + // pass it explicitly so generation still works. src/Reactor.Cli/Loc/CopilotRuntimeLocator.cs + // has its own copy of the install locations; keep the two in step. var cliPath = ResolveCliPath(); if (cliPath is not null) { diff --git a/src/Reactor.Cli/CopilotRuntime.targets b/src/Reactor.Cli/CopilotRuntime.targets new file mode 100644 index 0000000000..36304797d6 --- /dev/null +++ b/src/Reactor.Cli/CopilotRuntime.targets @@ -0,0 +1,91 @@ + + + + 30 + + + + + + <_ReactorCopilotCacheDir>$(IntermediateOutputPath)copilot-cli\$(CopilotCliVersion)\$(_CopilotPlatform) + <_ReactorCopilotCached Condition="Exists('$(_ReactorCopilotCacheDir)\prebuilds\$(_CopilotPlatform)\$(_CopilotRuntimeWrapper)') And Exists('$(_ReactorCopilotCacheDir)\prebuilds\$(_CopilotPlatform)\runtime.node') And Exists('$(_ReactorCopilotCacheDir)\.copilot-runtime-complete')">true + <_ReactorCopilotProbeDir>$(IntermediateOutputPath)copilot-cli-probe + <_ReactorCopilotUnstable>$([System.Text.RegularExpressions.Regex]::IsMatch('$(CopilotCliVersion)', '^(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}(?:-unstable|-(?:0|[1-9][0-9]*)\.unstable)\.r[1-9][0-9]*\.g[0-9a-f]{7}$')) + <_ReactorCopilotReleaseTag>v$(CopilotCliVersion) + <_ReactorCopilotReleaseTag Condition="'$(_ReactorCopilotUnstable)' == 'true'">runtime-$(CopilotCliVersion) + <_ReactorCopilotMirrorSet Condition="'$(CopilotCliReleaseBaseUrl)' != ''">true + <_ReactorCopilotReleaseBase>$(CopilotCliReleaseBaseUrl) + <_ReactorCopilotReleaseBase Condition="'$(_ReactorCopilotReleaseBase)' == '' And '$(_ReactorCopilotUnstable)' == 'true'">https://github.com/github/copilot-sdk/releases/download + <_ReactorCopilotReleaseBase Condition="'$(_ReactorCopilotReleaseBase)' == ''">https://github.com/github/copilot-cli/releases/download + <_ReactorCopilotNormalizedBase>$([System.String]::Copy('$(_ReactorCopilotReleaseBase)').TrimEnd('/')) + <_ReactorCopilotProbeUrl>$(_ReactorCopilotNormalizedBase)/$(_ReactorCopilotReleaseTag)/SHA256SUMS.txt + <_ReactorCopilotProbeTimeoutMs>$([System.Convert]::ToInt32($([MSBuild]::Multiply($(CopilotRuntimeProbeTimeoutSeconds), 1000)))) + <_ReactorCopilotProbeResult>cached + + + + + + <_ReactorCopilotProbeResult>$(MSBuildLastTaskResult) + <_ReactorCopilotAssetName>github-copilot-$(CopilotCliVersion)-$(_CopilotPlatform).tgz + <_ReactorCopilotAssetNameRegex>$([System.Text.RegularExpressions.Regex]::Escape('$(_ReactorCopilotAssetName)')) + + + + + + + <_ReactorCopilotChecksumMatch Include="@(_ReactorCopilotChecksumLine)" + Condition="$([System.Text.RegularExpressions.Regex]::IsMatch('%(Identity)', '^[0-9a-fA-F]{64}[\t ]+\*?$(_ReactorCopilotAssetNameRegex)[\t ]*$'))" /> + + + <_ReactorCopilotProbeResult>false + <_ReactorCopilotProbeFailure>'$(_ReactorCopilotProbeUrl)' does not list exactly one checksum for $(_ReactorCopilotAssetName) + + + + + true + <_ReactorCopilotProbeFailure Condition="'$(_ReactorCopilotProbeFailure)' == ''">Could not download '$(_ReactorCopilotProbeUrl)' (the MSB3923 warning above says why) + <_ReactorCopilotProbeAdvice>To bundle it, rebuild with network access, point CopilotCliReleaseBaseUrl at a mirror, or set CopilotCliBinaryPath to a downloaded binary. + <_ReactorCopilotProbeAdvice Condition="'$(_ReactorCopilotMirrorSet)' == 'true'">To bundle it, check the CopilotCliReleaseBaseUrl (or COPILOT_CLI_DOWNLOAD_BASE_URL) mirror, or set CopilotCliBinaryPath to a downloaded binary. + + + + \ No newline at end of file diff --git a/src/Reactor.Cli/Doctor/DoctorCommand.cs b/src/Reactor.Cli/Doctor/DoctorCommand.cs index e9752445fb..6148efb8ce 100644 --- a/src/Reactor.Cli/Doctor/DoctorCommand.cs +++ b/src/Reactor.Cli/Doctor/DoctorCommand.cs @@ -19,7 +19,9 @@ // 6. The Windows App SDK `dotnet new` template pack is registered, which is // what provides `dotnet new reactor` (always runs — does not depend on // the repo checkout being found) -// 7. Claude plugin at ~/.claude/plugins/reactor (informational only; not +// 7. The Copilot runtime `mur loc translate` will use (warn-only — release +// builds of mur don't bundle it, and it falls back to an installed CLI) +// 8. Claude plugin at ~/.claude/plugins/reactor (informational only; not // every developer uses Claude Code) using System.Diagnostics; @@ -176,7 +178,22 @@ public static int Run(string[] args) } } - // 5. Claude plugin (informational only — many devs don't use it) + // 5. Copilot runtime for `mur loc translate`. Release builds of mur (and ones built + // offline) have none bundled, and only that command needs one — so this is a + // warning, never a failure (issue #1133). + var (runtimeOk, runtimeDetail) = TranslateRuntimeCheck( + Loc.CopilotRuntimeLocator.Resolve(), Loc.CopilotRuntimeLocator.ExpectedVersion); + if (runtimeOk) + { + Pass("loc translate runtime", runtimeDetail); + } + else + { + Warn("loc translate runtime", runtimeDetail); + warnings++; + } + + // 6. Claude plugin (informational only — many devs don't use it) var claudePluginDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude", "plugins", "reactor"); @@ -208,6 +225,22 @@ public static int Run(string[] args) return 0; } + /// The loc translate runtime line: PASS with where the runtime comes from, or WARN with a fix. + internal static (bool Ok, string Detail) TranslateRuntimeCheck(Loc.CopilotRuntimeResolution runtime, string? expectedVersion) + { + var variable = Loc.CopilotRuntimeLocator.EnvironmentVariable; + if (runtime.Source == Loc.CopilotRuntimeSource.Missing) + { + return (false, runtime.Problem is not null + ? $"{runtime.Problem} `mur loc translate` will not run; set it to the full path of a copilot.exe, or unset it." + : "no Copilot runtime bundled with mur and no Copilot CLI installed, so `mur loc translate` will not run. " + + $"Install one with `winget install GitHub.Copilot`, or set {variable} to the full path of a copilot.exe."); + } + return (true, runtime.Source == Loc.CopilotRuntimeSource.Bundled || expectedVersion is null + ? runtime.Describe() + : $"{runtime.Describe()}; this mur was built for Copilot runtime {expectedVersion}"); + } + // ----------------------------------------------------------------------- // Output formatting // ----------------------------------------------------------------------- diff --git a/src/Reactor.Cli/Loc/CopilotRuntimeLocator.cs b/src/Reactor.Cli/Loc/CopilotRuntimeLocator.cs new file mode 100644 index 0000000000..17ab7e18d5 --- /dev/null +++ b/src/Reactor.Cli/Loc/CopilotRuntimeLocator.cs @@ -0,0 +1,205 @@ +using System.Runtime.InteropServices; + +namespace Microsoft.UI.Reactor.Cli.Loc; + +/// Where found the Copilot runtime. +internal enum CopilotRuntimeSource +{ + /// Bundled next to mur by GitHub.Copilot.SDK at build time. + Bundled, + /// The COPILOT_CLI_PATH environment variable. + Environment, + /// A standalone Copilot CLI in one of its fixed install locations. + Installed, + /// Nothing usable was found. + Missing, +} + +/// Where the runtime came from. +/// The bundled runtime folder, or the CLI to launch; null when missing. +/// Every location that was checked, for the missing-runtime diagnostic. +/// Why an explicit COPILOT_CLI_PATH could not be used, if it could not. +internal sealed record CopilotRuntimeResolution( + CopilotRuntimeSource Source, + string? Path, + IReadOnlyList Searched, + string? Problem = null) +{ + /// The CLI to pass to the SDK explicitly, or null to let it use the bundled runtime. + public string? ExplicitCliPath => Source is CopilotRuntimeSource.Environment or CopilotRuntimeSource.Installed ? Path : null; + + public string Describe() => Source switch + { + CopilotRuntimeSource.Bundled => $"bundled with mur ({Path})", + CopilotRuntimeSource.Environment => $"{CopilotRuntimeLocator.EnvironmentVariable} ({Path})", + CopilotRuntimeSource.Installed => $"installed Copilot CLI ({Path})", + _ => "not found", + }; +} + +/// +/// Finds the Copilot runtime that mur loc translate runs on (issue #1133). +/// +/// +/// +/// A mur built without network access, or with CopilotSkipCliDownload=true (as the +/// release pipelines do), has no runtime bundled under runtimes/<rid>/native. The SDK +/// then fails every request with "Copilot runtime wrapper not found". Resolving the runtime once, +/// up front, lets mur fall back to an installed Copilot CLI or fail with one actionable message. +/// +/// +/// Order: COPILOT_CLI_PATH (which the SDK itself also prefers over the bundled runtime), the +/// bundled runtime, then a standalone Copilot CLI in its fixed install locations. PATH is +/// never searched, so an unrelated copilot.exe earlier on PATH cannot be launched. +/// +/// +/// samples/apps/widget-creator/Services/CopilotSdkClient.cs has its own copy of the install +/// locations; keep the two in step when the SDK's layout or the Copilot CLI's install paths change. +/// +/// +internal static class CopilotRuntimeLocator +{ + public const string EnvironmentVariable = "COPILOT_CLI_PATH"; + + // GitHub.Copilot.SDK's bundled layout (GetBundledRuntimeLaunch in the SDK's Client.cs). + private const string RuntimeWrapper = "copilot-runtime.exe"; + private const string RuntimeNode = "runtime.node"; + private const string ExplicitCliMarker = ".copilot-explicit-cli"; + private const string CliBinary = "copilot.exe"; + + public static CopilotRuntimeResolution Resolve() => Resolve( + AppContext.BaseDirectory, + System.Environment.GetEnvironmentVariable(EnvironmentVariable), + // The SDK's GetPortableRid picks the bundled folder from the OS architecture, not the + // process's, so an x64 mur under emulation on ARM64 still looks in win-arm64. + RuntimeInformation.OSArchitecture, + System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), + System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles), + File.Exists); + + internal static CopilotRuntimeResolution Resolve( + string baseDirectory, + string? environmentPath, + Architecture osArchitecture, + string? localAppData, + string? programFiles, + Func fileExists) + { + // An explicit COPILOT_CLI_PATH is the user's choice, so a wrong one is reported + // rather than silently replaced by whatever else happens to be installed. Only an + // empty value counts as unset, as in the SDK, which would otherwise launch it as-is. + if (!string.IsNullOrEmpty(environmentPath)) + { + var path = environmentPath.Trim(); + string? problem = null; + if (path.Length == 0) + problem = $"{EnvironmentVariable} is set but blank."; + // A relative value would resolve against the project being localized, so a + // copilot.exe checked into that project could be launched. + else if (!System.IO.Path.IsPathFullyQualified(path)) + problem = $"{EnvironmentVariable} is set to '{path}', which is not a full path."; + else if (!fileExists(path)) + problem = $"{EnvironmentVariable} is set to '{path}', which does not exist."; + + return problem is null + ? new(CopilotRuntimeSource.Environment, path, [path]) + : new(CopilotRuntimeSource.Missing, null, [path], problem); + } + + var searched = new List(); + var rid = osArchitecture == Architecture.Arm64 ? "win-arm64" : "win-x64"; + var native = System.IO.Path.Join(baseDirectory, "runtimes", rid, "native"); + searched.Add(native); + var hasWrapper = fileExists(System.IO.Path.Join(native, RuntimeWrapper)); + var hasRuntimeNode = fileExists(System.IO.Path.Join(native, RuntimeNode)); + // The SDK launches the marked explicit CLI only when neither runtime-pair file exists; + // with just one of them it fails on the incomplete pair instead. + var hasExplicitCli = !hasWrapper && !hasRuntimeNode + && fileExists(System.IO.Path.Join(native, ExplicitCliMarker)) + && fileExists(System.IO.Path.Join(native, CliBinary)); + if ((hasWrapper && hasRuntimeNode) || hasExplicitCli) + return new(CopilotRuntimeSource.Bundled, native, searched); + + foreach (var candidate in InstalledCliPaths(localAppData, programFiles)) + { + searched.Add(candidate); + if (fileExists(candidate)) + return new(CopilotRuntimeSource.Installed, candidate, searched); + } + + return new(CopilotRuntimeSource.Missing, null, searched); + } + + /// + /// The standalone Copilot CLI's fixed install locations: the gh-managed copy, then the + /// WinGet GitHub.Copilot command links (user scope, then machine scope). + /// + internal static IEnumerable InstalledCliPaths(string? localAppData, string? programFiles) + { + if (!string.IsNullOrEmpty(localAppData)) + { + yield return System.IO.Path.Join(localAppData, "GitHub CLI", "copilot", CliBinary); + yield return System.IO.Path.Join(localAppData, "Microsoft", "WinGet", "Links", CliBinary); + } + if (!string.IsNullOrEmpty(programFiles)) + yield return System.IO.Path.Join(programFiles, "WinGet", "Links", CliBinary); + } + + /// The message printed when the runtime was found but would not start. + public static string FormatStartFailure(CopilotRuntimeResolution resolution, Exception error, string? expectedVersion) + { + var lines = new List + { + $"Error: could not start the Copilot runtime ({resolution.Describe()}): {error.Message}", + }; + var version = expectedVersion is null ? "" : $" {expectedVersion}"; + switch (resolution.Source) + { + case CopilotRuntimeSource.Environment: + lines.Add($" This mur was built for Copilot runtime{version}, and a Copilot CLI of another"); + lines.Add($" version may not be compatible. Point {EnvironmentVariable} at a Copilot CLI{version},"); + lines.Add(" or unset it to use the runtime bundled with mur or an installed Copilot CLI."); + break; + case CopilotRuntimeSource.Installed: + lines.Add($" This mur was built for Copilot runtime{version}, and a Copilot CLI of another"); + lines.Add($" version may not be compatible. Set {EnvironmentVariable} to the full path of a"); + lines.Add($" Copilot CLI{version}. If you build mur from source, rebuilding it with network"); + lines.Add(" access bundles the matching runtime."); + break; + } + return string.Join(System.Environment.NewLine, lines); + } + + /// The Copilot runtime version this mur was built against, if recorded. + public static string? ExpectedVersion => + typeof(CopilotRuntimeLocator).Assembly + .GetCustomAttributes(typeof(System.Reflection.AssemblyMetadataAttribute), inherit: false) + .Cast() + .FirstOrDefault(a => a.Key == "CopilotCliVersion")?.Value; + + /// The one message mur loc translate prints when it has no runtime to run on. + public static string FormatMissing(CopilotRuntimeResolution resolution) + { + var lines = new List + { + "Error: mur loc translate needs the GitHub Copilot runtime, and none was found.", + }; + if (resolution.Problem is not null) + { + lines.Add($" {resolution.Problem}"); + lines.Add($" Set {EnvironmentVariable} to the full path of a copilot.exe, or unset it to use the"); + lines.Add(" runtime bundled with mur or an installed Copilot CLI."); + } + else + { + lines.Add(" Release builds of mur don't bundle it, and neither does a mur built from source"); + lines.Add(" without network access. Fix it with one of:"); + lines.Add(" - Install the GitHub Copilot CLI: winget install GitHub.Copilot"); + lines.Add($" - Set {EnvironmentVariable} to the full path of a copilot.exe"); + lines.Add(" - If you build mur from source, rebuild it with network access to bundle the runtime"); + } + lines.Add(" Looked in:"); + lines.AddRange(resolution.Searched.Select(p => $" {p}")); + return string.Join(System.Environment.NewLine, lines); + } +} diff --git a/src/Reactor.Cli/Loc/CopilotTranslationProvider.cs b/src/Reactor.Cli/Loc/CopilotTranslationProvider.cs index 2c5fc3db91..1a0cf8e6bc 100644 --- a/src/Reactor.Cli/Loc/CopilotTranslationProvider.cs +++ b/src/Reactor.Cli/Loc/CopilotTranslationProvider.cs @@ -3,6 +3,12 @@ namespace Microsoft.UI.Reactor.Cli.Loc; +/// +/// The Copilot runtime could not be started. Every batch would fail the same way, so +/// reports it once and stops. +/// +internal sealed class CopilotRuntimeStartException(Exception inner) : Exception(inner.Message, inner); + /// /// Translates strings using the GitHub Copilot SDK, which routes through the user's /// authenticated GitHub Copilot subscription. Requires the GitHub CLI (`gh`) to be @@ -13,9 +19,16 @@ internal sealed class CopilotTranslationProvider : ITranslationProvider public string Name => "GitHub Copilot"; private readonly string _model; + private readonly string? _cliPath; - public CopilotTranslationProvider(string? model = null) + /// The model to request; defaults to COPILOT_MODEL, then gpt-5.4-mini. + /// + /// A Copilot CLI to launch instead of the runtime bundled with mur + /// (); null uses the bundled one. + /// + public CopilotTranslationProvider(string? model = null, string? cliPath = null) { + _cliPath = cliPath; // Default model: gpt-5.4-mini — a fast, low-cost model well-suited to // straightforward string translation (gpt-4o is no longer offered by the // Copilot runtime → session.create fails). Override via --model or COPILOT_MODEL. @@ -30,8 +43,19 @@ public async Task TranslateAsync(TranslationBatch batch, Canc var userMessage = TranslationPrompt.BuildUserMessage(batch); var fullPrompt = $"{systemPrompt}\n\n{userMessage}"; - await using var client = new CopilotClient(); - await client.StartAsync(); + var options = new CopilotClientOptions(); + if (_cliPath is not null) + options.Connection = RuntimeConnection.ForStdio(path: _cliPath); + + await using var client = new CopilotClient(options); + try + { + await client.StartAsync(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + throw new CopilotRuntimeStartException(ex); + } await using var session = await client.CreateSessionAsync(new SessionConfig { diff --git a/src/Reactor.Cli/Loc/TranslateCommand.cs b/src/Reactor.Cli/Loc/TranslateCommand.cs index 95434cd1d6..cff1863a44 100644 --- a/src/Reactor.Cli/Loc/TranslateCommand.cs +++ b/src/Reactor.Cli/Loc/TranslateCommand.cs @@ -10,7 +10,12 @@ internal static class TranslateCommand { private const int BatchSize = 25; - public static int Run(string[] args) + public static int Run(string[] args) => Run(args, CopilotRuntimeLocator.Resolve); + + internal static int Run( + string[] args, + Func resolveRuntime, + Func? createProvider = null) { string? sourcePath = null; string? targetLocales = null; @@ -77,23 +82,44 @@ public static int Run(string[] args) var sourceLocale = Path.GetFileName(sourcePath); var stringsDir = Path.GetDirectoryName(sourcePath)!; - ITranslationProvider provider = new CopilotTranslationProvider(model); - Console.WriteLine($"Using provider: {provider.Name}"); + createProvider ??= (model, cliPath) => new CopilotTranslationProvider(model, cliPath); // Run async translation - return RunAsync(provider, sourceFiles, sourceLocale, targets, stringsDir, missingOnly) + return RunAsync( + resolveRuntime, + runtime => createProvider(model, runtime.ExplicitCliPath), + sourceFiles, sourceLocale, targets, stringsDir, missingOnly) .GetAwaiter().GetResult(); } - private static async Task RunAsync( + internal static Task RunAsync( ITranslationProvider provider, List sourceFiles, string sourceLocale, string[] targets, string stringsDir, + bool missingOnly, + CopilotRuntimeResolution runtime) => + RunAsync(() => runtime, _ => provider, sourceFiles, sourceLocale, targets, stringsDir, missingOnly); + + internal static async Task RunAsync( + Func resolveRuntime, + Func createProvider, + List sourceFiles, + string sourceLocale, + string[] targets, + string stringsDir, bool missingOnly) { + // Resolved at the first batch that needs translating, so a run with nothing to + // translate succeeds without a runtime, and a missing one is reported once rather + // than as the same SDK error for every batch. + CopilotRuntimeResolution? runtime = null; + ITranslationProvider? provider = null; int totalTranslated = 0; + // Once a batch has run, the runtime is known to start, so a later start failure is + // a one-off and must not throw away the translations already collected. + bool runtimeStarted = false; int totalErrors = 0; foreach (var targetLocale in targets) @@ -170,9 +196,23 @@ private static async Task RunAsync( ExistingTranslations = existingKeys, }; + if (provider is null) + { + runtime = resolveRuntime(); + if (runtime.Source == CopilotRuntimeSource.Missing) + { + Console.WriteLine(); + Console.Error.WriteLine(CopilotRuntimeLocator.FormatMissing(runtime)); + return 1; + } + provider = createProvider(runtime); + Console.Write($" (provider: {provider.Name}, runtime: {runtime.Describe()})"); + } + try { var result = await provider.TranslateAsync(batch); + runtimeStarted = true; foreach (var (key, value) in result.Translations) allTranslations[key] = value; @@ -180,6 +220,13 @@ private static async Task RunAsync( foreach (var (key, error) in result.Errors) allErrors[key] = error; } + catch (CopilotRuntimeStartException ex) when (!runtimeStarted) + { + Console.WriteLine(); + Console.Error.WriteLine(CopilotRuntimeLocator.FormatStartFailure( + runtime!, ex, CopilotRuntimeLocator.ExpectedVersion)); + return 1; + } catch (Exception ex) { Console.Error.WriteLine($"\n Error translating batch: {ex.Message}"); @@ -295,5 +342,9 @@ private static void ShowHelp() Console.WriteLine(); Console.WriteLine("Requires GitHub CLI (gh) to be installed and authenticated with a"); Console.WriteLine("Copilot-enabled GitHub account."); + Console.WriteLine(); + Console.WriteLine("Runtime: the copilot.exe in COPILOT_CLI_PATH if set, else the Copilot"); + Console.WriteLine("runtime bundled with mur, else an installed Copilot CLI"); + Console.WriteLine("(winget install GitHub.Copilot). `mur doctor` shows which one is used."); } } diff --git a/src/Reactor.Cli/Reactor.Cli.csproj b/src/Reactor.Cli/Reactor.Cli.csproj index 7774624152..6ea7112d28 100644 --- a/src/Reactor.Cli/Reactor.Cli.csproj +++ b/src/Reactor.Cli/Reactor.Cli.csproj @@ -70,6 +70,10 @@ + + @@ -90,6 +94,10 @@ + + + diff --git a/tests/Reactor.Tests/Localization/CopilotRuntimeLocatorTests.cs b/tests/Reactor.Tests/Localization/CopilotRuntimeLocatorTests.cs new file mode 100644 index 0000000000..f7ab1567e5 --- /dev/null +++ b/tests/Reactor.Tests/Localization/CopilotRuntimeLocatorTests.cs @@ -0,0 +1,412 @@ +using CpuArchitecture = System.Runtime.InteropServices.Architecture; +using Microsoft.UI.Reactor.Cli.Loc; +using Xunit; + +namespace Microsoft.UI.Reactor.Tests.Localization; + +/// +/// How mur loc translate finds its Copilot runtime when mur may have been +/// built without one bundled (issue #1133). +/// +public class CopilotRuntimeLocatorTests +{ + private const string BaseDir = @"C:\tools\mur"; + private const string LocalAppData = @"C:\Users\u\AppData\Local"; + private const string ProgramFiles = @"C:\Program Files"; + + private static readonly string NativeX64 = global::System.IO.Path.Join(BaseDir, "runtimes", "win-x64", "native"); + private static readonly string GhManaged = global::System.IO.Path.Join(LocalAppData, "GitHub CLI", "copilot", "copilot.exe"); + private static readonly string WinGetUser = global::System.IO.Path.Join(LocalAppData, "Microsoft", "WinGet", "Links", "copilot.exe"); + private static readonly string WinGetMachine = global::System.IO.Path.Join(ProgramFiles, "WinGet", "Links", "copilot.exe"); + + private static CopilotRuntimeResolution Resolve( + IEnumerable existing, + string? environmentPath = null, + CpuArchitecture architecture = CpuArchitecture.X64) + { + var files = new HashSet(existing, StringComparer.OrdinalIgnoreCase); + return CopilotRuntimeLocator.Resolve(BaseDir, environmentPath, architecture, LocalAppData, ProgramFiles, files.Contains); + } + + private static string[] BundledPair(string native) => + [global::System.IO.Path.Join(native, "copilot-runtime.exe"), global::System.IO.Path.Join(native, "runtime.node")]; + + [Fact] + public void BundledRuntimePair_IsUsedWithoutAnExplicitPath() + { + var result = Resolve([.. BundledPair(NativeX64), WinGetUser]); + + Assert.Equal(CopilotRuntimeSource.Bundled, result.Source); + Assert.Equal(NativeX64, result.Path); + Assert.Null(result.ExplicitCliPath); + } + + [Fact] + public void BundledRuntime_FollowsTheOsArchitecture() + { + // Resolve() passes RuntimeInformation.OSArchitecture, matching the SDK's GetPortableRid. + var nativeArm64 = global::System.IO.Path.Join(BaseDir, "runtimes", "win-arm64", "native"); + + Assert.Equal(CopilotRuntimeSource.Bundled, Resolve(BundledPair(nativeArm64), architecture: CpuArchitecture.Arm64).Source); + Assert.Equal(CopilotRuntimeSource.Missing, Resolve(BundledPair(nativeArm64), architecture: CpuArchitecture.X64).Source); + } + + [Fact] + public void BundledExplicitCli_CountsAsBundled() + { + var result = Resolve([ + global::System.IO.Path.Join(NativeX64, ".copilot-explicit-cli"), + global::System.IO.Path.Join(NativeX64, "copilot.exe"), + ]); + + Assert.Equal(CopilotRuntimeSource.Bundled, result.Source); + } + + [Theory] + [InlineData("copilot-runtime.exe")] + [InlineData("runtime.node")] + public void ExplicitCliNextToHalfARuntimePair_IsNotBundled(string halfOfPair) + { + // The SDK would fail on the incomplete pair, so a usable installed CLI must win. + var result = Resolve([ + global::System.IO.Path.Join(NativeX64, ".copilot-explicit-cli"), + global::System.IO.Path.Join(NativeX64, "copilot.exe"), + global::System.IO.Path.Join(NativeX64, halfOfPair), + WinGetUser, + ]); + + Assert.Equal(CopilotRuntimeSource.Installed, result.Source); + } + + [Fact] + public void IncompleteBundle_FallsBackToAnInstalledCli() + { + // copilot.exe alone, without the explicit-CLI marker, is not something the SDK launches. + var result = Resolve([ + global::System.IO.Path.Join(NativeX64, "copilot-runtime.exe"), + global::System.IO.Path.Join(NativeX64, "copilot.exe"), + WinGetUser, + ]); + + Assert.Equal(CopilotRuntimeSource.Installed, result.Source); + Assert.Equal(WinGetUser, result.ExplicitCliPath); + } + + [Fact] + public void InstalledCli_PrefersGhManaged_ThenWinGetUser_ThenWinGetMachine() + { + Assert.Equal(GhManaged, Resolve([GhManaged, WinGetUser, WinGetMachine]).Path); + Assert.Equal(WinGetUser, Resolve([WinGetUser, WinGetMachine]).Path); + Assert.Equal(WinGetMachine, Resolve([WinGetMachine]).Path); + } + + [Fact] + public void EnvironmentVariable_WinsOverBundledAndInstalled() + { + const string custom = @"D:\copilot\copilot.exe"; + var result = Resolve([.. BundledPair(NativeX64), WinGetUser, custom], environmentPath: $" {custom} "); + + Assert.Equal(CopilotRuntimeSource.Environment, result.Source); + Assert.Equal(custom, result.ExplicitCliPath); + } + + [Fact] + public void EnvironmentVariable_PointingNowhere_IsReported_NotReplaced() + { + var result = Resolve([.. BundledPair(NativeX64), WinGetUser], environmentPath: @"D:\gone\copilot.exe"); + + Assert.Equal(CopilotRuntimeSource.Missing, result.Source); + Assert.Contains(@"D:\gone\copilot.exe", result.Problem); + Assert.Contains(@"D:\gone\copilot.exe", CopilotRuntimeLocator.FormatMissing(result)); + } + + [Fact] + public void EmptyEnvironmentVariable_CountsAsUnset() + { + Assert.Equal(CopilotRuntimeSource.Bundled, Resolve(BundledPair(NativeX64), environmentPath: "").Source); + } + + [Fact] + public void BlankEnvironmentVariable_IsReported() + { + // The SDK treats only an empty value as unset and would try to launch " ". + var result = Resolve([.. BundledPair(NativeX64), WinGetUser], environmentPath: " "); + + Assert.Equal(CopilotRuntimeSource.Missing, result.Source); + Assert.Contains("blank", result.Problem); + } + + [Theory] + [InlineData("copilot.exe")] + [InlineData(@"tools\copilot.exe")] + [InlineData("copilot")] + public void RelativeEnvironmentVariable_IsReported_EvenWhenItExists(string relative) + { + // Relative to the project being localized, so a checked-in copilot.exe could be launched. + var result = Resolve([relative, .. BundledPair(NativeX64)], environmentPath: relative); + + Assert.Equal(CopilotRuntimeSource.Missing, result.Source); + Assert.Contains("not a full path", result.Problem); + } + + [Fact] + public void NothingFound_SearchesOnlyTheFixedLocations_AndSaysHowToFixIt() + { + var result = Resolve([]); + + Assert.Equal(CopilotRuntimeSource.Missing, result.Source); + // A fixed list, never PATH: an unrelated copilot.exe on PATH must not be launched. + Assert.Equal([NativeX64, GhManaged, WinGetUser, WinGetMachine], result.Searched); + + var message = CopilotRuntimeLocator.FormatMissing(result); + Assert.Contains("winget install GitHub.Copilot", message); + Assert.Contains(CopilotRuntimeLocator.EnvironmentVariable, message); + Assert.All(result.Searched, path => Assert.Contains(path, message)); + } + + [Fact] + public void ExpectedVersion_IsTheRuntimeVersionTheSdkBundles() + { + // Stamped from the SDK's $(CopilotCliVersion) by Reactor.Cli.csproj. + Assert.Matches(@"^\d+\.\d+\.\d+", CopilotRuntimeLocator.ExpectedVersion); + } + + [Fact] + public void StartFailureAdvice_DependsOnWhereTheRuntimeCameFrom() + { + var error = new InvalidOperationException("protocol version mismatch"); + string Advice(CopilotRuntimeSource source) => CopilotRuntimeLocator.FormatStartFailure( + new CopilotRuntimeResolution(source, @"C:\cli\copilot.exe", []), error, "1.2.3"); + + // COPILOT_CLI_PATH overrides the bundled runtime, so rebuilding mur cannot help. + Assert.Contains("unset it", Advice(CopilotRuntimeSource.Environment)); + Assert.DoesNotContain("rebuild", Advice(CopilotRuntimeSource.Environment), StringComparison.OrdinalIgnoreCase); + Assert.Contains("Copilot CLI 1.2.3", Advice(CopilotRuntimeSource.Installed)); + Assert.Contains("If you build mur from source", Advice(CopilotRuntimeSource.Installed)); + Assert.DoesNotContain("1.2.3", Advice(CopilotRuntimeSource.Bundled)); + } +} + +/// The mur doctor line for the runtime mur loc translate uses (issue #1133). +public class DoctorTranslateRuntimeCheckTests +{ + [Fact] + public void Missing_WarnsWithAFix() + { + var (ok, detail) = Microsoft.UI.Reactor.Cli.Doctor.DoctorCommand.TranslateRuntimeCheck( + new CopilotRuntimeResolution(CopilotRuntimeSource.Missing, null, []), "1.2.3"); + + Assert.False(ok); + Assert.Contains("winget install GitHub.Copilot", detail); + } + + [Fact] + public void BadEnvironmentVariable_WarnsWithTheProblemAndAFix() + { + var (ok, detail) = Microsoft.UI.Reactor.Cli.Doctor.DoctorCommand.TranslateRuntimeCheck( + new CopilotRuntimeResolution(CopilotRuntimeSource.Missing, null, [], "COPILOT_CLI_PATH is set to 'x'."), "1.2.3"); + + Assert.False(ok); + Assert.StartsWith("COPILOT_CLI_PATH is set to 'x'.", detail); + Assert.Contains("unset it", detail); + } + + [Fact] + public void InstalledCli_NamesTheVersionMurWasBuiltFor_BundledDoesNot() + { + var installed = Microsoft.UI.Reactor.Cli.Doctor.DoctorCommand.TranslateRuntimeCheck( + new CopilotRuntimeResolution(CopilotRuntimeSource.Installed, @"C:\cli\copilot.exe", []), "1.2.3"); + var bundled = Microsoft.UI.Reactor.Cli.Doctor.DoctorCommand.TranslateRuntimeCheck( + new CopilotRuntimeResolution(CopilotRuntimeSource.Bundled, @"C:\mur\runtimes\win-x64\native", []), "1.2.3"); + + Assert.True(installed.Ok); + Assert.Contains(@"C:\cli\copilot.exe", installed.Detail); + Assert.Contains("built for Copilot runtime 1.2.3", installed.Detail); + Assert.True(bundled.Ok); + Assert.DoesNotContain("1.2.3", bundled.Detail); + } +} + +/// +/// mur loc translate reports a missing or unstartable Copilot runtime once, up front, +/// instead of once per batch (issue #1133). +/// +[Collection("ConsoleTests")] +public class TranslateCommandRuntimeTests : IDisposable +{ + private readonly string _root = global::System.IO.Path.Join( + global::System.IO.Path.GetTempPath(), "mur-translate-" + Guid.NewGuid().ToString("N")); + private readonly string _source; + + public TranslateCommandRuntimeTests() + { + _source = global::System.IO.Path.Join(_root, "Strings", "en-US"); + Directory.CreateDirectory(_source); + foreach (var ns in new[] { "Resources", "Errors" }) + { + File.WriteAllText(global::System.IO.Path.Join(_source, ns + ".resw"), """ + + + Hello + + """); + } + } + + public void Dispose() + { + // Best-effort cleanup of a temp folder: a leftover one must not fail the test. + try { Directory.Delete(_root, recursive: true); } + catch (IOException ex) { TestContext.Current.SendDiagnosticMessage($"Could not delete {_root}: {ex.Message}"); } + } + + [Fact] + public void MissingRuntime_FailsOnceBeforeTranslatingAnything() + { + var missing = new CopilotRuntimeResolution(CopilotRuntimeSource.Missing, null, [@"C:\nowhere"]); + var created = 0; + + var (exitCode, _, stderr) = Capture(() => TranslateCommand.Run( + ["--source", _source, "--target", "fr-FR,de-DE"], () => missing, + (_, _) => { created++; return new MockTranslationProvider(); })); + + Assert.Equal(1, exitCode); + Assert.Equal(0, created); + Assert.Single(stderr.Split('\n'), line => line.Contains("none was found")); + Assert.DoesNotContain( + Directory.GetFiles(global::System.IO.Path.Join(_root, "Strings"), "*.resw", SearchOption.AllDirectories), + f => !f.StartsWith(_source, StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public void NothingToTranslate_SucceedsWithoutARuntime() + { + // A no-op run (here --missing-only against a fully translated locale) never needs Copilot. + var target = global::System.IO.Path.Join(_root, "Strings", "fr-FR"); + Directory.CreateDirectory(target); + foreach (var file in Directory.GetFiles(_source)) + File.Copy(file, global::System.IO.Path.Join(target, global::System.IO.Path.GetFileName(file))); + var resolved = 0; + + var (exitCode, _, stderr) = Capture(() => TranslateCommand.Run( + ["--source", _source, "--target", "fr-FR", "--missing-only"], + () => { resolved++; return new CopilotRuntimeResolution(CopilotRuntimeSource.Missing, null, []); })); + + Assert.Equal(0, exitCode); + Assert.Equal(0, resolved); + Assert.DoesNotContain("none was found", stderr); + } + + [Fact] + public void RuntimeThatWillNotStart_IsReportedOnce_AndStopsTheRun() + { + var calls = 0; + var provider = new ThrowingProvider(() => + { + calls++; + throw new CopilotRuntimeStartException(new InvalidOperationException("protocol version mismatch")); + }); + var installed = new CopilotRuntimeResolution(CopilotRuntimeSource.Installed, @"C:\cli\copilot.exe", []); + var sourceFiles = ReswReader.ReadLocale(_source); + + var (exitCode, _, stderr) = Capture(() => TranslateCommand.RunAsync( + provider, sourceFiles, "en-US", ["fr-FR", "de-DE"], global::System.IO.Path.Join(_root, "Strings"), + missingOnly: false, installed).GetAwaiter().GetResult()); + + Assert.Equal(1, exitCode); + Assert.Equal(1, calls); + Assert.Single(stderr.Split('\n'), line => line.Contains("could not start the Copilot runtime")); + Assert.Contains("protocol version mismatch", stderr); + Assert.Contains(CopilotRuntimeLocator.EnvironmentVariable, stderr); + } + + [Theory] + [InlineData("Installed", @"C:\cli\copilot.exe", @"C:\cli\copilot.exe")] + [InlineData("Environment", @"D:\copilot.exe", @"D:\copilot.exe")] + [InlineData("Bundled", @"C:\mur\runtimes\win-x64\native", null)] + public void ProviderIsGivenTheResolvedCli_OnlyWhenNotBundled(string source, string path, string? expected) + { + var resolution = new CopilotRuntimeResolution(Enum.Parse(source), path, []); + string? given = "unset"; + + var (exitCode, _, _) = Capture(() => TranslateCommand.Run( + ["--source", _source, "--target", "fr-FR"], () => resolution, + (_, cliPath) => { given = cliPath; return new MockTranslationProvider(); })); + + Assert.Equal(0, exitCode); + Assert.Equal(expected, given); + } + + [Fact] + public async Task Provider_WrapsAFailedStart_AndLaunchesTheCliItWasGiven() + { + var missingCli = global::System.IO.Path.Join(_root, "no-such-dir", "copilot.exe"); + var provider = new CopilotTranslationProvider(cliPath: missingCli); + var batch = new TranslationBatch + { + SourceLocale = "en-US", + TargetLocale = "fr-FR", + Entries = [new TranslationEntry { Key = "Greeting", Value = "Hello" }], + }; + + var ex = await Assert.ThrowsAsync(() => provider.TranslateAsync(batch, TestContext.Current.CancellationToken)); + Assert.Contains(missingCli, ex.InnerException!.ToString()); + } + + [Fact] + public void StartFailureAfterABatchRan_KeepsTheFinishedTranslations() + { + // 26 keys make two batches in one namespace; the second fails to start. + var bigSource = global::System.IO.Path.Join(_root, "Big", "en-US"); + Directory.CreateDirectory(bigSource); + var data = string.Concat(Enumerable.Range(0, 26).Select(i => + $"Text {i}")); + File.WriteAllText(global::System.IO.Path.Join(bigSource, "Resources.resw"), + $"{data}"); + var calls = 0; + var flaky = new MockTranslationProvider(batch => ++calls == 1 + ? new TranslationResult { Translations = batch.Entries.ToDictionary(e => e.Key, e => "fr " + e.Value) } + : throw new CopilotRuntimeStartException(new InvalidOperationException("spawn timed out"))); + var bundled = new CopilotRuntimeResolution(CopilotRuntimeSource.Bundled, @"C:\mur", []); + var stringsDir = global::System.IO.Path.Join(_root, "Big"); + + var (exitCode, _, stderr) = Capture(() => TranslateCommand.RunAsync( + flaky, ReswReader.ReadLocale(bigSource), "en-US", ["fr-FR"], stringsDir, + missingOnly: false, bundled).GetAwaiter().GetResult()); + + Assert.Equal(1, exitCode); + Assert.Equal(2, calls); + Assert.DoesNotContain("could not start the Copilot runtime", stderr); + Assert.Contains("spawn timed out", stderr); + var written = ReswReader.ReadLocale(global::System.IO.Path.Join(stringsDir, "fr-FR")); + Assert.Equal(25, Assert.Single(written).Entries.Count); + } + + private sealed class ThrowingProvider(Func translate) : ITranslationProvider + { + public string Name => "Throwing"; + + public Task TranslateAsync(TranslationBatch batch, CancellationToken ct = default) => + Task.FromResult(translate()); + } + + private static (int ExitCode, string Stdout, string Stderr) Capture(Func action) + { + var origOut = Console.Out; + var origErr = Console.Error; + using var outWriter = new StringWriter(); + using var errWriter = new StringWriter(); + Console.SetOut(outWriter); + Console.SetError(errWriter); + try + { + var exitCode = action(); + return (exitCode, outWriter.ToString(), errWriter.ToString()); + } + finally + { + Console.SetOut(origOut); + Console.SetError(origErr); + } + } +} diff --git a/tests/build_props/ci/CopilotSdkContract.Tests.ps1 b/tests/build_props/ci/CopilotSdkContract.Tests.ps1 index 8fe8c4055c..efcec22ec3 100644 --- a/tests/build_props/ci/CopilotSdkContract.Tests.ps1 +++ b/tests/build_props/ci/CopilotSdkContract.Tests.ps1 @@ -1,8 +1,9 @@ <# .SYNOPSIS Headless tests for the repo's dependency on GitHub.Copilot.SDK's MSBuild - contract: the reviewed SDK version, and the CI-only CopilotSkipCliDownload - default that Directory.Build.props derives from $(CI). + contract: the reviewed SDK version, the CI-only CopilotSkipCliDownload + default that Directory.Build.props derives from $(CI), and the offline + fallback in src/Reactor.Cli/CopilotRuntime.targets (issue #1133). .DESCRIPTION Evaluates Directory.Build.props from a bare non-SDK project in a temp directory @@ -42,7 +43,12 @@ $packagesProps = Join-Path $repoRoot 'Directory.Packages.props' # (gh api repos/github/copilot-sdk/compare/v...v) and confirm that # CopilotSkipCliDownload still gates the native CLI download, and that # CopilotCliReleaseBaseUrl / COPILOT_CLI_DOWNLOAD_BASE_URL / CopilotCliBinaryPath -# still behave as Directory.Build.props and CONTRIBUTING.md describe. Then bump this. +# still behave as Directory.Build.props and CONTRIBUTING.md describe. Also confirm what +# src/Reactor.Cli/CopilotRuntime.targets mirrors: the release URL and tag shape, the +# $(_CopilotPlatform) / $(CopilotCliVersion) properties, the +# copilot-cli\\\.copilot-runtime-complete cache marker, and that +# _DownloadCopilotCli, _CopyCopilotCliToOutput and _RegisterCopilotCliForCopy still run on +# BeforeBuild / Build / GetCopyTo*DirectoryItems. Then bump this. $reviewedSdkVersion = '1.0.34' $sdkPinned = [regex]::Match( [IO.File]::ReadAllText($packagesProps), @@ -89,6 +95,99 @@ function Invoke-Probe { return $match.Groups['v'].Value } +# Stand-in for Reactor.Cli: the inputs GitHub.Copilot.SDK's build props and targets provide, +# then CopilotRuntime.targets, then a stand-in for the SDK's _DownloadCopilotCli. +$runtimeTargets = Join-Path $repoRoot 'src\Reactor.Cli\CopilotRuntime.targets' +$runtimeProbe = Join-Path $tmp 'runtime-probe.proj' +Set-Content -LiteralPath $runtimeProbe -Encoding UTF8 -Value @" + + + net10.0 + 9.9.9 + <_CopilotPlatform>win32-x64 + <_CopilotRuntimeWrapper>copilot-runtime.exe + obj\ + + + + + + + + + + + + + + +"@ + +# Serves a SHA256SUMS.txt for the releases in $served and 404 for anything else, so the +# probe's success and HTTP-error branches run without touching the network. +# 7.7.7 lists only another platform's archive, which the SDK would reject. +$sum = '0' * 64 +$served = @{ + '/v9.9.9/SHA256SUMS.txt' = "$sum github-copilot-9.9.9-win32-x64.tgz`n$sum github-copilot-9.9.9-linux-x64.tgz`n" + '/runtime-1.0.0-unstable.r1.gabcdef0/SHA256SUMS.txt' = "$sum *github-copilot-1.0.0-unstable.r1.gabcdef0-win32-x64.tgz`n" + '/v7.7.7/SHA256SUMS.txt' = "$sum github-copilot-7.7.7-linux-x64.tgz`n" +} +$requests = [System.Collections.Concurrent.ConcurrentQueue[string]]::new() +$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0) +$listener.Start() +$mirror = "http://127.0.0.1:$($listener.LocalEndpoint.Port)" +$server = [powershell]::Create() +$null = $server.AddScript({ + param($listener, $served, $requests) + while ($true) { + try { $client = $listener.AcceptTcpClient() } catch { return } + try { + $stream = $client.GetStream() + $reader = [IO.StreamReader]::new($stream, [Text.Encoding]::ASCII, $false, 1024, $true) + $path = ($reader.ReadLine() -split ' ')[1] + while ($reader.ReadLine()) { } + $requests.Enqueue($path) + $status = if ($served.ContainsKey($path)) { '200 OK' } else { '404 Not Found' } + $body = [Text.Encoding]::ASCII.GetBytes($(if ($served.ContainsKey($path)) { $served[$path] } else { 'not found' })) + $head = [Text.Encoding]::ASCII.GetBytes("HTTP/1.1 $status`r`nContent-Length: $($body.Length)`r`nConnection: close`r`n`r`n") + $stream.Write($head, 0, $head.Length) + $stream.Write($body, 0, $body.Length) + $stream.Flush() + } + catch { } + finally { $client.Close() } + } +}).AddArgument($listener).AddArgument($served).AddArgument($requests) +$null = $server.BeginInvoke() + +function Get-Requests { + $all = @() + $path = $null + while ($requests.TryDequeue([ref]$path)) { $all += $path } + return $all +} + +function Invoke-RuntimeProbe { + param([string[]]$Properties = @()) + + foreach ($name in $scrubbed) { [Environment]::SetEnvironmentVariable($name, $null, 'Process') } + $output = & dotnet msbuild $runtimeProbe -nologo -v:m @Properties 2>&1 | Out-String + $rc = $LASTEXITCODE + $global:LASTEXITCODE = 0 + if ($rc -ne 0) { throw "dotnet msbuild exited $rc`n$output" } + return $output +} + +function Get-Marker { + param([string]$Output, [string]$Name) + $match = [regex]::Match($Output, "$Name=\[(?[^\]]*)\]") + if (-not $match.Success) { throw "Probe produced no $Name marker:`n$Output" } + return $match.Groups['v'].Value +} + try { Assert-Equal 'true' (Invoke-Probe -Environment @{ CI = 'true' }) ` 'CI=true from the environment (GitHub Actions) skips the native CLI download' @@ -100,8 +199,79 @@ try { 'CI=false does not skip the native CLI download' Assert-Equal 'false' (Invoke-Probe -Environment @{ CI = 'true' } -Properties @('-p:CopilotSkipCliDownload=false')) ` 'an explicit CopilotSkipCliDownload=false opts a CI build back into the download' + + # src/Reactor.Cli/CopilotRuntime.targets (issue #1133): a cold build that cannot reach the + # release host skips the download with REACTORCLI001 instead of failing on MSB3923. The + # stand-in SDK targets are declared after the import, as nuget.g.targets is, so these cases + # also pin that the probe's property reaches the SDK's same-hook targets in time. + # 127.0.0.1:1 refuses at once and $mirror is local, so no case touches the network. + $unreachable = '-p:CopilotCliReleaseBaseUrl=https://127.0.0.1:1/releases' + + # Positive control first: a release host that answers keeps the download on. + $out = Invoke-RuntimeProbe -Properties @("-p:CopilotCliReleaseBaseUrl=$mirror/") + Assert-Equal '' (Get-Marker $out 'SKIP') 'a reachable release host leaves the download on' + Assert-Equal $false ($out -match 'REACTORCLI001') 'a reachable release host is not reported' + Assert-Equal $true ($out -match 'SDK_DOWNLOAD_RAN') 'a reachable release host lets the SDK download the runtime' + Assert-Equal '/v9.9.9/SHA256SUMS.txt' ((Get-Requests) -join ',') 'the probe requests the release the SDK would download, trailing slash trimmed' + + $out = Invoke-RuntimeProbe -Properties @("-p:CopilotCliReleaseBaseUrl=$mirror", '-p:CopilotCliVersion=1.0.0-unstable.r1.gabcdef0') + Assert-Equal $false ($out -match 'REACTORCLI001') 'an unstable runtime is probed under its runtime- tag' + Assert-Equal '/runtime-1.0.0-unstable.r1.gabcdef0/SHA256SUMS.txt' ((Get-Requests) -join ',') 'the unstable tag matches the SDK' + + $out = Invoke-RuntimeProbe -Properties @("-p:CopilotCliReleaseBaseUrl=$mirror", '-p:CopilotCliVersion=7.7.7') + $null = Get-Requests + Assert-Equal 'true' (Get-Marker $out 'SKIP') "checksums that don't list this platform's archive skip the download" + Assert-Equal $true ($out -match 'does not list exactly one checksum for github-copilot-7\.7\.7-win32-x64\.tgz') 'REACTORCLI001 names the missing checksum' + + $out = Invoke-RuntimeProbe -Properties @("-p:CopilotCliReleaseBaseUrl=$mirror", '-p:CopilotCliVersion=8.8.8') + $null = Get-Requests + Assert-Equal 'true' (Get-Marker $out 'SKIP') 'a release the mirror does not have (404) skips the download' + Assert-Equal $true ($out -match 'warning MSB3923') 'the failed probe keeps its MSB3923 reason visible' + Assert-Equal $true ($out -match 'check the CopilotCliReleaseBaseUrl') 'with a mirror set, REACTORCLI001 says to check that mirror' + + $out = Invoke-RuntimeProbe -Properties @($unreachable) + Assert-Equal 'true' (Get-Marker $out 'SKIP') 'an unreachable release host skips the download for this build' + Assert-Equal $true ($out -match 'warning REACTORCLI001') 'the skipped download is reported as REACTORCLI001' + Assert-Equal $true ($out -match '127\.0\.0\.1:1/releases/v9\.9\.9/SHA256SUMS\.txt') 'the probe checks the release the SDK would download' + Assert-Equal $false ($out -match 'SDK_DOWNLOAD_RAN') "the SDK's download target sees the skip" + + # Entered through GetCopyToOutputDirectoryItems without a Build, as a project reference + # built with BuildProjectReferences=false is. + $out = Invoke-RuntimeProbe -Properties @($unreachable, '-t:GetCopyToOutputDirectoryItems') + Assert-Equal $true ($out -match 'warning REACTORCLI001') 'the probe also runs ahead of GetCopyToOutputDirectoryItems' + Assert-Equal $false ($out -match 'SDK_REGISTER_RAN|SDK_DOWNLOAD_RAN') "the SDK's register target sees the skip" + + $out = Invoke-RuntimeProbe -Properties @($unreachable, '-p:CopilotSkipCliDownload=false') + Assert-Equal $false ($out -match 'REACTORCLI001') 'an explicit CopilotSkipCliDownload=false is not probed' + Assert-Equal $true ($out -match 'SDK_DOWNLOAD_RAN') 'an explicit CopilotSkipCliDownload=false keeps the strict SDK download' + + $out = Invoke-RuntimeProbe -Properties @($unreachable, '-p:CopilotSkipCliDownload=true') + Assert-Equal $false ($out -match 'REACTORCLI001') 'CopilotSkipCliDownload=true (CI) is not probed' + + $out = Invoke-RuntimeProbe -Properties @($unreachable, '-p:CopilotCliBinaryPath=C:\copilot\copilot.exe') + Assert-Equal $false ($out -match 'REACTORCLI001') 'a supplied CopilotCliBinaryPath is not probed' + + $cache = Join-Path $tmp 'obj\copilot-cli\9.9.9\win32-x64' + $cacheFiles = @('.copilot-runtime-complete', 'prebuilds\win32-x64\copilot-runtime.exe', 'prebuilds\win32-x64\runtime.node') + foreach ($file in $cacheFiles) { New-Item -ItemType File -Force -Path (Join-Path $cache $file) | Out-Null } + $out = Invoke-RuntimeProbe -Properties @($unreachable) + Assert-Equal $false ($out -match 'REACTORCLI001') 'a warm runtime cache is not probed, so offline rebuilds stay quiet' + Assert-Equal $true ($out -match 'SDK_DOWNLOAD_RAN') 'a warm runtime cache leaves the SDK target to reuse it' + + # The SDK re-downloads a cache missing any of the three, so the probe must too. + Remove-Item -LiteralPath (Join-Path $cache 'prebuilds\win32-x64\copilot-runtime.exe') + $out = Invoke-RuntimeProbe -Properties @($unreachable) + Remove-Item -LiteralPath $cache -Recurse -Force + Assert-Equal $true ($out -match 'warning REACTORCLI001') 'a cache with only its marker left is probed like a cold one' + + # The probe only protects Reactor.Cli if its project body imports it. + [xml]$cliProject = Get-Content -Raw -LiteralPath (Join-Path $repoRoot 'src\Reactor.Cli\Reactor.Cli.csproj') + $imports = @($cliProject.Project.ChildNodes | Where-Object { $_.LocalName -eq 'Import' -and $_.Project -eq 'CopilotRuntime.targets' }) + Assert-Equal 1 $imports.Count 'Reactor.Cli.csproj imports CopilotRuntime.targets directly in its project body' } finally { + $listener.Stop() + $server.Dispose() foreach ($name in $scrubbed) { [Environment]::SetEnvironmentVariable($name, $saved[$name], 'Process') } Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue }