diff --git a/.github/workflows/bash-exe.yml b/.github/workflows/bash-exe.yml new file mode 100644 index 000000000..d157932c5 --- /dev/null +++ b/.github/workflows/bash-exe.yml @@ -0,0 +1,186 @@ +# Builds BaoCode Bash (bash.exe, github.com/baocode-dev/bash-exe) for +# Windows x64 and arm64, and runs it on each (tool/test_bash_exe.ps1). The +# app offers it on Windows (lib/bash_exe/) and downloads it from +# dl.baocode.dev/tools/bash-exe/. +# +# git tag bash-exe-0.2.0 && git push origin bash-exe-0.2.0 +# build bash-exe's tag v0.2.0 (its +# version has to be 0.2.0), and publish +# the builds at dl.baocode.dev/tools/ +# bash-exe/0.2.0/, then latest.json +# there naming them, for the app +# Actions → BaoCode Bash → Run workflow +# build a branch, tag or commit of it, +# to try it +name: BaoCode Bash + +on: + push: + tags: ['bash-exe-*'] + # Its main, with this workflow and its test changed. + pull_request: + paths: + - .github/workflows/bash-exe.yml + - tool/test_bash_exe.ps1 + workflow_dispatch: + inputs: + ref: + description: The branch, tag or commit of baocode-dev/bash-exe to build + default: main + +permissions: + contents: read + +jobs: + build: + name: Build for Windows (${{ matrix.arch }}) + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - arch: x64 + runner: windows-latest + target: x86_64-pc-windows-msvc + - arch: arm64 + runner: windows-11-arm + target: aarch64-pc-windows-msvc + outputs: + version: ${{ steps.version.outputs.version }} + commit: ${{ steps.version.outputs.commit }} + steps: + - uses: actions/checkout@v5 + - name: Which bash-exe + id: ref + shell: bash + run: | + if [ "$GITHUB_EVENT_NAME" = push ]; then + echo "ref=v${GITHUB_REF_NAME#bash-exe-}" >> "$GITHUB_OUTPUT" + else + echo "ref=${{ inputs.ref || 'main' }}" >> "$GITHUB_OUTPUT" + fi + - uses: actions/checkout@v5 + with: + repository: baocode-dev/bash-exe + ref: ${{ steps.ref.outputs.ref }} + path: bash-exe + - uses: ./.github/actions/setup-rust + with: + dir: bash-exe + - name: Its version + id: version + shell: bash + working-directory: bash-exe + run: | + version=$(sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\(.*\)"/\1/p' Cargo.toml) + echo "bash-exe $version, $(git rev-parse HEAD)" + if [ "$GITHUB_EVENT_NAME" = push ] && [ "bash-exe-$version" != "$GITHUB_REF_NAME" ]; then + echo "::error::$GITHUB_REF_NAME, but bash-exe's ${{ steps.ref.outputs.ref }} is version $version" + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "commit=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + - uses: actions/cache@v5 + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + bash-exe/target + key: bash-exe-${{ matrix.target }}-${{ hashFiles('bash-exe/Cargo.lock', 'bash-exe/rust-toolchain.toml') }} + restore-keys: bash-exe-${{ matrix.target }}- + - name: Build + working-directory: bash-exe + run: cargo build --locked --release -p bash-exe --target ${{ matrix.target }} + - name: Run it here + shell: pwsh + run: ./tool/test_bash_exe.ps1 bash-exe/target/${{ matrix.target }}/release/bash.exe + - name: Package it + shell: pwsh + run: | + $out = "dist/bash-exe-windows-${{ matrix.arch }}" + New-Item -ItemType Directory -Path $out | Out-Null + Copy-Item bash-exe/target/${{ matrix.target }}/release/bash.exe, bash-exe/LICENSE, bash-exe/LICENSE-MIT, bash-exe/README.md $out + # GPL: where its source is, exactly. + "BaoCode Bash ${{ steps.version.outputs.version }}`nSource: https://github.com/baocode-dev/bash-exe/tree/${{ steps.version.outputs.commit }}`n" | + Set-Content -NoNewline "$out/SOURCE.txt" + # For people, with its license; the app takes bash.exe alone, + # gzipped (dart:io has gzip, not zip). + Compress-Archive -Path "$out/*" -DestinationPath "dist/bash-exe-windows-${{ matrix.arch }}.zip" + $gz = "dist/bash-windows-${{ matrix.arch }}.exe.gz" + $in = [IO.File]::OpenRead((Resolve-Path "$out/bash.exe")) + $file = [IO.File]::Create((Join-Path $PWD $gz)) + $zip = New-Object IO.Compression.GZipStream($file, [IO.Compression.CompressionLevel]::SmallestSize) + $in.CopyTo($zip) + $zip.Dispose(); $file.Dispose(); $in.Dispose() + "$out/bash.exe", "dist/bash-exe-windows-${{ matrix.arch }}.zip", $gz | + ForEach-Object { "{0}: {1:N1} MB" -f $_, ((Get-Item $_).Length / 1MB) } + - uses: actions/upload-artifact@v6 + with: + name: bash-exe-windows-${{ matrix.arch }} + if-no-files-found: error + path: | + dist/bash-exe-windows-${{ matrix.arch }}.zip + dist/bash-windows-${{ matrix.arch }}.exe.gz + + publish: + name: Publish to dl.baocode.dev/tools/bash-exe/ + needs: build + if: github.event_name == 'push' + runs-on: ubuntu-latest + # The release environment's R2 token (it has to let bash-exe-* tags in). + environment: release + concurrency: + group: bash-exe-publish + cancel-in-progress: false + env: + VERSION: ${{ needs.build.outputs.version }} + COMMIT: ${{ needs.build.outputs.commit }} + R2_BUCKET: ${{ vars.R2_BUCKET }} + AWS_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: auto + AWS_ENDPOINT_URL: https://${{ secrets.R2_ACCOUNT_ID }}.r2.cloudflarestorage.com + # R2 does not take every checksum newer AWS CLIs send by default. + AWS_REQUEST_CHECKSUM_CALCULATION: when_required + AWS_RESPONSE_CHECKSUM_VALIDATION: when_required + steps: + - uses: actions/download-artifact@v7 + with: + pattern: bash-exe-windows-* + merge-multiple: true + path: dist + - name: Upload the builds + run: | + # Named by the version, so never changed once there. + aws s3 cp dist "s3://$R2_BUCKET/tools/bash-exe/$VERSION/" \ + --recursive --cache-control 'public, max-age=31536000, immutable' + - name: Check they are served + run: | + for file in dist/*; do + url="https://dl.baocode.dev/tools/bash-exe/$VERSION/$(basename "$file")" + expected=$(stat -c %s "$file") + served=$(curl -fsSI "$url" | tr -d '\r' | awk 'tolower($1) == "content-length:" { print $2 }') + echo "$url: $served bytes (expected $expected)" + [ "$served" = "$expected" ] || { echo "::error::$url is not served as uploaded"; exit 1; } + done + - name: Name them in latest.json, last + run: | + # What the app downloads: bash.exe gzipped, by architecture; the + # size and SHA-256 of the download, and the size unpacked. + files='{}' + for arch in x64 arm64; do + gz="dist/bash-windows-$arch.exe.gz" + files=$(jq --arg arch "$arch" \ + --arg url "https://dl.baocode.dev/tools/bash-exe/$VERSION/$(basename "$gz")" \ + --argjson size "$(stat -c %s "$gz")" \ + --arg sha256 "$(sha256sum "$gz" | cut -d' ' -f1)" \ + --argjson unpacked "$(gzip -dc "$gz" | wc -c)" \ + '.[$arch] = {url: $url, size: $size, sha256: $sha256, unpacked: $unpacked}' <<< "$files") + done + jq -n --arg version "$VERSION" --arg commit "$COMMIT" --argjson files "$files" \ + '{version: $version, commit: $commit, files: $files}' > latest.json + cat latest.json + aws s3 cp latest.json "s3://$R2_BUCKET/tools/bash-exe/latest.json" \ + --cache-control 'public, max-age=60' --content-type application/json + echo "## BaoCode Bash \`$VERSION\` (bash-exe ${COMMIT::7})" >> "$GITHUB_STEP_SUMMARY" diff --git a/lib/bash_exe/bao_bash.dart b/lib/bash_exe/bao_bash.dart new file mode 100644 index 000000000..2c6b5335a --- /dev/null +++ b/lib/bash_exe/bao_bash.dart @@ -0,0 +1,306 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../tips/feature_tip.dart' show TipStorage; +import '../tips/feature_tips_controller.dart'; +import 'bao_bash_stub.dart' if (dart.library.io) 'bao_bash_io.dart' as platform; + +/// The build of BaoCode Bash `latest.json` names for this machine +/// (.github/workflows/bash-exe.yml publishes them): `bash.exe` gzipped, +/// the size and SHA-256 (lowercase hex) of the download, and its size +/// unpacked. +class BaoBashRelease { + const BaoBashRelease({ + required this.version, + required this.url, + required this.size, + required this.sha256, + this.unpacked, + }); + + /// Where the builds are named. + static final latestUrl = Uri.parse( + 'https://dl.baocode.dev/tools/bash-exe/latest.json', + ); + + /// The build for [arch] (`x64`, `arm64`) in [json], `latest.json`; null + /// when it names none, or its version could not name a folder. + static BaoBashRelease? parse(Object? json, String arch) { + if (json + case { + 'version': final String version, + 'files': final Map files, + } + when _folderName.hasMatch(version)) { + if (files[arch] case { + 'url': final String url, + 'size': final int size, + 'sha256': final String sha256, + }) { + final unpacked = (files[arch]! as Map)['unpacked']; + return BaoBashRelease( + version: version, + url: Uri.parse(url), + size: size, + sha256: sha256.toLowerCase(), + unpacked: unpacked is int ? unpacked : null, + ); + } + } + return null; + } + + static final _folderName = RegExp(r'^[A-Za-z0-9][A-Za-z0-9._+-]*$'); + + final String version; + final Uri url; + final int size; + final String sha256; + final int? unpacked; +} + +/// BaoCode Bash as installed: its version, and its `bash.exe`. +typedef BaoBashInstall = ({String version, String executable}); + +/// Where BaoCode Bash is installed, and what fetches it: the data +/// directory's `tools/bash-exe/` and dl.baocode.dev (bao_bash_io.dart); +/// replaceable under test. +abstract interface class BaoBashHost { + /// This machine's architecture as the builds are named (`x64`, + /// `arm64`); null where there is none for it. + String? get arch; + + /// What is installed; null for none. + BaoBashInstall? installed(); + + /// `latest.json`, decoded. + Future fetchLatest(); + + /// Downloads [release], checks it is the one named, and installs it in + /// place of what was; [progress] told what share of it came. + Future install( + BaoBashRelease release, + void Function(double done) progress, + ); + + /// Removes what is installed; a `bash.exe` an agent is running is + /// removed the next time. + Future uninstall(); +} + +/// BaoCode Bash (github.com/baocode-dev/bash-exe), offered on Windows: +/// bash 5.3 with `rg`, `grep`, `sed`, `awk`, `find`, `jq` and the like +/// built in, that takes `C:\x` and `/c/x` alike. Installed, the built-in +/// core runs its agents' commands with it ahead of Git Bash +/// ([executable]; `Shell.find` in bao_agent). +/// +/// Settings → General installs, updates and removes it. Above every page +/// the settings dialog recommends it ([showsNotice]) to all but a new user +/// ([newUser]: the app first run here less than [newUserDays] ago, or +/// fewer than [newUserMessages] messages sent), until put off for good. +class BaoBash extends ChangeNotifier { + BaoBash({required this.host, this.storage, DateTime Function()? now}) + : _now = now ?? DateTime.now, + _installed = host.installed(); + + /// The app's, made in main(); null where it is not offered: anywhere + /// but Windows, and under test. + static BaoBash? current; + + /// The platform's, with what is kept in [storage]; null where it is not + /// offered. + static BaoBash? forPlatform(TipStorage? storage) { + final host = platform.baoBashHost(); + if (host == null || host.arch == null) return null; + return BaoBash(host: host, storage: storage); + } + + /// The `bash.exe` the agents run commands with, where it is installed. + static String? get executable => current?.installed?.executable; + + final BaoBashHost host; + + /// Where [newUser] and the notice put off are kept; none under test. + final TipStorage? storage; + final DateTime Function() _now; + + BaoBashInstall? _installed; + BaoBashInstall? get installed => _installed; + + BaoBashRelease? _latest; + + /// The build there is to install, once [check] found it. + BaoBashRelease? get latest => _latest; + + DateTime? _checkedAt; + + /// Whether it is downloading or removing. + bool get busy => _busy; + bool _busy = false; + + /// The share of the download that came, while it comes. + double? get progress => _progress; + double? _progress; + + /// What went wrong the last time, in words to show. + String? get error => _error; + String? _error; + + bool get updateAvailable => switch ((installed, latest)) { + (final installed?, final latest?) => latest.version != installed.version, + _ => false, + }; + + bool _disposed = false; + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } + + /// Looks for the latest build, at most once an hour unless [force]d. + /// Offline, there is none to show. + Future check({bool force = false}) async { + final checkedAt = _checkedAt; + if (!force && + checkedAt != null && + _now().difference(checkedAt) < const Duration(hours: 1)) { + return; + } + _checkedAt = _now(); + try { + _latest = BaoBashRelease.parse(await host.fetchLatest(), host.arch!); + } on Object catch (error) { + debugPrint('BaoCode Bash: no latest.json: $error'); + } + _notify(); + } + + /// Installs the latest build, or updates to it. + Future install() async { + if (_busy) return; + _busy = true; + _progress = 0; + _error = null; + _notify(); + try { + if (_latest == null) await check(force: true); + final release = _latest; + if (release == null) { + throw StateError('dl.baocode.dev could not be reached'); + } + _installed = await host.install(release, (done) { + _progress = done; + _notify(); + }); + } on Object catch (error) { + _error = '$error'; + } finally { + _busy = false; + _progress = null; + _notify(); + } + } + + Future uninstall() async { + if (_busy) return; + _busy = true; + _error = null; + _notify(); + try { + await host.uninstall(); + } on Object catch (error) { + _error = '$error'; + } finally { + _installed = host.installed(); + _busy = false; + _notify(); + } + } + + // --- Whom to recommend it to ---------------------------------------------- + + static const storageKey = 'baoBash'; + static const newUserDays = 7; + static const newUserMessages = 5; + + /// What [firstSeen] is for an install that ran before it was kept. + static const _longAgo = '2000-01-01T00:00:00.000Z'; + + Map get _kept => switch (storage?.get(storageKey)) { + final Map map => { + for (final MapEntry(:key, :value) in map.entries) + if (key is String) key: value, + }, + _ => {}, + }; + + void _keep(Map kept) { + final storage = this.storage; + if (storage == null) return; + unawaited( + storage + .set(storageKey, kept) + .catchError((Object error) => debugPrint('$storageKey: $error')), + ); + } + + /// At the app's start, before the feature tips have: when the app first + /// ran here is now, unless it ran before (the tips kept the version that + /// ran last), long ago then. + void noteStart() { + final kept = _kept; + if (kept['firstSeen'] is String) return; + final ranBefore = switch (storage?.get(FeatureTipsController.storageKey)) { + {'lastVersion': String _} => true, + _ => false, + }; + kept['firstSeen'] = ranBefore ? _longAgo : _now().toUtc().toIso8601String(); + _keep(kept); + } + + /// The user sent a message: counted up to [newUserMessages]. + void countSent() { + final kept = _kept; + final sent = _sent(kept); + if (sent >= newUserMessages) return; + kept['sent'] = sent + 1; + _keep(kept); + if (sent + 1 == newUserMessages) _notify(); + } + + static int _sent(Map kept) => switch (kept['sent']) { + final int sent => sent, + _ => 0, + }; + + /// Whether the user is new here: the app first ran less than + /// [newUserDays] ago, or fewer than [newUserMessages] messages sent. + bool get newUser { + final kept = _kept; + final firstSeen = switch (kept['firstSeen']) { + final String at => DateTime.tryParse(at), + _ => null, + }; + return firstSeen == null || + _now().difference(firstSeen) < const Duration(days: newUserDays) || + _sent(kept) < newUserMessages; + } + + /// Whether the notice was put off for good. + bool get noticeDismissed => _kept['dismissed'] == true; + + void dismissNotice() { + _keep(_kept..['dismissed'] = true); + _notify(); + } + + /// Whether the settings dialog recommends it above every page. + bool get showsNotice => installed == null && !newUser && !noticeDismissed; +} diff --git a/lib/bash_exe/bao_bash_io.dart b/lib/bash_exe/bao_bash_io.dart new file mode 100644 index 000000000..acca49c87 --- /dev/null +++ b/lib/bash_exe/bao_bash_io.dart @@ -0,0 +1,163 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart' as crypto; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; + +import '../network/network_proxy_io.dart'; +import '../platform/data_dir.dart'; +import 'bao_bash.dart'; + +/// Windows': in the data directory's `tools/bash-exe/`. +BaoBashHost? baoBashHost() => Platform.isWindows + ? IoBaoBashHost(p.join(DataDirectory.current.path, 'tools', 'bash-exe')) + : null; + +/// BaoCode Bash in [root]: each version in a folder of its own +/// (`/bash.exe`, so that one an agent is running need not be +/// overwritten), and `installed.json` naming the one installed. +class IoBaoBashHost implements BaoBashHost { + IoBaoBashHost( + this.root, { + Map? environment, + HttpClient Function()? client, + this.timeout = const Duration(seconds: 30), + }) : _environment = environment ?? Platform.environment, + _client = client ?? _proxied; + + static HttpClient _proxied() => + HttpClient()..findProxy = NetworkProxy.instance.findProxy; + + final String root; + final Map _environment; + final HttpClient Function() _client; + + /// For connecting, and for a response that stops sending. + final Duration timeout; + + File get _record => File(p.join(root, 'installed.json')); + + String _executable(String version) => p.join(root, version, 'bash.exe'); + + /// An Arm machine's own, an x64 app under emulation there too. + @override + String? get arch { + final names = [ + _environment['PROCESSOR_ARCHITEW6432'], + _environment['PROCESSOR_ARCHITECTURE'], + ].whereType().map((name) => name.toUpperCase()); + if (names.contains('ARM64')) return 'arm64'; + if (names.contains('AMD64')) return 'x64'; + return null; + } + + @override + BaoBashInstall? installed() { + try { + final json = jsonDecode(_record.readAsStringSync()); + if (json case {'version': final String version}) { + final executable = _executable(version); + if (File(executable).existsSync()) { + return (version: version, executable: executable); + } + } + } on Object { + // None, or not one this wrote. + } + return null; + } + + @override + Future fetchLatest() async { + final client = _client()..connectionTimeout = timeout; + try { + final request = await client.getUrl(BaoBashRelease.latestUrl); + final response = await request.close().timeout(timeout); + if (response.statusCode != HttpStatus.ok) { + throw HttpException('${response.statusCode}', uri: request.uri); + } + return jsonDecode( + await response.transform(utf8.decoder).join().timeout(timeout), + ); + } finally { + client.close(); + } + } + + @override + Future install( + BaoBashRelease release, + void Function(double done) progress, + ) async { + final gzipped = await _download(release, progress); + if (gzipped.length != release.size || + '${crypto.sha256.convert(gzipped)}' != release.sha256) { + throw StateError( + 'What was downloaded is not the build named (${release.url})', + ); + } + final exe = gzip.decode(gzipped); + if (release.unpacked case final unpacked? when exe.length != unpacked) { + throw StateError('The build downloaded does not unpack whole'); + } + final executable = _executable(release.version); + final file = File(executable); + await file.parent.create(recursive: true); + final part = File('$executable.part'); + await part.writeAsBytes(exe, flush: true); + if (await file.exists()) await file.delete(); + await part.rename(executable); + await _record.writeAsString( + jsonEncode({'version': release.version}), + flush: true, + ); + await _prune(keep: release.version); + return (version: release.version, executable: executable); + } + + Future> _download( + BaoBashRelease release, + void Function(double done) progress, + ) async { + final client = _client()..connectionTimeout = timeout; + try { + final request = await client.getUrl(release.url); + final response = await request.close().timeout(timeout); + if (response.statusCode != HttpStatus.ok) { + throw HttpException('${response.statusCode}', uri: release.url); + } + final bytes = BytesBuilder(copy: false); + await for (final chunk in response.timeout(timeout)) { + bytes.add(chunk); + progress((bytes.length / release.size).clamp(0, 1)); + } + return bytes.takeBytes(); + } finally { + client.close(); + } + } + + @override + Future uninstall() async { + if (await _record.exists()) await _record.delete(); + await _prune(); + } + + /// Removes the versions but [keep]; one an agent is running stays, to + /// go the next time. + Future _prune({String? keep}) async { + final dir = Directory(root); + if (!await dir.exists()) return; + await for (final entry in dir.list()) { + if (entry is! Directory || p.basename(entry.path) == keep) continue; + try { + await entry.delete(recursive: true); + } on FileSystemException catch (error) { + debugPrint('BaoCode Bash: ${entry.path} stays: ${error.message}'); + } + } + } +} diff --git a/lib/bash_exe/bao_bash_stub.dart b/lib/bash_exe/bao_bash_stub.dart new file mode 100644 index 000000000..beb0bc89f --- /dev/null +++ b/lib/bash_exe/bao_bash_stub.dart @@ -0,0 +1,4 @@ +import 'bao_bash.dart'; + +/// None on the web. +BaoBashHost? baoBashHost() => null; diff --git a/lib/bash_exe/bao_bash_view.dart b/lib/bash_exe/bao_bash_view.dart new file mode 100644 index 000000000..0c262d6f3 --- /dev/null +++ b/lib/bash_exe/bao_bash_view.dart @@ -0,0 +1,192 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import '../ide/ide_button.dart'; +import '../kernel/claude_code/claude_core_setting.dart'; +import '../l10n/l10n.dart'; +import '../settings/pages/settings_widgets.dart'; +import '../theme/codicons.dart'; +import '../theme/workbench_theme.dart' show themeColors; +import 'bao_bash.dart'; + +/// [size] bytes, as a download's size reads: `13 MB`. +String _megabytes(int size) => '${(size / (1024 * 1024)).round()} MB'; + +/// Settings → General → Command Line: BaoCode Bash, whether and which is +/// installed, and the buttons to install, update or remove it. +class BaoBashSetting extends StatefulWidget { + const BaoBashSetting({super.key, required this.bash}); + + final BaoBash bash; + + @override + State createState() => _BaoBashSettingState(); +} + +class _BaoBashSettingState extends State { + @override + void initState() { + super.initState(); + unawaited(widget.bash.check()); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final bash = widget.bash; + return ListenableBuilder( + listenable: bash, + builder: (context, _) { + final installed = bash.installed; + final latest = bash.latest; + final progress = bash.progress; + final error = bash.error; + return SettingsRow( + label: installed == null ? l10n.baoBashRecommended : 'BaoCode Bash', + description: l10n.baoBashDescription, + below: [ + Text(switch ((installed, progress)) { + (_, final progress?) => l10n.baoBashDownloading( + (progress * 100).round(), + ), + (final installed?, _) when bash.updateAvailable => + '${l10n.baoBashInstalled(installed.version)} ' + '${l10n.baoBashUpdateAvailable(latest!.version)}', + (final installed?, _) => l10n.baoBashInstalled(installed.version), + (null, _) => l10n.baoBashNotInstalled, + }, style: SettingsText.description), + if (error != null) + Text( + l10n.baoBashFailed(error), + style: SettingsText.description.copyWith( + color: themeColors['errorForeground'], + ), + ), + ], + trailing: SettingsButtons( + children: [ + if (installed == null) + IdeButton( + label: switch (latest) { + final latest? => l10n.baoBashInstallSize( + _megabytes(latest.size), + ), + null => l10n.baoBashInstall, + }, + onPressed: bash.busy ? null : () => unawaited(bash.install()), + ) + else ...[ + if (bash.updateAvailable) + IdeButton( + label: l10n.baoBashUpdate, + onPressed: bash.busy + ? null + : () => unawaited(bash.install()), + ), + IdeButton( + label: l10n.baoBashUninstall, + secondary: true, + onPressed: bash.busy + ? null + : () => unawaited(bash.uninstall()), + ), + ], + ], + ), + ); + }, + ); + } +} + +/// Above every page of the settings dialog: BaoCode Bash recommended, as +/// [BaoBash.showsNotice] says, to those whose agents would run it (the +/// built-in core's: Claude Code's CLI is not given it yet). Install, or +/// Not Now for good; the Command Line setting stays. +class BaoBashNotice extends StatelessWidget { + const BaoBashNotice({super.key, required this.bash, this.core}); + + final BaoBash bash; + + /// The core new sessions run on; the setting's by default. + final ClaudeCore Function()? core; + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: bash, + builder: (context, _) { + if (!bash.showsNotice || + (core ?? ClaudeCore.current)() != ClaudeCore.builtin) { + return const SizedBox.shrink(); + } + final l10n = context.l10n; + final colors = themeColors; + final progress = bash.progress; + final error = bash.error; + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Container( + padding: const EdgeInsets.fromLTRB(10, 6, 6, 6), + decoration: BoxDecoration( + color: colors['inputValidation.infoBackground'], + border: Border.all(color: colors['inputValidation.infoBorder']), + borderRadius: BorderRadius.circular(4), + ), + child: Row( + children: [ + Icon( + Codicons.terminal, + size: 14, + color: colors['editorInfo.foreground'], + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + l10n.baoBashNoticeTitle, + style: TextStyle( + color: colors['foreground'], + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + Text( + switch ((progress, error)) { + (final progress?, _) => l10n.baoBashDownloading( + (progress * 100).round(), + ), + (null, final error?) => l10n.baoBashFailed(error), + _ => l10n.baoBashNoticeBody, + }, + style: TextStyle( + color: error != null && progress == null + ? colors['errorForeground'] + : colors['descriptionForeground'], + fontSize: 12, + ), + ), + ], + ), + ), + const SizedBox(width: 8), + IdeButton( + label: l10n.baoBashNoticeLater, + secondary: true, + onPressed: bash.busy ? null : bash.dismissNotice, + ), + const SizedBox(width: 6), + IdeButton( + label: l10n.baoBashInstall, + onPressed: bash.busy ? null : () => unawaited(bash.install()), + ), + ], + ), + ), + ); + }, + ); +} diff --git a/lib/chat/chat_session.dart b/lib/chat/chat_session.dart index 06539ed48..87c90f88e 100644 --- a/lib/chat/chat_session.dart +++ b/lib/chat/chat_session.dart @@ -1133,6 +1133,7 @@ class ChatSession extends ChangeNotifier implements ChatFeed { List notes = const [], }) { if (message.isEmpty || !canSend) return; + if (from != null) userSent?.call(); final turn = KernelTurn( id: newTurnId(), // Pastes too long to send, kept in files the agent reads; a remote @@ -1153,6 +1154,10 @@ class ChatSession extends ChangeNotifier implements ChatFeed { _kernel.send(turn); } + /// Told of each message the user sends (not the app): main() counts + /// them for [BaoBash.newUser]. + static void Function()? userSent; + static final _random = math.Random.secure(); /// A random UUID (v4): kernels may use it as the message's id. diff --git a/lib/kernel/claude_code/dart_core_transport_io.dart b/lib/kernel/claude_code/dart_core_transport_io.dart index 81a09647e..d379222df 100644 --- a/lib/kernel/claude_code/dart_core_transport_io.dart +++ b/lib/kernel/claude_code/dart_core_transport_io.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'package:bao_agent/bao_agent.dart'; +import '../../bash_exe/bao_bash.dart'; import '../../models/launch_environment.dart'; import '../../network/network_proxy_io.dart'; import 'claude_code_transport.dart'; @@ -61,6 +62,10 @@ class DartCoreTransport implements ClaudeCodeTransport { ..addAll(ClaudeLaunch.environment) ..addAll(ClaudeEnvironment.stateDirectory(base)); await CoreRipgrep.addTo(environment); + // Its commands run with BaoCode Bash, where it is installed (Windows). + if (BaoBash.executable case final bash?) { + environment[Shell.baoBashVariable] = bash; + } final instructions = launch.instructions; return EngineOptions( cwd: launch.cwd, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 27ecfa4c7..fe127b13c 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -8925,5 +8925,55 @@ "settingsTransferFailed": "Not done: {error}", "@settingsTransferFailed": {"placeholders": {"error": {"type": "String"}}}, "generalSettingsSessionTools": "Agents can coordinate other conversations", - "generalSettingsSessionToolsDescription": "An agent can list your other conversations, read where they stand without waking them, hand them work (resumed if stopped, queued if busy) and wait for them. For one conversation that coordinates the others; agents started after the change have it." + "generalSettingsSessionToolsDescription": "An agent can list your other conversations, read where they stand without waking them, hand them work (resumed if stopped, queued if busy) and wait for them. For one conversation that coordinates the others; agents started after the change have it.", + "generalSettingsCommandLine": "Command Line", + "baoBashRecommended": "BaoCode Bash (recommended)", + "baoBashDescription": "A complete bash for agents on Windows: rg, grep, sed, awk, find, jq, tar and some 80 other common commands built in, no Git for Windows needed, and C:\\ and /c/ paths alike. The built-in core runs its agents' commands with it.", + "baoBashNotInstalled": "Not installed: agents run commands with Git Bash, or with cmd.exe where there is none.", + "baoBashInstalled": "Version {version} installed.", + "@baoBashInstalled": { + "placeholders": { + "version": { + "type": "String" + } + } + }, + "baoBashUpdateAvailable": "Version {version} is out.", + "@baoBashUpdateAvailable": { + "placeholders": { + "version": { + "type": "String" + } + } + }, + "baoBashDownloading": "Downloading… {percent}%", + "@baoBashDownloading": { + "placeholders": { + "percent": { + "type": "int" + } + } + }, + "baoBashInstall": "Install", + "baoBashInstallSize": "Install ({size})", + "@baoBashInstallSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, + "baoBashUpdate": "Update", + "baoBashUninstall": "Uninstall", + "baoBashFailed": "Could not install it: {error}", + "@baoBashFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "baoBashNoticeTitle": "On Windows, BaoCode Bash is recommended", + "baoBashNoticeBody": "Agents run commands more reliably with it. It brings bash with rg, grep, sed, awk, find, jq, tar and some 80 other common commands, no Git for Windows needed; it takes C:\\ and /c/ paths alike, so commands no longer fail on the differences between cmd and PowerShell.", + "baoBashNoticeLater": "Not Now" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 126505807..640276dec 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -22812,6 +22812,96 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'An agent can list your other conversations, read where they stand without waking them, hand them work (resumed if stopped, queued if busy) and wait for them. For one conversation that coordinates the others; agents started after the change have it.'** String get generalSettingsSessionToolsDescription; + + /// No description provided for @generalSettingsCommandLine. + /// + /// In en, this message translates to: + /// **'Command Line'** + String get generalSettingsCommandLine; + + /// No description provided for @baoBashRecommended. + /// + /// In en, this message translates to: + /// **'BaoCode Bash (recommended)'** + String get baoBashRecommended; + + /// No description provided for @baoBashDescription. + /// + /// In en, this message translates to: + /// **'A complete bash for agents on Windows: rg, grep, sed, awk, find, jq, tar and some 80 other common commands built in, no Git for Windows needed, and C:\\ and /c/ paths alike. The built-in core runs its agents\' commands with it.'** + String get baoBashDescription; + + /// No description provided for @baoBashNotInstalled. + /// + /// In en, this message translates to: + /// **'Not installed: agents run commands with Git Bash, or with cmd.exe where there is none.'** + String get baoBashNotInstalled; + + /// No description provided for @baoBashInstalled. + /// + /// In en, this message translates to: + /// **'Version {version} installed.'** + String baoBashInstalled(String version); + + /// No description provided for @baoBashUpdateAvailable. + /// + /// In en, this message translates to: + /// **'Version {version} is out.'** + String baoBashUpdateAvailable(String version); + + /// No description provided for @baoBashDownloading. + /// + /// In en, this message translates to: + /// **'Downloading… {percent}%'** + String baoBashDownloading(int percent); + + /// No description provided for @baoBashInstall. + /// + /// In en, this message translates to: + /// **'Install'** + String get baoBashInstall; + + /// No description provided for @baoBashInstallSize. + /// + /// In en, this message translates to: + /// **'Install ({size})'** + String baoBashInstallSize(String size); + + /// No description provided for @baoBashUpdate. + /// + /// In en, this message translates to: + /// **'Update'** + String get baoBashUpdate; + + /// No description provided for @baoBashUninstall. + /// + /// In en, this message translates to: + /// **'Uninstall'** + String get baoBashUninstall; + + /// No description provided for @baoBashFailed. + /// + /// In en, this message translates to: + /// **'Could not install it: {error}'** + String baoBashFailed(String error); + + /// No description provided for @baoBashNoticeTitle. + /// + /// In en, this message translates to: + /// **'On Windows, BaoCode Bash is recommended'** + String get baoBashNoticeTitle; + + /// No description provided for @baoBashNoticeBody. + /// + /// In en, this message translates to: + /// **'Agents run commands more reliably with it. It brings bash with rg, grep, sed, awk, find, jq, tar and some 80 other common commands, no Git for Windows needed; it takes C:\\ and /c/ paths alike, so commands no longer fail on the differences between cmd and PowerShell.'** + String get baoBashNoticeBody; + + /// No description provided for @baoBashNoticeLater. + /// + /// In en, this message translates to: + /// **'Not Now'** + String get baoBashNoticeLater; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 0c6a4b006..885ca1be5 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -14073,4 +14073,62 @@ class AppLocalizationsEn extends AppLocalizations { @override String get generalSettingsSessionToolsDescription => 'An agent can list your other conversations, read where they stand without waking them, hand them work (resumed if stopped, queued if busy) and wait for them. For one conversation that coordinates the others; agents started after the change have it.'; + + @override + String get generalSettingsCommandLine => 'Command Line'; + + @override + String get baoBashRecommended => 'BaoCode Bash (recommended)'; + + @override + String get baoBashDescription => + 'A complete bash for agents on Windows: rg, grep, sed, awk, find, jq, tar and some 80 other common commands built in, no Git for Windows needed, and C:\\ and /c/ paths alike. The built-in core runs its agents\' commands with it.'; + + @override + String get baoBashNotInstalled => + 'Not installed: agents run commands with Git Bash, or with cmd.exe where there is none.'; + + @override + String baoBashInstalled(String version) { + return 'Version $version installed.'; + } + + @override + String baoBashUpdateAvailable(String version) { + return 'Version $version is out.'; + } + + @override + String baoBashDownloading(int percent) { + return 'Downloading… $percent%'; + } + + @override + String get baoBashInstall => 'Install'; + + @override + String baoBashInstallSize(String size) { + return 'Install ($size)'; + } + + @override + String get baoBashUpdate => 'Update'; + + @override + String get baoBashUninstall => 'Uninstall'; + + @override + String baoBashFailed(String error) { + return 'Could not install it: $error'; + } + + @override + String get baoBashNoticeTitle => 'On Windows, BaoCode Bash is recommended'; + + @override + String get baoBashNoticeBody => + 'Agents run commands more reliably with it. It brings bash with rg, grep, sed, awk, find, jq, tar and some 80 other common commands, no Git for Windows needed; it takes C:\\ and /c/ paths alike, so commands no longer fail on the differences between cmd and PowerShell.'; + + @override + String get baoBashNoticeLater => 'Not Now'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 983d5ba03..4fd068205 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -13271,4 +13271,62 @@ class AppLocalizationsZh extends AppLocalizations { @override String get generalSettingsSessionToolsDescription => 'Agent 能列出你的其他对话、在不唤醒的情况下查看进展、给它们派活(没在运行的会恢复,正忙的会排队)并等待结果。适合用一个对话统筹其他对话;改动后新启动的 Agent 才有。'; + + @override + String get generalSettingsCommandLine => '命令行'; + + @override + String get baoBashRecommended => 'BaoCode Bash(推荐)'; + + @override + String get baoBashDescription => + '让智能体在 Windows 上用上完整的 bash:自带 rg、grep、sed、awk、find、jq、tar 等八十多个常用命令,不需要装 Git for Windows;C:\\ 和 /c/ 两种路径都认。内置内核会用它运行命令。'; + + @override + String get baoBashNotInstalled => + '未安装:智能体现在用 Git Bash 运行命令,没装 Git Bash 时用 cmd.exe。'; + + @override + String baoBashInstalled(String version) { + return '已安装 $version。'; + } + + @override + String baoBashUpdateAvailable(String version) { + return '有新版本 $version。'; + } + + @override + String baoBashDownloading(int percent) { + return '正在下载… $percent%'; + } + + @override + String get baoBashInstall => '安装'; + + @override + String baoBashInstallSize(String size) { + return '安装($size)'; + } + + @override + String get baoBashUpdate => '更新'; + + @override + String get baoBashUninstall => '卸载'; + + @override + String baoBashFailed(String error) { + return '安装失败:$error'; + } + + @override + String get baoBashNoticeTitle => '在 Windows 上,推荐安装 BaoCode Bash'; + + @override + String get baoBashNoticeBody => + '智能体运行命令会更稳。它自带 bash 和 rg、grep、sed、awk、find、jq、tar 等八十多个常用命令,不需要装 Git for Windows;C:\\ 和 /c/ 两种路径都认,不会再因为 cmd 和 PowerShell 写法不同而出错。'; + + @override + String get baoBashNoticeLater => '暂不'; } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index a0feeaf7b..f37eadc8a 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3792,5 +3792,20 @@ "settingsTransferNotAFile": "这不是 BaoCode 导出的设置文件。", "settingsTransferFailed": "没能完成:{error}", "generalSettingsSessionTools": "Agent 可以统筹其他对话", - "generalSettingsSessionToolsDescription": "Agent 能列出你的其他对话、在不唤醒的情况下查看进展、给它们派活(没在运行的会恢复,正忙的会排队)并等待结果。适合用一个对话统筹其他对话;改动后新启动的 Agent 才有。" + "generalSettingsSessionToolsDescription": "Agent 能列出你的其他对话、在不唤醒的情况下查看进展、给它们派活(没在运行的会恢复,正忙的会排队)并等待结果。适合用一个对话统筹其他对话;改动后新启动的 Agent 才有。", + "generalSettingsCommandLine": "命令行", + "baoBashRecommended": "BaoCode Bash(推荐)", + "baoBashDescription": "让智能体在 Windows 上用上完整的 bash:自带 rg、grep、sed、awk、find、jq、tar 等八十多个常用命令,不需要装 Git for Windows;C:\\ 和 /c/ 两种路径都认。内置内核会用它运行命令。", + "baoBashNotInstalled": "未安装:智能体现在用 Git Bash 运行命令,没装 Git Bash 时用 cmd.exe。", + "baoBashInstalled": "已安装 {version}。", + "baoBashUpdateAvailable": "有新版本 {version}。", + "baoBashDownloading": "正在下载… {percent}%", + "baoBashInstall": "安装", + "baoBashInstallSize": "安装({size})", + "baoBashUpdate": "更新", + "baoBashUninstall": "卸载", + "baoBashFailed": "安装失败:{error}", + "baoBashNoticeTitle": "在 Windows 上,推荐安装 BaoCode Bash", + "baoBashNoticeBody": "智能体运行命令会更稳。它自带 bash 和 rg、grep、sed、awk、find、jq、tar 等八十多个常用命令,不需要装 Git for Windows;C:\\ 和 /c/ 两种路径都认,不会再因为 cmd 和 PowerShell 写法不同而出错。", + "baoBashNoticeLater": "暂不" } diff --git a/lib/main.dart b/lib/main.dart index 2a5b32ed7..b6b790dd6 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -16,10 +16,12 @@ import 'package:bao_editor/monaco/flutter/language_assets.dart'; import 'base/quiet_view.dart'; import 'base/smooth_scroll.dart' show BaoScrollBehavior; +import 'bash_exe/bao_bash.dart'; import 'bots/bots.dart'; import 'browser/browser_bridge.dart'; import 'browser/browser_tools.dart' show BrowserHistory; import 'chat/composer/composer_files.dart' show ComposerFile, pastedAsPicture; +import 'chat/chat_session.dart'; import 'chat/chat_width.dart'; import 'chat/reply_scroll.dart'; import 'chat/edit_detail.dart'; @@ -418,6 +420,10 @@ Future main(List arguments) async { link: link, customizations: customizations, ); + // Before the feature tips start: they tell it whether the app ran + // here before. + BaoBash.current = settings.bash?..noteStart(); + ChatSession.userSent = BaoBash.current?.countSent; _startTelemetry(files, link); } // The theme extensions (lib/extensions/): color and file icon themes diff --git a/lib/settings/app_settings.dart b/lib/settings/app_settings.dart index 000e64858..08d95bb2f 100644 --- a/lib/settings/app_settings.dart +++ b/lib/settings/app_settings.dart @@ -2,6 +2,8 @@ import 'dart:async'; import 'package:flutter/widgets.dart'; +import '../bash_exe/bao_bash.dart'; +import '../bash_exe/bao_bash_view.dart'; import '../channel/channel_gate.dart'; import '../channel/channel_setup.dart' show ChannelSetup; import '../diagnostics/diagnostics_upload.dart'; @@ -118,6 +120,13 @@ class AppSettings { null => null, }; + /// BaoCode Bash, where it is offered (Windows, with settings files); + /// main() makes it the app's ([BaoBash.current]). + late final BaoBash? bash = switch (files?.storage) { + final storage? => BaoBash.forPlatform(_TipStorage(storage)), + null => null, + }; + /// Writes the keyboard page's changes into keybindings.json: one for /// the app, so they are made one at a time. late final KeybindingsEditingService editing = KeybindingsEditingService( @@ -137,12 +146,19 @@ class AppSettings { ]; } - /// What the settings dialog says above every page: the browser's - /// debugging history grown large. + /// What the settings dialog says above every page: BaoCode Bash + /// recommended, on Windows; the browser's debugging history grown large. Widget buildNotice( BuildContext context, void Function(SettingsSection section) open, - ) => BrowserHistoryNotice(open: () => open(SettingsSection.browser)); + ) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (bash case final bash?) BaoBashNotice(bash: bash), + BrowserHistoryNotice(open: () => open(SettingsSection.browser)), + ], + ); /// [section]'s page of the settings dialog. Widget buildPage(BuildContext context, SettingsSection section) { @@ -152,6 +168,7 @@ class AppSettings { settings: files?.settings, tips: tips, claudeStatus: claudeStatus, + bash: bash, ); case SettingsSection.appearance: final themes = WorkbenchThemeService.instance; diff --git a/lib/settings/pages/general_page.dart b/lib/settings/pages/general_page.dart index ace031704..f7725ad7b 100644 --- a/lib/settings/pages/general_page.dart +++ b/lib/settings/pages/general_page.dart @@ -3,6 +3,8 @@ import 'dart:async'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; +import '../../bash_exe/bao_bash.dart'; +import '../../bash_exe/bao_bash_view.dart'; import '../../ide/explorer_excludes.dart'; import '../../ide/ide_button.dart'; import '../../ide/ide_menu.dart'; @@ -39,8 +41,7 @@ import 'settings_widgets.dart'; /// (`chat.promptSuggestions`), whether the composer has its Polish button /// (`chat.composer.polish`), whether the turn under way shows its time, /// speed and tokens (`chat.liveTurnStats`), the Claude Code to run -/// (`claudeCode.path`), -/// the `code` shell command, and Open with BaoCode in Finder's or +/// (`claudeCode.path`), BaoCode Bash on Windows, the `code` shell command, and Open with BaoCode in Finder's or /// Explorer's context menu. A choice is written at once; the default is not /// written. class GeneralSettingsPage extends StatelessWidget { @@ -49,6 +50,7 @@ class GeneralSettingsPage extends StatelessWidget { this.settings, this.tips, this.claudeStatus, + this.bash, }); /// settings.json; none under test, where choices are not kept. @@ -58,6 +60,9 @@ class GeneralSettingsPage extends StatelessWidget { /// test and on the web, where the path is not shown. final Future Function()? claudeStatus; + /// BaoCode Bash, where it is offered (Windows); none under test. + final BaoBash? bash; + /// The feature tips: those not on yet are listed first. final FeatureTipsController? tips; @@ -444,6 +449,13 @@ class GeneralSettingsPage extends StatelessWidget { ), ], ), + if (bash case final bash?) + SettingsGroup( + title: l10n.generalSettingsCommandLine, + children: [ + SettingsCard(children: [BaoBashSetting(bash: bash)]), + ], + ), SettingsGroup( title: l10n.generalSettingsWindows, children: _windowRows(context), diff --git a/packages/bao_agent/lib/bao_agent.dart b/packages/bao_agent/lib/bao_agent.dart index 1a45953b3..8b78b96c8 100644 --- a/packages/bao_agent/lib/bao_agent.dart +++ b/packages/bao_agent/lib/bao_agent.dart @@ -18,4 +18,5 @@ export 'src/engine/isolate.dart' show AgentIsolate; export 'src/engine/session.dart' show EngineOptions, MissingCredentials; export 'src/engine/session_store.dart' show agentVersion; export 'src/tools/file_index.dart' show FileIndex; +export 'src/util/processes.dart' show Shell; export 'src/util/cancel.dart' show CancelToken, Cancelled; diff --git a/packages/bao_agent/lib/src/engine/context.dart b/packages/bao_agent/lib/src/engine/context.dart index 50810ac53..6d9f31896 100644 --- a/packages/bao_agent/lib/src/engine/context.dart +++ b/packages/bao_agent/lib/src/engine/context.dart @@ -174,10 +174,14 @@ class SessionContext { static String _date(DateTime now) => '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}'; + /// The user's shell, as `SHELL` names it; else (Windows) the one + /// commands run in. String get _shell { final shell = session.environment['SHELL']; - if (shell == null || shell.isEmpty) return 'unknown'; - return p.basename(shell); + if (shell != null && shell.isNotEmpty) return p.basename(shell); + final runs = session.shell; + if (runs.baoBash) return 'bash (BaoCode Bash)'; + return runs.posix ? 'bash' : 'cmd.exe'; } String _environment(String model) { diff --git a/packages/bao_agent/lib/src/tools/bash_tool.dart b/packages/bao_agent/lib/src/tools/bash_tool.dart index 6e387d09c..d0d2f675e 100644 --- a/packages/bao_agent/lib/src/tools/bash_tool.dart +++ b/packages/bao_agent/lib/src/tools/bash_tool.dart @@ -34,7 +34,7 @@ class BashTool extends Tool { - The shell starts where the last command left it, but give absolute paths where you can: a `cd` inside a compound command may need the user's say-so. Variables and functions do not carry over from call to call; the shell is set up from the user's profile. - Do not use it to read or change files (cat, head, tail, sed, awk, echo): Read, Edit and Write do that better, and the user can follow them. Use it for that only when nothing else will do, or the user asked for it. -- ${_search(session)} Keep a search narrow (a folder, a file type) and its output short (`-l`, `| head`). +${_shellNote(session)}- ${_search(session)} Keep a search narrow (a folder, a file type) and its output short (`-l`, `| head`). - What a command prints is shown to you, not always to the user: say what matters in your reply. - `timeout` is in milliseconds: ${defaultTimeout.inMilliseconds} unless given, at most ${maxTimeout.inMilliseconds} in the foreground. - `run_in_background` starts it detached: it runs on across turns, and you are woken when it ends. `timeout` then bounds how long it may run (${defaultBackgroundTimeout.inMilliseconds} unless given, at most ${maxBackgroundTimeout.inMilliseconds}): at that limit it is stopped, and you are told. It needs no `&`. @@ -45,12 +45,18 @@ class BashTool extends Tool { - Make commits and push them only when told to; on the default branch, start a branch for them first. - End commit messages and pull request descriptions with the attribution lines the conversation gives in a , when it gives any.'''; + /// What the shell is, where it is not what a model expects of the + /// platform: BaoCode Bash on Windows. + static String _shellNote(AgentSession session) => session.shell.baoBash + ? '- The shell is bash (BaoCode Bash), with `rg`, `grep`, `sed`, `awk`, `find`, `xargs`, `jq`, `tar` and the other usual Unix tools built in. Write paths as `C:\\x`, `C:/x` or `/c/x`: all name the same file. Windows programs on the PATH run as usual.\n' + : ''; + /// How to search, with what this machine has: a model told of `rg` /// where there is none spends a call finding that out, and one left to /// cmd.exe's own writes scripts to search with. static String _search(AgentSession session) { final posix = session.shell.posix; - if (session.fileIndex.ripgrep != null) { + if (session.shell.baoBash || session.fileIndex.ripgrep != null) { return posix ? "To find files and what is in them, search here: `rg` (or `grep -rn`) for text, `rg --files -g ''` (or `find`) for names. Search rather than write a script to." : "To find files and what is in them, search here: `rg` for text, `rg --files -g \"\"` for names (the shell is cmd.exe: double quotes). Search rather than write a script to."; diff --git a/packages/bao_agent/lib/src/util/processes.dart b/packages/bao_agent/lib/src/util/processes.dart index c0c1f9024..5a8102020 100644 --- a/packages/bao_agent/lib/src/util/processes.dart +++ b/packages/bao_agent/lib/src/util/processes.dart @@ -90,15 +90,26 @@ Future> _descendants(int pid) async { } /// The shell commands are run in: the user's, when it is bash or zsh; -/// else bash; on Windows, Git's bash where it is installed. +/// else bash; on Windows, the one set by `CLAUDE_CODE_GIT_BASH_PATH`, else +/// BaoCode Bash where the app installed it ([baoBashVariable]), else Git's +/// bash where it is installed, else cmd.exe. class Shell { - const Shell(this.executable, {this.posix = true}); + const Shell(this.executable, {this.posix = true, this.baoBash = false}); + + /// The variable the app names BaoCode Bash's `bash.exe` in + /// (github.com/baocode-dev/bash-exe): bash 5.3 with `rg`, `grep`, `sed`, + /// `awk`, `find`, `jq` and the like built in, that takes `C:\x` and + /// `/c/x` alike. + static const baoBashVariable = 'BAOCODE_BASH'; final String executable; /// Whether it takes POSIX shell commands (not cmd.exe). final bool posix; + /// Whether it is BaoCode Bash, its tools there whatever is installed. + final bool baoBash; + /// The shell for [environment]'s user, on Windows when [windows] (where /// this runs, when not given); [exists] says whether a file is there. static Shell find( @@ -109,8 +120,14 @@ class Shell { exists ??= (path) => File(path).existsSync(); if (windows ?? Platform.isWindows) { final path = p.windows; + if (environment['CLAUDE_CODE_GIT_BASH_PATH'] case final set? + when exists(set)) { + return Shell(set); + } + if (environment[baoBashVariable] case final bao? when exists(bao)) { + return Shell(bao, baoBash: true); + } final candidates = [ - environment['CLAUDE_CODE_GIT_BASH_PATH'], // Git's own, by the git on the PATH (`Git\cmd\git.exe`). for (final dir in (environment['PATH'] ?? environment['Path'] ?? '').split(';')) @@ -121,7 +138,7 @@ class Shell { if (environment['LOCALAPPDATA'] case final local?) path.join(local, 'Programs', 'Git', 'bin', 'bash.exe'), ]; - for (final candidate in candidates.whereType()) { + for (final candidate in candidates) { if (exists(candidate)) return Shell(candidate); } return Shell(environment['COMSPEC'] ?? 'cmd.exe', posix: false); diff --git a/packages/bao_agent/test/units/utils_test.dart b/packages/bao_agent/test/units/utils_test.dart index 1aee8d153..fe815923e 100644 --- a/packages/bao_agent/test/units/utils_test.dart +++ b/packages/bao_agent/test/units/utils_test.dart @@ -426,6 +426,25 @@ void main() { expect(windows({}, {}).executable, 'cmd.exe'); }); + test('on Windows: BaoCode Bash, where the app installed it, before ' + 'Git\'s; the one set before both', () { + const bao = + r'C:\Users\me\AppData\Roaming\BaoCode\tools\bash-exe\bash.exe'; + const git = r'C:\Program Files\Git\bin\bash.exe'; + final found = windows({Shell.baoBashVariable: bao}, {bao, git}); + expect((found.executable, found.posix, found.baoBash), (bao, true, true)); + // Uninstalled since. + expect(windows({Shell.baoBashVariable: bao}, {git}).executable, git); + expect(windows({Shell.baoBashVariable: bao}, {git}).baoBash, isFalse); + expect( + windows( + {Shell.baoBashVariable: bao, 'CLAUDE_CODE_GIT_BASH_PATH': git}, + {bao, git}, + ).executable, + git, + ); + }); + test('elsewhere: the user\'s bash or zsh, else bash, else sh', () { Shell find(Map env, Set files) => Shell.find(env, windows: false, exists: files.contains); diff --git a/test/bash_exe/bao_bash_test.dart b/test/bash_exe/bao_bash_test.dart new file mode 100644 index 000000000..2b71a91c8 --- /dev/null +++ b/test/bash_exe/bao_bash_test.dart @@ -0,0 +1,374 @@ +// BaoCode Bash, offered on Windows: the build latest.json names, whom the +// settings dialog recommends it to, installing it, and its Settings → General +// row and notice. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:baocode/bash_exe/bao_bash.dart'; +import 'package:baocode/bash_exe/bao_bash_io.dart'; +import 'package:baocode/bash_exe/bao_bash_view.dart'; +import 'package:baocode/kernel/claude_code/claude_core_setting.dart'; +import 'package:baocode/tips/feature_tip.dart'; +import 'package:baocode/tips/feature_tips_controller.dart'; +import 'package:crypto/crypto.dart' as crypto; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +class _Storage implements TipStorage { + final Map values = {}; + + @override + Object? get(String key) => values[key]; + + @override + Future set(String key, Object? value) async => + values[key] = jsonDecode(jsonEncode(value)); +} + +class _Host implements BaoBashHost { + _Host({this.latest}); + + Object? latest; + BaoBashInstall? kept; + Completer? downloading; + + @override + String? get arch => 'x64'; + + @override + BaoBashInstall? installed() => kept; + + @override + Future fetchLatest() async { + if (latest == null) throw const SocketException('offline'); + return latest; + } + + @override + Future install( + BaoBashRelease release, + void Function(double done) progress, + ) async { + progress(0.5); + await downloading?.future; + return kept = ( + version: release.version, + executable: + r'C:\data\tools\bash-exe\' + '${release.version}\\bash.exe', + ); + } + + @override + Future uninstall() async => kept = null; +} + +Map _latest(String version) => { + 'version': version, + 'commit': 'abc', + 'files': { + 'x64': { + 'url': 'https://dl.baocode.dev/tools/bash-exe/$version/x64.exe.gz', + 'size': 13 * 1024 * 1024, + 'sha256': 'AB' * 32, + 'unpacked': 31 * 1024 * 1024, + }, + }, +}; + +void main() { + test('the build latest.json names for the architecture', () { + final release = BaoBashRelease.parse(_latest('0.2.0'), 'x64')!; + expect(release.version, '0.2.0'); + expect(release.sha256, 'ab' * 32); + expect(release.unpacked, 31 * 1024 * 1024); + expect(BaoBashRelease.parse(_latest('0.2.0'), 'arm64'), isNull); + expect(BaoBashRelease.parse(_latest('../x'), 'x64'), isNull); + expect(BaoBashRelease.parse('nonsense', 'x64'), isNull); + }); + + group('recommended to', () { + var now = DateTime.utc(2026, 11, 13); + BaoBash make(_Storage storage) => + BaoBash(host: _Host(), storage: storage, now: () => now); + + setUp(() => now = DateTime.utc(2026, 11, 13)); + + test('one who ran the app before, once they have sent five messages', () { + final storage = _Storage() + ..values[FeatureTipsController.storageKey] = {'lastVersion': '1.0.0'}; + final bash = make(storage)..noteStart(); + expect(bash.newUser, isTrue); + for (var i = 0; i < 4; i++) { + bash.countSent(); + } + expect(bash.newUser, isTrue); + bash.countSent(); + expect(bash.newUser, isFalse); + expect(bash.showsNotice, isTrue); + // Kept: the next run knows. + expect(make(storage).showsNotice, isTrue); + + bash.dismissNotice(); + expect(bash.showsNotice, isFalse); + expect(make(storage).showsNotice, isFalse); + }); + + test('a new install, a week on', () { + final storage = _Storage(); + final bash = make(storage)..noteStart(); + for (var i = 0; i < 10; i++) { + bash.countSent(); + } + expect(bash.newUser, isTrue); + now = now.add(const Duration(days: 6)); + expect(bash.newUser, isTrue); + now = now.add(const Duration(days: 2)); + expect(bash.newUser, isFalse); + // The first run is kept as it was, the tips having run since. + storage.values[FeatureTipsController.storageKey] = {'lastVersion': '2'}; + make(storage).noteStart(); + expect(make(storage).newUser, isFalse); + }); + + test('nobody, once it is installed', () async { + final storage = _Storage() + ..values[BaoBash.storageKey] = { + 'firstSeen': '2000-01-01T00:00:00.000Z', + 'sent': 5, + }; + final host = _Host(latest: _latest('0.1.0')); + final bash = BaoBash(host: host, storage: storage); + expect(bash.showsNotice, isTrue); + await bash.install(); + expect(bash.showsNotice, isFalse); + }); + }); + + test('installed, updated and taken out', () async { + final host = _Host(latest: _latest('0.1.0')); + final bash = BaoBash(host: host); + expect(bash.installed, isNull); + + final progress = []; + bash.addListener(() => progress.add(bash.progress)); + await bash.install(); + expect(bash.installed?.version, '0.1.0'); + expect(progress, containsAllInOrder([0, 0.5, null])); + expect(bash.updateAvailable, isFalse); + + host.latest = _latest('0.2.0'); + await bash.check(); + // Not again within the hour. + expect(bash.updateAvailable, isFalse); + await bash.check(force: true); + expect(bash.updateAvailable, isTrue); + await bash.install(); + expect(bash.installed?.version, '0.2.0'); + + await bash.uninstall(); + expect(bash.installed, isNull); + }); + + test('offline: said so, nothing installed', () async { + final bash = BaoBash(host: _Host()); + await bash.install(); + expect(bash.installed, isNull); + expect(bash.error, contains('dl.baocode.dev')); + expect(bash.busy, isFalse); + }); + + group('on disk', () { + late Directory root; + late HttpServer server; + late List exe; + late List served; + + setUp(() async { + // flutter_test's clients answer 400 to all: a real one, to the + // server here. + HttpOverrides.global = null; + root = await Directory.systemTemp.createTemp('baocode-bash-exe'); + exe = utf8.encode('MZ a bash.exe' * 1000); + served = gzip.encode(exe); + server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((request) { + request.response + ..contentLength = served.length + ..add(served); + unawaited(request.response.close()); + }); + }); + + tearDown(() async { + await server.close(force: true); + await root.delete(recursive: true); + }); + + BaoBashRelease release(String version, {String? sha256}) => BaoBashRelease( + version: version, + url: Uri.parse('http://127.0.0.1:${server.port}/bash.exe.gz'), + size: served.length, + sha256: sha256 ?? '${crypto.sha256.convert(served)}', + unpacked: exe.length, + ); + + test('each version in its folder, the one before removed', () async { + final host = IoBaoBashHost(root.path, client: HttpClient.new); + expect(host.installed(), isNull); + + final first = await host.install(release('0.1.0'), (_) {}); + expect(first.executable, p.join(root.path, '0.1.0', 'bash.exe')); + expect(await File(first.executable).readAsBytes(), exe); + expect(host.installed(), first); + + final next = await host.install(release('0.2.0'), (_) {}); + expect(host.installed(), next); + expect(Directory(p.join(root.path, '0.1.0')).existsSync(), isFalse); + + await host.uninstall(); + expect(host.installed(), isNull); + expect(File(next.executable).existsSync(), isFalse); + }); + + test('not one other than named', () async { + final host = IoBaoBashHost(root.path, client: HttpClient.new); + await expectLater( + host.install(release('0.1.0', sha256: '00' * 32), (_) {}), + throwsStateError, + ); + expect(host.installed(), isNull); + }); + + test('the build for the machine', () { + String? arch(Map environment) => + IoBaoBashHost(root.path, environment: environment).arch; + expect(arch({'PROCESSOR_ARCHITECTURE': 'AMD64'}), 'x64'); + expect(arch({'PROCESSOR_ARCHITECTURE': 'ARM64'}), 'arm64'); + // An x64 app on an Arm machine. + expect( + arch({ + 'PROCESSOR_ARCHITECTURE': 'AMD64', + 'PROCESSOR_ARCHITEW6432': 'ARM64', + }), + 'arm64', + ); + expect(arch({'PROCESSOR_ARCHITECTURE': 'x86'}), isNull); + }); + }); + + group('in the settings', () { + Future pump(WidgetTester tester, Widget child) async { + tester.view.physicalSize = const Size(1000, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + home: Scaffold(body: Column(children: [child])), + ), + ); + await tester.pump(); + } + + BaoBash oldUser(_Host host) => BaoBash( + host: host, + storage: _Storage() + ..values[BaoBash.storageKey] = { + 'firstSeen': '2000-01-01T00:00:00.000Z', + 'sent': 5, + }, + ); + + testWidgets('the notice installs it, or is put off for good', ( + tester, + ) async { + final host = _Host(latest: _latest('0.1.0')) + ..downloading = Completer(); + final bash = oldUser(host); + await pump( + tester, + BaoBashNotice(bash: bash, core: () => ClaudeCore.builtin), + ); + expect(find.text('On Windows, BaoCode Bash is recommended'), findsOne); + + await tester.tap(find.text('Install')); + await tester.pump(); + await tester.pump(); + expect(find.text('Downloading… 50%'), findsOne); + host.downloading!.complete(); + await tester.pump(); + await tester.pump(); + expect( + find.text('On Windows, BaoCode Bash is recommended'), + findsNothing, + ); + + final later = oldUser(_Host()); + await pump( + tester, + BaoBashNotice(bash: later, core: () => ClaudeCore.builtin), + ); + await tester.tap(find.text('Not Now')); + await tester.pump(); + expect( + find.text('On Windows, BaoCode Bash is recommended'), + findsNothing, + ); + expect(later.noticeDismissed, isTrue); + }); + + testWidgets('no notice where the CLI runs the agents, nor to a new user', ( + tester, + ) async { + await pump( + tester, + BaoBashNotice(bash: oldUser(_Host()), core: () => ClaudeCore.cli), + ); + expect( + find.text('On Windows, BaoCode Bash is recommended'), + findsNothing, + ); + await pump( + tester, + BaoBashNotice( + bash: BaoBash(host: _Host(), storage: _Storage()), + core: () => ClaudeCore.builtin, + ), + ); + expect( + find.text('On Windows, BaoCode Bash is recommended'), + findsNothing, + ); + }); + + testWidgets('the row: its size to install, its version once installed', ( + tester, + ) async { + final host = _Host(latest: _latest('0.1.0')); + final bash = BaoBash(host: host); + await pump(tester, BaoBashSetting(bash: bash)); + await tester.pump(); + expect(find.text('BaoCode Bash (recommended)'), findsOne); + expect(find.text('Install (13 MB)'), findsOne); + + await tester.tap(find.text('Install (13 MB)')); + await tester.pump(); + await tester.pump(); + expect(find.text('Version 0.1.0 installed.'), findsOne); + expect(find.text('Uninstall'), findsOne); + expect(find.text('Update'), findsNothing); + + host.latest = _latest('0.2.0'); + await bash.check(force: true); + await tester.pump(); + expect( + find.text('Version 0.1.0 installed. Version 0.2.0 is out.'), + findsOne, + ); + expect(find.text('Update'), findsOne); + }); + }); +} diff --git a/tool/test_bash_exe.ps1 b/tool/test_bash_exe.ps1 new file mode 100644 index 000000000..372051f09 --- /dev/null +++ b/tool/test_bash_exe.ps1 @@ -0,0 +1,135 @@ +# Runs a build of BaoCode Bash (bash.exe, github.com/baocode-dev/bash-exe) +# as the app's agents do, `bash -c COMMAND`: its built-in tools, both kinds +# of path, Windows programs, exit statuses, stdin. +# +# pwsh tool/test_bash_exe.ps1 +# +# CI runs it where it builds it (.github/workflows/bash-exe.yml); it runs on +# a Windows machine with the build copied there as well. +param([Parameter(Mandatory)] [string] $Bash) +$ErrorActionPreference = 'Stop' + +$Bash = (Resolve-Path -LiteralPath $Bash).Path +$work = Join-Path ([IO.Path]::GetTempPath()) "bash-exe-test-$PID" +New-Item -ItemType Directory -Path $work | Out-Null +Set-Content -LiteralPath (Join-Path $work 'a.txt') -Value "one`nfoo bar`nthree" -NoNewline +Set-Content -LiteralPath (Join-Path $work 'b.json') -Value '{"name":"bao","tags":["x","y"]}' +$failed = 0 + +# `bash ARGS…`, in [work], [stdin] given; its status, stdout and stderr. +function Invoke-Bash([string[]] $Arguments, [string] $Stdin = '', [int] $Seconds = 60) { + $info = New-Object Diagnostics.ProcessStartInfo $Bash + foreach ($argument in $Arguments) { $info.ArgumentList.Add($argument) } + $info.WorkingDirectory = $work + $info.RedirectStandardInput = $true + $info.RedirectStandardOutput = $true + $info.RedirectStandardError = $true + $info.UseShellExecute = $false + $process = [Diagnostics.Process]::Start($info) + $out = $process.StandardOutput.ReadToEndAsync() + $err = $process.StandardError.ReadToEndAsync() + $process.StandardInput.Write($Stdin) + $process.StandardInput.Close() + if (-not $process.WaitForExit($Seconds * 1000)) { + $process.Kill($true) + return @{ Status = -1; Out = ''; Err = "still running after ${Seconds}s" } + } + $process.WaitForExit() + @{ Status = $process.ExitCode; Out = $out.Result.Replace("`r`n", "`n"); Err = $err.Result } +} + +# `bash -c COMMAND` has to exit with [Status] and print what [Expected] +# matches. +function Test-Bash([string] $Name, [string] $Command, [string] $Expected, [int] $Status = 0, [string] $Stdin = '') { + $ran = Invoke-Bash @('-c', $Command) $Stdin + if ($ran.Status -eq $Status -and $ran.Out -match $Expected) { + Write-Host "ok $Name" + return + } + Write-Host "FAIL $Name" + Write-Host " command: $Command" + Write-Host " status: $($ran.Status) (expected $Status)" + Write-Host " stdout: $($ran.Out)" + Write-Host " stderr: $($ran.Err)" + Write-Host " expected: /$Expected/" + $script:failed++ +} + +try { + $version = Invoke-Bash @('--version') + Write-Host $version.Out + if ($version.Status -ne 0 -or $version.Out -notmatch '(?m)^GNU bash, version 5\.' -or $version.Out -notmatch 'BaoCode Bash \d') { + Write-Host "FAIL --version: $($version.Status) $($version.Err)" + $failed++ + } + + Test-Bash 'echo' 'echo hello' '^hello\n$' + Test-Bash 'no arguments' 'echo "[$1]"' '^\[\]\n$' + $named = Invoke-Bash @('-c', 'echo "$0|$1|$2"', 'name', 'a b', "it's") + if ($named.Out -ne "name|a b|it's`n") { Write-Host "FAIL -c with arguments: $($named.Out)"; $failed++ } else { Write-Host 'ok -c with arguments' } + Test-Bash 'exit status' 'exit 7' '^$' 7 + Test-Bash 'set -e' 'set -e; false; echo after' '^$' 1 + Test-Bash 'command not found' 'no-such-command-here' '^$' 127 + Test-Bash 'stdin' 'read line; echo "got:$line"' '^got:piped\n$' 0 "piped`n" + Test-Bash 'arithmetic, [[ ]], arrays' 'a=(x y z); [[ ${#a[@]} -eq 3 ]] && echo $(( 6 * 7 ))' '^42\n$' + + Test-Bash 'rg' 'rg -n foo a.txt' '^2:foo bar\n$' + Test-Bash 'grep' 'grep -c o a.txt' '^2\n$' + Test-Bash 'sed' 'sed -n "s/foo/baz/p" a.txt' '^baz bar\n$' + Test-Bash 'awk' 'awk "NR==2 {print \$2}" a.txt' '^bar\n$' + Test-Bash 'jq' 'jq -r ".tags | join(\",\")" b.json' '^x,y\n$' + Test-Bash 'find' 'find . -name "*.json"' '^\./b\.json\n$' + Test-Bash 'pipes, sort, uniq, wc' 'printf "b\na\nb\n" | sort | uniq | wc -l' '^\s*2\n$' + Test-Bash 'xargs' 'echo a.txt | xargs cat | head -1' '^one\n$' + Test-Bash 'tar' 'tar -cf t.tar a.txt && tar -tf t.tar' '^a\.txt\n$' + Test-Bash 'built in' 'type -t rg sed' '^builtin\nbuiltin\n$' + + $windows = $env:SystemRoot.Replace('\', '/') + $drive = $windows.Substring(0, 1).ToLower() + $msys = "/$drive" + $windows.Substring(2) + Test-Bash 'C:\ path' "ls '$($env:SystemRoot)\System32\cmd.exe'" 'cmd\.exe' + Test-Bash 'C:/ path' "ls '$windows/System32/cmd.exe'" 'cmd\.exe' + Test-Bash '/c/ path' "ls '$msys/System32/cmd.exe'" 'cmd\.exe' + Test-Bash '/mnt/c/ path' "test -f '/mnt$msys/System32/cmd.exe' && echo yes" '^yes\n$' + Test-Bash 'cd /c/' "cd '$msys' && ls -d System32" '^System32\n$' + + Test-Bash 'pwd, in Windows spelling' "cd '$msys' && pwd -P" '(?i)^[a-z]:[\\/]windows\n$' + + # As bao_agent's Bash tool runs a command (Shell.arguments in + # packages/bao_agent/lib/src/util/processes.dart): where it ended up is + # written to a file, for the next. + $cwdFile = Join-Path $work 'cwd.txt' + $script = 'eval "$1" < /dev/null; __bao_status=$?; pwd -P >| "$2" 2>/dev/null; exit $__bao_status' + $agent = Invoke-Bash @('-c', $script, 'bash', "cd '$msys' && echo moved && (exit 3)", $cwdFile) + $ended = if (Test-Path -LiteralPath $cwdFile) { (Get-Content -LiteralPath $cwdFile -Raw).Trim() } else { '' } + if ($agent.Status -ne 3 -or $agent.Out -ne "moved`n" -or $ended -notmatch '(?i)^[a-z]:[\\/]windows$') { + Write-Host "FAIL as the agent runs it: $($agent.Status) '$($agent.Out)' '$ended' $($agent.Err)" + $failed++ + } else { + Write-Host "ok as the agent runs it ($ended)" + } + + Test-Bash 'Windows programs' 'cmd.exe /c echo from-cmd' '^from-cmd\s*$' + Test-Bash 'a program on PATH' 'git --version' '^git version' + Test-Bash 'Windows find, as written for it' 'find /c "foo" a.txt' '(?i)a\.txt: 1' + Test-Bash 'a redirection to a file' 'echo written > out.txt && cat out.txt' '^written\n$' + + # A job left in the background is not waited for, as bash's are not. + $started = Get-Date + $background = Invoke-Bash @('-c', 'sleep 30 & echo started') '' 20 + $took = ((Get-Date) - $started).TotalSeconds + if ($background.Out -ne "started`n" -or $took -gt 15) { + Write-Host "FAIL background job: '$($background.Out)' after $([int]$took)s $($background.Err)" + $failed++ + } else { + Write-Host 'ok background job' + } +} finally { + Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue +} + +if ($failed -gt 0) { + Write-Host "$failed failed" + exit 1 +} +Write-Host 'All passed'