diff --git a/AGENTS.md b/AGENTS.md index 3f8f926..02dacda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -784,6 +784,12 @@ editor and any AI agent see exactly the tools App Studio runs: An empty directory is removed; anything else stops the install and says where. `flutter precache --web` runs after, best effort — Flutter fetches the same components on the first web build. +- **A failed step shows its command's output, from the first error line on** + (`ToolInstallException.fromOutput`, `failureExcerpt` in + `util/command_output.dart`). A compiler, `git` or `dart install` names the + real problem first; the tail it replaced ended on "Failed to build". The + whole output rides along as `installErrorOutput` for the copy button, and + goes to `setup.log` on Windows. - **Apple's installer reports nothing, so it is polled.** `xcode-select --install` returns at once; the installer polls `xcode-select -p` for a real `git` every 3 s. It also watches for the `Install Command Line Developer @@ -1271,6 +1277,7 @@ install. Sparkle would also catch it, but later and less clearly. — that is what it replaced, one different amount per dialog. `test/widgets/dialog_body_test.dart` measures the spacing and fails on a file with more dialogs than `DialogBody`s. +- **`ErrorBanner` text is selectable, and a banner with a log has a copy button.** It is a `SelectionArea`, like the server log, so ⌘C/⌘A work and every other key reaches the form. Copy takes the message plus the *full* output (`fullLog`) in a ``` fence — unfenced, GitHub turns every `#12` stack frame into a link to issue 12. Pass `log` as the part worth showing and `fullLog` as all of it. - **`ShadBadge.secondary` is invisible on a `muted` card** — slate defines `secondary` and `muted` as the same colour, in both brightnesses. Use `.outline` on a muted surface, and check any `secondary`-on-`muted` pairing before assuming it reads. - **`onPressed: null` does not grey out a `ShadButton` — pass `enabled: false` too.** The dimming is an `Opacity(.5)` driven by `ShadState.disabled`, which shad sets from the `enabled` property alone; that defaults to `true` no matter what `onPressed` is. A null handler on its own gets you a button that is inert but looks live, which reads as a broken click rather than an unavailable action. Settings → Tools passes both. The toolbar's `_IconAction` derives it as `enabled: onPressed != null`, so Start and Stop dim like everything else. - **A `ShadTooltip` never opens on a disabled `ShadButton`** — which is exactly when its text is worth reading. `ShadTooltip` owns no `MouseRegion`: it injects `onHoverChange` into the theme's hover strategies and relies on the *child* to report hover, and a disabled button puts its content behind an `AbsorbPointer`, so nothing ever reports. Wrap the button in a bare `ShadGestureDetector` — that sits outside the absorber and reports hover regardless. `HotRestartButton` does this, because "start the server first" is the whole point of the tooltip there. @@ -1868,6 +1875,7 @@ that could not work — there is no Flutter SDK to build with yet. - **Picking one is mandatory, and Create is what says so.** `_canCreate` waits on the editor as well as the name. This replaced a set of checkboxes that could all be left clear plus a "No external editor selected" prompt (Continue / Pick Editor) raised *after* the user had committed — a control that cannot express the empty answer says the same thing up front and needs no prompt. `_hasExternalEditor` and `_confirmNoExternalEditor` are gone with it. - **`builtIn` still exists and nothing sets it any more.** It meant "configured whether or not it was asked for", and OpenCode was the only one, because App Studio ran it as its own agent. With `kOpenCodeAgentEnabled` off there is no Agent tab, so `IdeIntegration.opencode` takes `builtIn: kOpenCodeAgentEnabled` and a new project gets exactly what was picked. `configuredIdes()` is consequently an identity function today; it is kept because the flag can come back. Do not mark OpenCode's option specially — a checked-and-disabled box was tried and deliberately reverted. - Names must match `^[a-z][a-z0-9_]*$` (they become Dart package names); the input folds case and drops separators as you type. +- **A failed `serverpod create` is read, not tailed** (`ProjectCreationException.fromCliOutput`). The CLI logs through `cli_tools`, which with no terminal prefixes `ERROR: ` once and wraps the whole message at 80 columns, never inside a word. A plain error is the `ERROR:` paragraph re-joined; an uncaught exception ("Yikes! … file an issue") is the paragraph directly above the first `#0` frame, and the log starts there — the exception and the top of the stack, not the `main` at the bottom. `output` keeps everything, for the banner's copy button. Only a blank line tells an error's continuation from a following `info` line; the CLI exits after an error, so that is enough. - After the CLI succeeds, `patchFlutterAppForPreview` sets `device: web-server` on the `flutter_apps` entry in `_server/pubspec.yaml` — without it the runner launches the app on `web-server-launch-browser`, which also opens the system browser. No port: the runner publishes the URL. The project is then opened, which auto-starts it. - Last used location is remembered in `ProjectSession` (`new_project_directory` pref). - **`IdeIntegration` lives in `process/ide_integration.dart`, not in the creator**, purely so `ProjectSettings` can use it without dragging `dart:io` in. `project_creator.dart` re-exports it, so every existing import still reads naturally. diff --git a/lib/process/project_creator.dart b/lib/process/project_creator.dart index d469187..b2e3e8b 100644 --- a/lib/process/project_creator.dart +++ b/lib/process/project_creator.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'dart:math' as math; import 'package:flutter/services.dart' show rootBundle; import 'package:meta/meta.dart'; @@ -11,6 +12,7 @@ import '../runner/runner_protocol.dart' show kHeadlessWebDevice; import '../session/project_settings.dart'; import '../toolchain/tool_status.dart'; import '../toolchain/toolchain_controller.dart'; +import '../util/command_output.dart'; import 'ide_integration.dart'; import 'tool_command.dart'; @@ -19,8 +21,6 @@ import 'tool_command.dart'; // its tests still reach it through the creator, where it reads naturally. export 'ide_integration.dart'; -final _ansiEscape = RegExp(r'\x1B\[[0-9;]*[A-Za-z]'); - /// Agent instructions tuned for App Studio, written into every new project as /// its `AGENTS.md`. /// @@ -49,13 +49,100 @@ String? validateProjectName(String name) { /// Failure while running `serverpod create` or preparing the project. class ProjectCreationException implements Exception { - ProjectCreationException(this.message, {this.log, this.createdPath}); + ProjectCreationException( + this.message, { + this.log, + this.output, + this.createdPath, + }); + + /// Reads what a failed `serverpod create` printed. + /// + /// The CLI logs through `cli_tools`' `StdOutLogger`: with no terminal it + /// prefixes an error with `ERROR: ` — once, on its first line — and wraps + /// the whole message at 80 columns, never inside a word. Two shapes reach + /// us: + /// + /// - **A plain error**, `ERROR: Project x already exists.`, possibly + /// wrapped over several lines. The [message] is the whole of it, joined + /// back into one paragraph; the [log] is the end of the output, which is + /// what led up to it. + /// - **An internal error** — an uncaught exception, which the CLI prints as + /// its "Yikes! … please file an issue" paragraph, the issue URL, then the + /// exception and its stack trace, all in one `log.error` call. The + /// paragraph that matters is the one directly above the first stack + /// frame, so that is the [message], and the [log] starts there: the + /// exception and the top of the stack, which is where it was thrown. The + /// bottom of the stack is `main` and says nothing. + /// + /// Either way [output] carries all of it, for a bug report. + factory ProjectCreationException.fromCliOutput( + String output, { + required int exitCode, + String? createdPath, + }) { + final lines = commandOutputLines(output); + final fallback = 'serverpod create failed (exit code $exitCode).'; + final full = lines.join('\n'); + + final errorAt = lines.indexWhere((l) => l.startsWith('ERROR:')); + if (errorAt < 0) { + return ProjectCreationException( + fallback, + log: _tail(lines, from: lines.length), + output: full, + createdPath: createdPath, + ); + } + + final frameAt = lines.indexWhere(_isStackFrame, errorAt); + if (frameAt > errorAt) { + // The exception is the paragraph directly above the stack. It can be + // the `ERROR:` line itself, for an error logged with a stack trace but + // no "Yikes" preamble. + var start = frameAt; + while (start > errorAt && lines[start - 1].trim().isNotEmpty) { + start--; + } + final paragraph = _paragraph(lines.sublist(start, frameAt)); + if (paragraph.isNotEmpty) { + return ProjectCreationException( + paragraph, + log: lines.sublist(start).join('\n'), + output: full, + createdPath: createdPath, + ); + } + } + + // A plain error: everything up to the next blank line, the next + // level-prefixed line, or a stack trace. + var end = errorAt + 1; + while (end < lines.length && + lines[end].trim().isNotEmpty && + !_levelPrefix.hasMatch(lines[end]) && + !_isStackFrame(lines[end])) { + end++; + } + final paragraph = _paragraph(lines.sublist(errorAt, end)); + return ProjectCreationException( + paragraph.isEmpty ? fallback : paragraph, + log: _tail(lines, from: errorAt), + output: full, + createdPath: createdPath, + ); + } final String message; - /// Tail of the CLI output, when the failure came from `serverpod create`. + /// The part of the CLI output worth showing under [message], when the + /// failure came from `serverpod create`. final String? log; + /// Everything the CLI printed, for copying into a bug report. [log] is cut + /// to what explains the failure; this is not. + final String? output; + /// Set when the project exists on disk despite the failure — it can still /// be opened. final String? createdPath; @@ -64,6 +151,40 @@ class ProjectCreationException implements Exception { String toString() => message; } +/// The longest [ProjectCreationException.message] taken from the CLI's +/// output, in lines as it printed them. Past that it is cut with an ellipsis; +/// the whole of it is still in the log, and copied with it. +const _kMaxMessageLines = 8; + +/// The fewest lines of output the log shows for a plain error. +const _kLogTailLines = 12; + +final _levelPrefix = RegExp(r'^(ERROR|WARNING|DEBUG): '); + +final _stackFrame = RegExp(r'^#\d+\s'); + +bool _isStackFrame(String line) => _stackFrame.hasMatch(line); + +/// The last [_kLogTailLines] lines of [lines], reaching back to [from] if +/// that is earlier, so the error is never cut off the top. +String _tail(List lines, {required int from}) { + final start = math.min(math.max(0, lines.length - _kLogTailLines), from); + return lines.sublist(start).join('\n'); +} + +/// [lines] unwrapped into one paragraph, without the level prefix. The CLI +/// wraps at spaces only, so joining with a space puts the text back as it was +/// logged. +String _paragraph(List lines) { + final cut = lines.length > _kMaxMessageLines; + final text = lines + .take(_kMaxMessageLines) + .map((l) => l.replaceFirst(_levelPrefix, '').trim()) + .where((l) => l.isNotEmpty) + .join(' '); + return cut ? '$text …' : text; +} + /// Creates Serverpod projects with the bundled CLI and configures them for the /// App Studio preview pane. class ProjectCreator { @@ -151,9 +272,9 @@ class ProjectCreator { ); if (code != 0) { - throw ProjectCreationException( - _failureMessage(log.toString(), code), - log: _logTail(log.toString()), + throw ProjectCreationException.fromCliOutput( + log.toString(), + exitCode: code, createdPath: await Directory(projectPath).exists() ? projectPath : null, ); } @@ -299,35 +420,13 @@ class ProjectCreator { } await pubspec.writeAsString(patched); } - - String _failureMessage(String log, int exitCode) { - final plain = log.replaceAll(_ansiEscape, ''); - for (final line in const LineSplitter().convert(plain)) { - final trimmed = line.trim(); - if (trimmed.startsWith('ERROR:')) { - return trimmed.substring('ERROR:'.length).trim(); - } - } - return 'serverpod create failed (exit code $exitCode).'; - } - - String _logTail(String log, {int lines = 12}) { - final plain = log.replaceAll(_ansiEscape, '').replaceAll('\r', '\n'); - final all = const LineSplitter() - .convert(plain) - .map((l) => l.trimRight()) - .where((l) => l.isNotEmpty) - .toList(); - if (all.length <= lines) return all.join('\n'); - return all.sublist(all.length - lines).join('\n'); - } } /// Last step line in [chunk] — the CLI redraws steps with `\r` and ends each /// one with an ellipsis (`Running serverpod generator...`). Completion and /// epilogue lines are skipped so the status keeps naming the running step. String? _lastStatusLine(String chunk) { - final plain = chunk.replaceAll(_ansiEscape, '').replaceAll('\r', '\n'); + final plain = chunk.replaceAll(ansiEscapePattern, '').replaceAll('\r', '\n'); for (final line in const LineSplitter().convert(plain).reversed) { final trimmed = line.trim(); if (!trimmed.endsWith('...') && !trimmed.endsWith('…')) continue; diff --git a/lib/toolchain/toolchain_controller.dart b/lib/toolchain/toolchain_controller.dart index 8f9678d..b2550d5 100644 --- a/lib/toolchain/toolchain_controller.dart +++ b/lib/toolchain/toolchain_controller.dart @@ -105,6 +105,8 @@ class ToolchainController extends ChangeNotifier implements ToolsView { InstallProgress? _progress; CancelToken? _cancel; String? _installError; + String? _installErrorLog; + String? _installErrorOutput; bool _finalizing = false; ToolchainInstaller get installer => @@ -153,6 +155,10 @@ class ToolchainController extends ChangeNotifier implements ToolsView { _finalizing || (_progress != null && !_progress!.isDone); @override String? get installError => _installError; + @override + String? get installErrorLog => _installErrorLog; + @override + String? get installErrorOutput => _installErrorOutput; @override bool get isBusy => isInstalling || _refreshing || _planning; @@ -228,10 +234,18 @@ class ToolchainController extends ChangeNotifier implements ToolsView { // -- install -------------------------------------------------------------- - /// Windows: appends a failed step, with the detail the setup screen leaves - /// out, to `setup.log` in App Studio's local data, where the clean-room - /// report (`tool/windows/vm_collect.ps1`) picks it up. A release build has - /// nowhere else to say what went wrong. + /// The three always move together: a log left over from the last failure + /// under the next one's message would explain the wrong thing. + void _setInstallError(String? message, {String? log, String? output}) { + _installError = message; + _installErrorLog = message == null ? null : log; + _installErrorOutput = message == null ? null : output; + } + + /// Windows: appends a failed step, with the command's whole output, to + /// `setup.log` in App Studio's local data, where the clean-room report + /// (`tool/windows/vm_collect.ps1`) picks it up. The setup screen shows the + /// output too, but a VM run has nobody there to copy it. void _logFailure(ToolId id, String message, String? detail) { final root = paths.localDataRoot; if (root == null) return; @@ -267,13 +281,13 @@ class ToolchainController extends ChangeNotifier implements ToolsView { if (!_plan.covers(ids)) { final error = await preflight(); if (error != null) { - _installError = error; + _setInstallError(error); _notify(); return; } } - _installError = null; + _setInstallError(null); _finalizing = true; final cancel = _cancel = CancelToken(); final startedAt = DateTime.now(); @@ -291,6 +305,7 @@ class ToolchainController extends ChangeNotifier implements ToolsView { report(); try { String? failure; + ToolInstallException? failed; for (final id in ids) { if (failure != null || cancel.isCancelled) { state[id] = state[id]!.copyWith(phase: ToolPhase.cancelled); @@ -309,10 +324,12 @@ class ToolchainController extends ChangeNotifier implements ToolsView { // Each step needs the one before it — Flutter's `git`, the // Serverpod CLI's `dart` — so the first failure ends the run. failure = e is ToolInstallException ? e.message : '$e'; - if (e is ToolInstallException && e.detail != null) { - debugPrint('ToolchainController: ${e.message}\n${e.detail}'); + failed = e is ToolInstallException ? e : null; + final output = failed?.output ?? failed?.detail; + if (output != null) { + debugPrint('ToolchainController: $failure\n$output'); } - _logFailure(id, failure, e is ToolInstallException ? e.detail : null); + _logFailure(id, failure, output); state[id] = state[id]!.copyWith(phase: ToolPhase.failed, error: failure); } @@ -320,7 +337,11 @@ class ToolchainController extends ChangeNotifier implements ToolsView { // The next step reads what this one installed. await refresh(); } - _installError = failure; + _setInstallError( + failure, + log: failed?.detail, + output: failed?.output, + ); _cancel = null; await refresh(deep: true); } finally { diff --git a/lib/toolchain/toolchain_installer.dart b/lib/toolchain/toolchain_installer.dart index 64b175b..d16aa6d 100644 --- a/lib/toolchain/toolchain_installer.dart +++ b/lib/toolchain/toolchain_installer.dart @@ -12,6 +12,7 @@ import '../platform/windows/win32_system.dart'; import '../platform/windows/windows_roots.dart'; import '../platform/windows/windows_system.dart'; import '../process/tool_command.dart'; +import '../util/command_output.dart'; import 'install_plan.dart'; import 'install_progress.dart'; import 'install_record.dart'; @@ -23,11 +24,29 @@ import 'tool_version.dart'; import 'toolchain_paths.dart'; class ToolInstallException implements Exception { - const ToolInstallException(this.message, {this.detail}); + const ToolInstallException(this.message, {this.detail, this.output}); + + /// A step that ran a command and failed: [detail] is the part of its + /// [output] that explains why — from the first error line on — and + /// [output] is all of it, for copying into a bug report. + factory ToolInstallException.fromOutput(String message, String output) { + final lines = commandOutputLines(output); + return ToolInstallException( + message, + detail: lines.isEmpty ? null : failureExcerpt(lines), + output: lines.isEmpty ? null : lines.join('\n'), + ); + } final String message; + + /// What to show under [message]: a command's output, cut to what explains + /// the failure, or the error behind a step that ran no command. final String? detail; + /// Everything the command printed, when [detail] is only part of it. + final String? output; + @override String toString() => message; } @@ -307,12 +326,12 @@ class ToolchainInstaller { } final root = result.exitCode == 0 ? await installedGitRoot() : null; if (root == null) { - throw ToolInstallException( + throw ToolInstallException.fromOutput( result.exitCode == 0 ? 'Git for Windows installed, but App Studio cannot find it.' : 'Git for Windows could not be installed ' '(exit ${result.exitCode}).', - detail: _tail('${result.stdout}\n${result.stderr}'), + '${result.stdout}\n${result.stderr}', ); } await _enableGitLongPaths(_host.path.join(root, 'cmd', 'git.exe')); @@ -396,9 +415,9 @@ class ToolchainInstaller { '/SUPPRESSMSGBOXES', ]); if (result.exitCode != 0) { - throw ToolInstallException( + throw ToolInstallException.fromOutput( 'Git for Windows could not be uninstalled (exit ${result.exitCode}).', - detail: _tail('${result.stdout}\n${result.stderr}'), + '${result.stdout}\n${result.stderr}', ); } final deadline = DateTime.now().add(gitUninstallTimeout); @@ -672,9 +691,9 @@ class ToolchainInstaller { )); final result = await _runFlutter(root, const ['upgrade']); if (result.exitCode != 0) { - throw ToolInstallException( + throw ToolInstallException.fromOutput( 'Flutter could not be updated.', - detail: _tail('${result.stdout}\n${result.stderr}'), + '${result.stdout}\n${result.stderr}', ); } final info = FlutterInfo.parse(await File( @@ -765,14 +784,14 @@ class ToolchainInstaller { if (result.exitCode != 0) { final output = '${result.stdout}\n${result.stderr}'; if (previous != null) await restoreLauncher(previous); - throw ToolInstallException( + throw ToolInstallException.fromOutput( // Windows will not delete an executable that is running. _host.isWindows && output.contains('might be in use') ? 'Serverpod could not be updated while the installed version is ' 'running. Close other Serverpod servers and the AI agents ' 'using Serverpod, or restart the computer, then try again.' : 'Serverpod could not be installed.', - detail: _tail(output), + output, ); } @@ -802,9 +821,9 @@ class ToolchainInstaller { const ['uninstall', 'serverpod_cli'], ); if (result.exitCode != 0) { - throw ToolInstallException( + throw ToolInstallException.fromOutput( 'Serverpod could not be uninstalled.', - detail: _tail('${result.stdout}\n${result.stderr}'), + '${result.stdout}\n${result.stderr}', ); } } else if (owned.path case final path?) { @@ -1081,9 +1100,9 @@ class ToolchainInstaller { ['-q', '-o', archive.path, '-d', into.path], ); if (result.exitCode != 0) { - throw ToolInstallException( + throw ToolInstallException.fromOutput( 'Could not unpack Flutter.', - detail: _tail('${result.stderr}'), + '${result.stderr}', ); } } @@ -1116,14 +1135,6 @@ class ToolchainInstaller { } catch (_) {} } - static String _tail(String output) { - final lines = const LineSplitter() - .convert(output.trim()) - .where((l) => l.trim().isNotEmpty) - .toList(); - return lines.skip(lines.length > 20 ? lines.length - 20 : 0).join('\n'); - } - static String _stamp() => DateTime.now().microsecondsSinceEpoch.toString(); static String _mb(int bytes) => '${(bytes / (1000 * 1000)).round()} MB'; diff --git a/lib/ui/new_project_dialog.dart b/lib/ui/new_project_dialog.dart index 3004e6a..bffd90e 100644 --- a/lib/ui/new_project_dialog.dart +++ b/lib/ui/new_project_dialog.dart @@ -183,6 +183,10 @@ class _NewProjectDialogState extends State { String? _error; String? _errorLog; + /// All of the CLI's output, which the banner's copy button takes; + /// [_errorLog] is only the part of it shown. + String? _errorOutput; + /// Set when the project reached disk but could not be fully configured. String? _createdPath; @@ -210,6 +214,7 @@ class _NewProjectDialogState extends State { setState(() { _error = null; _errorLog = null; + _errorOutput = null; _createdPath = null; }); } else { @@ -235,6 +240,7 @@ class _NewProjectDialogState extends State { _directoryController.text = prettyPath(_directory); _error = null; _errorLog = null; + _errorOutput = null; }); } @@ -247,6 +253,7 @@ class _NewProjectDialogState extends State { _status = 'Starting Serverpod…'; _error = null; _errorLog = null; + _errorOutput = null; _createdPath = null; }); @@ -268,6 +275,7 @@ class _NewProjectDialogState extends State { _status = null; _error = e.message; _errorLog = e.log; + _errorOutput = e.output; _createdPath = e.createdPath; }); } catch (e) { @@ -347,7 +355,11 @@ class _NewProjectDialogState extends State { children: [ const SizedBox(height: 8), if (_error != null) ...[ - ErrorBanner(message: _error!, log: _errorLog), + ErrorBanner( + message: _error!, + log: _errorLog, + fullLog: _errorOutput, + ), const SizedBox(height: 16), ], FieldLabel('Project name'), diff --git a/lib/ui/toolchain/manage_tools_pane.dart b/lib/ui/toolchain/manage_tools_pane.dart index 29db9b8..c701cad 100644 --- a/lib/ui/toolchain/manage_tools_pane.dart +++ b/lib/ui/toolchain/manage_tools_pane.dart @@ -80,7 +80,11 @@ class _ManageToolsPaneState extends State { ), const ShadGap(3), if (toolchains.installError case final error?) ...[ - ErrorBanner(message: error), + ErrorBanner( + message: error, + log: toolchains.installErrorLog, + fullLog: toolchains.installErrorOutput, + ), const ShadGap(3), ] else if (missing.isNotEmpty && manual.isEmpty && diff --git a/lib/ui/toolchain/toolchain_setup_dialog.dart b/lib/ui/toolchain/toolchain_setup_dialog.dart index 997ed66..9c09001 100644 --- a/lib/ui/toolchain/toolchain_setup_dialog.dart +++ b/lib/ui/toolchain/toolchain_setup_dialog.dart @@ -201,7 +201,11 @@ class _ToolchainSetupDialogState extends State { mainAxisSize: MainAxisSize.min, children: [ if (toolchains.installError case final error?) ...[ - ErrorBanner(message: error), + ErrorBanner( + message: error, + log: toolchains.installErrorLog, + fullLog: toolchains.installErrorOutput, + ), const SizedBox(height: 12), ], SettingsTable( diff --git a/lib/ui/toolchain/tools_view.dart b/lib/ui/toolchain/tools_view.dart index 87b792a..d000e5f 100644 --- a/lib/ui/toolchain/tools_view.dart +++ b/lib/ui/toolchain/tools_view.dart @@ -33,8 +33,18 @@ abstract interface class ToolsView implements Listenable { InstallPlan get plan; InstallProgress? get progress; + + /// Why the last install failed, in a sentence. Null while it has not. String? get installError; + /// The failing command's output, cut to the part that explains + /// [installError] — shown under it. Null when no command produced any. + String? get installErrorLog; + + /// All of the failing command's output, which the error's copy button + /// takes. Null when [installErrorLog] is already all of it. + String? get installErrorOutput; + bool get isBusy; bool get isInstalling; diff --git a/lib/util/command_output.dart b/lib/util/command_output.dart new file mode 100644 index 0000000..acc0256 --- /dev/null +++ b/lib/util/command_output.dart @@ -0,0 +1,54 @@ +import 'dart:math' as math; + +/// An ANSI escape sequence: colour, cursor movement. +final ansiEscapePattern = RegExp(r'\x1B\[[0-9;]*[A-Za-z]'); + +/// A line that reports an error the way compilers, `git` and the Dart and +/// Serverpod tools do: `Error:`, `error:`, `ERROR:`, `fatal:`. +final _errorLine = RegExp(r'\b(?:error|fatal)\b:', caseSensitive: false); + +/// A command's [output] as the lines a terminal would have shown: colour +/// codes dropped, and a line the command redrew with `\r` (a progress step, +/// a download counter) kept as it was last drawn rather than once per frame. +/// Trailing whitespace is trimmed, runs of blank lines fold into one, and +/// blank lines at either end are dropped. +List commandOutputLines(String output) { + final plain = output + .replaceAll(ansiEscapePattern, '') + .replaceAll('\r\n', '\n'); + final lines = []; + for (final raw in plain.split('\n')) { + final drawn = raw.split('\r').lastWhere( + (segment) => segment.trim().isNotEmpty, + orElse: () => '', + ); + final line = drawn.trimRight(); + if (line.isEmpty && (lines.isEmpty || lines.last.isEmpty)) continue; + lines.add(line); + } + while (lines.isNotEmpty && lines.last.isEmpty) { + lines.removeLast(); + } + return lines; +} + +/// The part of a failed command's [lines] worth showing under its message. +/// +/// The first error line and everything after it, with [context] lines before +/// it: a compiler or `git` names the real problem first, and the lines after +/// it are consequences — so the last few lines, which is what a tail shows, +/// are usually "Failed to build" and nothing more. With no error line, the +/// last [tailLines]. +/// +/// It is for display only. Keep the whole output beside it for copying. +String failureExcerpt( + List lines, { + int tailLines = 20, + int context = 2, +}) { + final first = lines.indexWhere(_errorLine.hasMatch); + final start = first < 0 + ? math.max(0, lines.length - tailLines) + : math.max(0, first - context); + return lines.sublist(start).join('\n'); +} diff --git a/lib/widgets/error_banner.dart b/lib/widgets/error_banner.dart index e3bb46f..868baa5 100644 --- a/lib/widgets/error_banner.dart +++ b/lib/widgets/error_banner.dart @@ -1,21 +1,84 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:shad/shad.dart'; import '../theme/app_theme.dart'; -/// Destructive-tinted failure box with an optional scrollable log tail. -class ErrorBanner extends StatelessWidget { - const ErrorBanner({super.key, required this.message, this.log}); +/// Destructive-tinted failure box with an optional scrollable log. +/// +/// The text is selectable — message and log together, as one selection — and +/// a banner with a log carries a copy button that puts the whole failure on +/// the clipboard, so it can be pasted into an issue. +/// +/// Selection is a [SelectionArea], as in the server log: it answers ⌘C and ⌘A +/// while it holds focus and lets every other key through, so the form around +/// it keeps Tab, Enter and the menu bar's shortcuts. +class ErrorBanner extends StatefulWidget { + const ErrorBanner({ + super.key, + required this.message, + this.log, + this.fullLog, + }); final String message; /// Command output shown in a capped, scrollable monospace pane. final String? log; + /// Everything the command printed, when [log] is only the part of it that + /// explains the failure. The copy button takes this over [log]. + final String? fullLog; + + /// The tallest the log pane gets before it scrolls: about ten lines, which + /// is an exception and the top of its stack, and keeps the banner from + /// pushing the form below it out of the window. + static const logMaxHeight = 150.0; + + @override + State createState() => _ErrorBannerState(); +} + +class _ErrorBannerState extends State { + bool _copied = false; + + String? get _copyLog { + final full = widget.fullLog; + if (full != null && full.isNotEmpty) return full; + final log = widget.log; + return log != null && log.isNotEmpty ? log : null; + } + + /// The message, then the output in a fence. Markdown, because it is going + /// into an issue: unfenced, GitHub turns every `#12` frame of a stack trace + /// into a link to issue 12. + String get _copyText { + final log = _copyLog; + if (log == null) return widget.message; + return '${widget.message}\n\n```\n$log\n```'; + } + + Future _copy() async { + await Clipboard.setData(ClipboardData(text: _copyText)); + if (mounted) setState(() => _copied = true); + } + + @override + void didUpdateWidget(ErrorBanner oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.message != widget.message || + oldWidget.fullLog != widget.fullLog || + oldWidget.log != widget.log) { + _copied = false; + } + } + @override Widget build(BuildContext context) { final theme = ShadTheme.of(context); final scheme = theme.colorScheme; + final log = widget.log; + final hasLog = log != null && log.isNotEmpty; // `muted`, not `small`: failure messages wrap, and `small` is the label // role (`leading-none`), which sets them solid. @@ -35,43 +98,73 @@ class ErrorBanner extends StatelessWidget { borderRadius: theme.radii.md, border: Border.all(color: scheme.destructive.withValues(alpha: 0.35)), ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox( - height: lineHeight, - child: Center( - child: Icon( - LucideIcons.circleAlert, - size: 14, - color: scheme.destructive, + child: SelectionArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + height: lineHeight, + child: Center( + child: Icon( + LucideIcons.circleAlert, + size: 14, + color: scheme.destructive, + ), ), ), - ), - const SizedBox(width: 8), - Expanded(child: Text(message, style: messageStyle)), - ], - ), - if (log != null && log!.isNotEmpty) ...[ - const SizedBox(height: 8), - ConstrainedBox( - constraints: const BoxConstraints(maxHeight: 120), - child: SingleChildScrollView( - child: Text( - log!, - style: theme.textTheme.muted.copyWith( - fontFamily: kMonoFont, - fontSize: 10.5, - height: 1.4, + const SizedBox(width: 8), + Expanded(child: Text(widget.message, style: messageStyle)), + if (hasLog) ...[ + const SizedBox(width: 8), + // Out of the selection: a drag across the banner should not + // pick up the button, and ⌘A should not paint it. + SelectionContainer.disabled( + child: ShadTooltip( + builder: (context) => Text( + _copied ? 'Copied' : 'Copy error and output', + ), + child: ShadIconButton.ghost( + semanticLabel: 'Copy error and output', + width: lineHeight, + height: lineHeight, + padding: EdgeInsets.zero, + iconSize: 14, + icon: Icon( + _copied ? LucideIcons.check : LucideIcons.copy, + ), + onPressed: _copy, + ), + ), + ), + ], + ], + ), + if (hasLog) ...[ + const SizedBox(height: 8), + ConstrainedBox( + constraints: const BoxConstraints( + maxHeight: ErrorBanner.logMaxHeight, + ), + child: SingleChildScrollView( + child: SizedBox( + width: double.infinity, + child: Text( + log, + style: theme.textTheme.muted.copyWith( + fontFamily: kMonoFont, + fontSize: 10.5, + height: 1.4, + ), + ), ), ), ), - ), + ], ], - ], + ), ), ); } diff --git a/test/new_project_dialog_test.dart b/test/new_project_dialog_test.dart index 7e1f99e..51cf30d 100644 --- a/test/new_project_dialog_test.dart +++ b/test/new_project_dialog_test.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:appstudio/toolchain/toolchain_controller.dart'; @@ -13,6 +14,9 @@ import 'package:appstudio/session/project_session.dart'; import 'package:appstudio/theme/app_theme.dart'; import 'package:appstudio/ui/new_project_dialog.dart'; import 'package:appstudio/util/pretty_path.dart'; +import 'package:appstudio/widgets/error_banner.dart'; + +import '../widgetbook/fakes/project.dart'; /// Existing directory the dialog can offer as the default location. final String _location = Directory.systemTemp @@ -214,4 +218,71 @@ void main() { // Nothing can reach the empty answer now, so there is nothing left to ask. expect(find.text('No external editor selected'), findsNothing); }); + + testWidgets('a crashed CLI shows its exception, and copies all of it', ( + tester, + ) async { + final copied = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied.add((call.arguments as Map)['text'] as String); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + tester.view.physicalSize = const Size(900, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget( + ShadApp( + theme: buildLightTheme(), + home: Scaffold( + body: NewProjectDialog( + actions: FakeNewProject(outcome: CreateOutcome.crashes), + initialName: 'bookshelf', + initialIde: IdeIntegration.cursor, + createOnOpen: true, + ), + ), + ), + ); + await tester.pump(); + await tester.pump(); + + // The line that says what went wrong, not the first line of "Yikes". + expect( + find.text( + 'Exception: Error while parsing pubspec file: ' + '/Users/someone/lab/dart/pubspec.yaml: ' + "Instance of '_WrappedYamlException'", + ), + findsOneWidget, + ); + expect(find.textContaining('Yikes'), findsNothing); + + await tester.tap( + find.descendant( + of: find.byType(ErrorBanner), + matching: find.byType(ShadIconButton), + ), + ); + await tester.pump(); + expect(copied.single, contains('Yikes!')); + expect(copied.single, contains('#11 main')); + + // The form is still the form: the name field takes typing, and doing so + // clears the failure. + await tester.enterText(find.byType(ShadInput).first, 'bookshelf2'); + await tester.pump(); + expect(find.byType(ErrorBanner), findsNothing); + }); } diff --git a/test/project_creator_test.dart b/test/project_creator_test.dart index 47948b7..79edacb 100644 --- a/test/project_creator_test.dart +++ b/test/project_creator_test.dart @@ -7,6 +7,7 @@ import 'package:appstudio/analytics/app_analytics.dart'; import 'package:appstudio/process/project_creator.dart'; import 'package:appstudio/session/project_settings.dart'; +import '../widgetbook/fakes/project.dart'; import 'support/agent_flag.dart'; import 'support/recording_analytics.dart'; import 'support/toolchain_support.dart'; @@ -38,6 +39,157 @@ serverpod: '''; void main() { + group('ProjectCreationException.fromCliOutput', () { + test('an internal error names the exception, not the boilerplate', () { + final e = ProjectCreationException.fromCliOutput( + kSampleInternalErrorOutput, + exitCode: 1, + ); + + // The exception and its wrapped continuation, joined back up. + expect( + e.message, + 'Exception: Error while parsing pubspec file: ' + '/Users/someone/lab/dart/pubspec.yaml: ' + "Instance of '_WrappedYamlException'", + ); + }); + + test('an internal error logs the exception and the top of the stack', () { + final e = ProjectCreationException.fromCliOutput( + kSampleInternalErrorOutput, + exitCode: 1, + ); + final log = e.log!.split('\n'); + + expect( + log.first, + 'Exception: Error while parsing pubspec file: ' + '/Users/someone/lab/dart/pubspec.yaml:', + ); + expect(log[2], startsWith('#0 parsePubspec')); + // The "Yikes" paragraph is in the copy, not in the pane. + expect(e.log, isNot(contains('Yikes'))); + // And nothing is cut off the end. + expect(log.last, ''); + }); + + test('the whole output is kept for copying', () { + final e = ProjectCreationException.fromCliOutput( + kSampleInternalErrorOutput, + exitCode: 1, + ); + + expect(e.output, kSampleInternalErrorOutput.trimRight()); + }); + + test('a plain error that wraps is shown whole', () { + // `Are you sure …?` is two lines of its own, the second of which wraps + // at 80 columns: three lines in all, one message. + const output = 'ERROR: Are you sure you want to create a project named ' + '"test"?\n' + 'Use the --force flag to force creation, or pick a name that is not ' + 'reserved by\n' + 'Serverpod.\n'; + final e = ProjectCreationException.fromCliOutput(output, exitCode: 1); + + expect( + e.message, + 'Are you sure you want to create a project named "test"? ' + 'Use the --force flag to force creation, or pick a name that is not ' + 'reserved by Serverpod.', + ); + expect(e.log, output.trimRight()); + }); + + test('a wrapped plain error is one message, the tail its log', () { + final e = ProjectCreationException.fromCliOutput( + kSamplePlainErrorOutput, + exitCode: 1, + ); + + expect( + e.message, + 'Could not download the required resources for Serverpod. Make sure ' + 'that you are connected to the internet and that you are using the ' + 'latest version of Serverpod.', + ); + expect(e.log, startsWith('Downloading templates...')); + }); + + test('a plain error ends at the next blank or level-prefixed line', () { + const output = 'Downloading templates...\n' + 'ERROR: Failed to download templates.\n' + 'WARNING: Something else went wrong.\n'; + final e = ProjectCreationException.fromCliOutput(output, exitCode: 1); + + expect(e.message, 'Failed to download templates.'); + }); + + test('a plain error stays in the log however much follows it', () { + final output = [ + for (var i = 0; i < 20; i++) 'step $i...', + 'ERROR: Project fine already exists.', + // An `info` line has no prefix, so only a blank line tells it from + // the error's own continuation. The CLI exits after an error, so + // there is rarely anything after it at all. + '', + for (var i = 0; i < 20; i++) 'cleanup $i', + ].join('\n'); + final e = ProjectCreationException.fromCliOutput(output, exitCode: 1); + + expect(e.message, 'Project fine already exists.'); + expect(e.log, startsWith('ERROR: Project fine already exists.')); + }); + + test('progress redraws are kept as last drawn, colours dropped', () { + const output = '\x1B[33m⠋ Creating project...\r⠙ Creating project...' + '\r✓ Creating project.\x1B[0m\n' + '\n\n\n' + 'ERROR: Project fine already exists.\n'; + final e = ProjectCreationException.fromCliOutput(output, exitCode: 1); + + expect( + e.output, + '✓ Creating project.\n\nERROR: Project fine already exists.', + ); + }); + + test('output with no error line falls back to the exit code', () { + final e = ProjectCreationException.fromCliOutput( + [for (var i = 0; i < 30; i++) 'line $i'].join('\n'), + exitCode: 64, + ); + + expect(e.message, 'serverpod create failed (exit code 64).'); + expect(e.log!.split('\n'), hasLength(12)); + expect(e.log, endsWith('line 29')); + expect(e.output!.split('\n'), hasLength(30)); + }); + + test('a very long error is cut, and kept whole in the output', () { + final output = [ + 'ERROR: first', + for (var i = 0; i < 20; i++) 'more $i', + ].join('\n'); + final e = ProjectCreationException.fromCliOutput(output, exitCode: 1); + + expect(e.message, startsWith('first more 0')); + expect(e.message, endsWith(' …')); + expect(e.message, isNot(contains('more 19'))); + expect(e.output, contains('more 19')); + }); + + test('carries the created path through', () { + final e = ProjectCreationException.fromCliOutput( + 'ERROR: nope', + exitCode: 1, + createdPath: '/tmp/fine', + ); + expect(e.createdPath, '/tmp/fine'); + }); + }); + group('validateProjectName', () { test('accepts lowercase names with digits and underscores', () { expect(validateProjectName('my_app2'), isNull); diff --git a/test/toolchain/install_failure_test.dart b/test/toolchain/install_failure_test.dart new file mode 100644 index 0000000..ab56f32 --- /dev/null +++ b/test/toolchain/install_failure_test.dart @@ -0,0 +1,100 @@ +import 'dart:io'; + +import 'package:appstudio/toolchain/install_record.dart'; +import 'package:appstudio/toolchain/tool_probe.dart'; +import 'package:appstudio/toolchain/tool_status.dart'; +import 'package:appstudio/toolchain/toolchain.dart'; +import 'package:appstudio/toolchain/toolchain_controller.dart'; +import 'package:appstudio/toolchain/toolchain_installer.dart'; +import 'package:appstudio/toolchain/toolchain_paths.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../widgetbook/fakes/tools.dart'; +import '../support/toolchain_support.dart'; + +/// An installer whose first step fails the way a command does. +class _FailingInstaller extends ToolchainInstaller { + _FailingInstaller({required super.paths}); + + @override + Future installCommandLineTools({ + required ProgressSink onProgress, + required CancelToken cancel, + }) async { + throw ToolInstallException.fromOutput( + 'Serverpod could not be installed.', + kSampleDartInstallFailure, + ); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('ToolInstallException.fromOutput', () { + test('shows from the first error, and keeps all of it', () { + final e = sampleInstallFailure; + + // A tail would have opened on the package list and ended on "Failed to + // build": the compiler's own error is what says why. + expect(e.detail!.split('\n').take(2), [ + 'Building package executable...', + 'Compiling bin/serverpod_cli.dart...', + ]); + expect(e.detail, contains("Error: Can't have modifier 'final' here.")); + expect(e.detail, isNot(contains('+ analyzer'))); + expect(e.output, startsWith('Resolving dependencies...')); + expect(e.output, endsWith('Failed to build serverpod_cli:serverpod_cli.')); + }); + + test('a command that printed nothing carries no detail', () { + final e = ToolInstallException.fromOutput('It failed.', '\n \n'); + expect(e.detail, isNull); + expect(e.output, isNull); + }); + }); + + group('a failed install step', () { + late Directory tmp; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + tmp = await Directory.systemTemp.createTemp('install_failure'); + }); + + tearDown(() async { + if (await tmp.exists()) await tmp.delete(recursive: true); + }); + + test('hands its output to the UI with its message', () async { + final paths = ToolchainPaths.forHome(tmp.path); + final manifest = await loadTestManifest(); + final spec = manifest[ToolId.commandLineTools]!; + final controller = ToolchainController( + initial: Toolchain( + ToolchainInventory( + manifest: manifest, + tools: { + ToolId.commandLineTools: ToolStatus( + spec: spec, + candidates: const [], + action: ToolAction.install, + ), + }, + ), + ), + manifest: manifest, + paths: paths, + installer: _FailingInstaller(paths: paths), + probeSandbox: ProbeSandbox.empty, + ); + + await controller.installMissing(); + + expect(controller.installError, 'Serverpod could not be installed.'); + expect(controller.installErrorLog, sampleInstallFailure.detail); + expect(controller.installErrorOutput, sampleInstallFailure.output); + }); + }); +} diff --git a/test/toolchain/manage_tools_pane_test.dart b/test/toolchain/manage_tools_pane_test.dart index 438a8a5..f97a66c 100644 --- a/test/toolchain/manage_tools_pane_test.dart +++ b/test/toolchain/manage_tools_pane_test.dart @@ -4,8 +4,10 @@ import 'package:appstudio/toolchain/install_plan.dart'; import 'package:appstudio/toolchain/tool_status.dart'; import 'package:appstudio/ui/toolchain/manage_tools_pane.dart'; import 'package:appstudio/widgets/command_block.dart'; +import 'package:appstudio/widgets/error_banner.dart'; import 'package:appstudio/widgets/settings_table.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../support/host_skips.dart'; @@ -24,6 +26,50 @@ void main() { await tester.pump(); } + testWidgets('a failed install shows why, and copies all of it', ( + tester, + ) async { + final copied = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied.add((call.arguments as Map)['text'] as String); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null), + ); + final failure = sampleInstallFailure; + await pumpPane( + tester, + FakeToolsView( + inventory: mixedInventory, + installError: failure.message, + installErrorLog: failure.detail, + installErrorOutput: failure.output, + ), + ); + + final banner = tester.widget(find.byType(ErrorBanner)); + expect(banner.message, 'Serverpod could not be installed.'); + expect(banner.log, contains("Error: Can't have modifier 'final' here.")); + + await tester.tap( + find.descendant( + of: find.byType(ErrorBanner), + matching: find.byType(ShadIconButton), + ), + ); + await tester.pump(); + // The whole output, package list included, not just what is shown. + expect(copied.single, contains('+ analyzer 9.0.0')); + expect(copied.single, startsWith('Serverpod could not be installed.')); + }); + testWidgets('lists every tool with its version and who installed it', (tester) async { await pumpPane(tester, FakeToolsView(inventory: completeInventory)); diff --git a/test/toolchain/toolchain_setup_dialog_test.dart b/test/toolchain/toolchain_setup_dialog_test.dart index 6a1ddd2..4db962e 100644 --- a/test/toolchain/toolchain_setup_dialog_test.dart +++ b/test/toolchain/toolchain_setup_dialog_test.dart @@ -6,6 +6,7 @@ import 'package:appstudio/toolchain/install_progress.dart'; import 'package:appstudio/toolchain/tool_status.dart'; import 'package:appstudio/ui/toolchain/toolchain_setup_dialog.dart'; import 'package:flutter/material.dart'; +import 'package:appstudio/widgets/error_banner.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shad/shad.dart'; @@ -212,14 +213,20 @@ void main() { await startDownload(tester, tools); tools.landDownloads(); - tools.installError = 'dart install serverpod_cli failed.'; + tools.installError = sampleInstallFailure.message; + tools.installErrorLog = sampleInstallFailure.detail; + tools.installErrorOutput = sampleInstallFailure.output; tools.finishReprobe(); await settle(tester); // The dialog is the only thing on screen, so a failure has to leave the // user something to press. expect(find.byType(ToolchainSetupDialog), findsOneWidget); - expect(find.text('dart install serverpod_cli failed.'), findsOneWidget); + expect(find.text('Serverpod could not be installed.'), findsOneWidget); expect(find.text('Install'), findsOneWidget); + // And something to read: what the command said, not only that it failed. + final banner = tester.widget(find.byType(ErrorBanner)); + expect(banner.log, sampleInstallFailure.detail); + expect(banner.fullLog, sampleInstallFailure.output); }); } diff --git a/test/util/command_output_test.dart b/test/util/command_output_test.dart new file mode 100644 index 0000000..f3fb790 --- /dev/null +++ b/test/util/command_output_test.dart @@ -0,0 +1,78 @@ +import 'package:appstudio/util/command_output.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('commandOutputLines', () { + test('drops colour codes and keeps a redrawn line as last drawn', () { + expect( + commandOutputLines( + '\x1B[33m⠋ Downloading...\r⠙ Downloading...\r✓ Downloaded.\x1B[0m\n' + 'done\n', + ), + ['✓ Downloaded.', 'done'], + ); + }); + + test('folds runs of blank lines and trims the ends', () { + expect( + commandOutputLines('\n\na \r\n\n\n\nb\n\n'), + ['a', '', 'b'], + ); + }); + }); + + group('failureExcerpt', () { + test('starts just above the first error line', () { + final lines = [ + for (var i = 0; i < 30; i++) '+ package_$i 1.0.0', + 'Compiling bin/serverpod_cli.dart...', + 'lib/a.dart:1:2: Error: first', + 'lib/b.dart:3:4: Error: second', + 'Failed to build serverpod_cli:serverpod_cli.', + ]; + + expect( + failureExcerpt(lines).split('\n'), + [ + '+ package_29 1.0.0', + 'Compiling bin/serverpod_cli.dart...', + 'lib/a.dart:1:2: Error: first', + 'lib/b.dart:3:4: Error: second', + 'Failed to build serverpod_cli:serverpod_cli.', + ], + ); + }); + + test('knows git, the Serverpod CLI and lowercase errors', () { + for (final line in [ + 'fatal: not a git repository', + 'error: Your local changes would be overwritten', + 'ERROR: Project fine already exists.', + ]) { + expect( + failureExcerpt(['one', 'two', 'three', line], context: 0), + line, + reason: line, + ); + } + }); + + test('is not fooled by a count of errors or a word in passing', () { + final lines = [ + for (var i = 0; i < 25; i++) 'line $i', + 'Found 0 errors.', + 'An error occurred while fetching', + ]; + + // No error line, so the tail. + expect(failureExcerpt(lines).split('\n'), hasLength(20)); + }); + + test('with no error line, the last lines', () { + final lines = [for (var i = 0; i < 30; i++) 'line $i']; + + expect(failureExcerpt(lines, tailLines: 5), 'line 25\nline 26\n' + 'line 27\nline 28\nline 29'); + }); + }); +} diff --git a/test/widgets/error_banner_test.dart b/test/widgets/error_banner_test.dart new file mode 100644 index 0000000..7c15f66 --- /dev/null +++ b/test/widgets/error_banner_test.dart @@ -0,0 +1,212 @@ +import 'package:appstudio/process/project_creator.dart'; +import 'package:appstudio/theme/app_theme.dart'; +import 'package:appstudio/widgets/error_banner.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shad/shad.dart'; + +import '../../widgetbook/fakes/project.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late List copied; + + setUp(() { + copied = []; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.setData') { + copied.add((call.arguments as Map)['text'] as String); + } + return null; + }); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null); + }); + + // macOS, the platform the shortcuts are written for. On the test default + // (Android) Flutter binds Ctrl-C itself. + final macOS = TargetPlatformVariant.only(TargetPlatform.macOS); + + final crash = ProjectCreationException.fromCliOutput( + kSampleInternalErrorOutput, + exitCode: 1, + ); + + /// The banner as the New Project form shows it, above a text field standing + /// in for the form's name field. + Future pumpBanner(WidgetTester tester, {bool withLog = true}) async { + tester.view.physicalSize = const Size(800, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + ShadApp( + theme: buildLightTheme(), + home: Scaffold( + body: SizedBox( + width: 460, + child: Column( + children: [ + ErrorBanner( + message: crash.message, + log: withLog ? crash.log : null, + fullLog: withLog ? crash.output : null, + ), + const ShadInput(), + ], + ), + ), + ), + ), + ); + await tester.pump(); + } + + Future pressWithCommand( + WidgetTester tester, + LogicalKeyboardKey key, + String character, + ) async { + await tester.sendKeyDownEvent( + LogicalKeyboardKey.metaLeft, + platform: 'macos', + ); + final handled = await tester.sendKeyDownEvent( + key, + platform: 'macos', + character: character, + ); + await tester.sendKeyUpEvent(key, platform: 'macos'); + await tester.sendKeyUpEvent( + LogicalKeyboardKey.metaLeft, + platform: 'macos', + ); + await tester.pump(); + return handled; + } + + Finder copyButton() => find.byWidgetPredicate( + (w) => + w is ShadIconButton && w.semanticLabel == 'Copy error and output', + ); + + /// Taps the log, which is what a user does before dragging a selection, + /// and checks the banner's selection now holds focus. + Future focusBanner(WidgetTester tester) async { + // Near the top of the log: its centre is scrolled out of the pane. + await tester.tapAt( + tester.getTopLeft(find.textContaining('#0 parsePubspec')) + + const Offset(20, 6), + ); + await tester.pump(); + final focused = FocusManager.instance.primaryFocus?.context; + expect( + focused?.findAncestorWidgetOfExactType(), + isNotNull, + reason: 'the banner should hold focus', + ); + } + + testWidgets('the message and log are selectable and ⌘C copies them', ( + tester, + ) async { + await pumpBanner(tester); + await focusBanner(tester); + + expect(await pressWithCommand(tester, LogicalKeyboardKey.keyA, 'a'), isTrue); + expect(await pressWithCommand(tester, LogicalKeyboardKey.keyC, 'c'), isTrue); + + // One selection across both, so a drag can take the message and the + // stack together. + expect(copied.single, contains(crash.message)); + expect(copied.single, contains('#0 parsePubspec')); + }, variant: macOS); + + testWidgets('the copy button copies the message and the whole output', ( + tester, + ) async { + await pumpBanner(tester); + + await tester.tap(copyButton()); + await tester.pump(); + + expect( + copied.single, + '${crash.message}\n\n```\n${kSampleInternalErrorOutput.trimRight()}\n```', + ); + // The full output, not the part the pane shows. + expect(copied.single, contains('Yikes!')); + expect(find.byIcon(LucideIcons.check), findsOneWidget); + }); + + testWidgets('a banner with no log has no copy button', (tester) async { + await pumpBanner(tester, withLog: false); + + expect(copyButton(), findsNothing); + // Still selectable. + expect(find.byType(SelectionArea), findsOneWidget); + }); + + testWidgets('the log pane stays capped and scrolls', (tester) async { + await pumpBanner(tester); + + final pane = find.ancestor( + of: find.textContaining('#0 parsePubspec'), + matching: find.byType(SingleChildScrollView), + ); + expect( + tester.getSize(pane).height, + lessThanOrEqualTo(ErrorBanner.logMaxHeight), + ); + }); + + group('keys the banner does not own pass through', () { + testWidgets('a menu shortcut', (tester) async { + await pumpBanner(tester); + await focusBanner(tester); + + expect( + await pressWithCommand(tester, LogicalKeyboardKey.keyW, 'w'), + isFalse, + reason: '⌘W belongs to the menu bar', + ); + }, variant: macOS); + + testWidgets('typing', (tester) async { + await pumpBanner(tester); + await focusBanner(tester); + + expect( + await tester.sendKeyEvent(LogicalKeyboardKey.keyX, platform: 'macos'), + isFalse, + ); + }, variant: macOS); + + testWidgets('Tab moves on, to the copy button and then the form', ( + tester, + ) async { + await pumpBanner(tester); + await focusBanner(tester); + + Future tab() async { + await tester.sendKeyEvent(LogicalKeyboardKey.tab, platform: 'macos'); + await tester.pump(); + return FocusManager.instance.primaryFocus?.context; + } + + expect( + (await tab())?.findAncestorWidgetOfExactType(), + isNotNull, + ); + expect( + (await tab())?.findAncestorWidgetOfExactType(), + isNotNull, + ); + }, variant: macOS); + }); +} diff --git a/widgetbook/fakes/project.dart b/widgetbook/fakes/project.dart index 8966922..cf1a58e 100644 --- a/widgetbook/fakes/project.dart +++ b/widgetbook/fakes/project.dart @@ -43,6 +43,55 @@ class FakeRecentProjects extends ChangeNotifier implements RecentProjectsView { } } +/// What Serverpod CLI 4.1.2 printed when `serverpod create` ran in a folder +/// holding an unrelated project with an invalid `pubspec.yaml`. One +/// `log.error` call — the "Yikes" paragraph, the issue URL, the exception and +/// its stack — word-wrapped at 80 columns with `ERROR: ` on the first line. +/// +/// Verbatim, apart from the elided paths: `test/project_creator_test.dart` +/// pins the parsing against it. +const kSampleInternalErrorOutput = ''' +ERROR: Yikes! It is possible that this error is caused by an internal issue with +the Serverpod tooling. We would appreciate if you filed an issue over at Github. +Please include the stack trace below and describe any steps you did to trigger +the error. + +https://github.com/serverpod/serverpod/issues + +Exception: Error while parsing pubspec file: /Users/someone/lab/dart/pubspec.yaml: +Instance of '_WrappedYamlException' +#0 parsePubspec (package:serverpod_cli/src/util/pubspec_helpers.dart:16) +#1 isServerDirectory (package:serverpod_cli/src/util/directory.dart:27) +#2 findServerDirectory. +(package:serverpod_cli/src/util/directory.dart:55) +#3 Iterable.firstWhere (dart:core/iterable.dart:768) +#4 findServerDirectory (package:serverpod_cli/src/util/directory.dart:54) +#5 ServerpodCommandRunner.runCommand +(package:serverpod_cli/src/runner/serverpod_command_runner.dart:182) +#6 BetterCommandRunner.run +(package:cli_tools/src/better_command_runner/better_command_runner.dart:401) + +#7 _main (file:///.../serverpod_cli-4.1.2/bin/serverpod_cli.dart:121) + +#8 main. +(file:///.../serverpod_cli-4.1.2/bin/serverpod_cli.dart:68) + +#9 runZonedGuarded (dart:async/zone.dart:1902) +#10 _rootRun (dart:async/zone.dart:1525) +#11 main +(file:///.../serverpod_cli-4.1.2/bin/serverpod_cli.dart:63) + +'''; + +/// What the CLI prints when it cannot fetch its templates: a plain error, +/// wrapped at 80 columns like everything it logs. +const kSamplePlainErrorOutput = ''' +Downloading templates... +ERROR: Could not download the required resources for Serverpod. Make sure that +you are connected to the internet and that you are using the latest version of +Serverpod. +'''; + /// How [FakeNewProject.create] ends. enum CreateOutcome { /// Walks through the CLI's status lines, then succeeds. @@ -51,9 +100,12 @@ enum CreateOutcome { /// Never finishes — the progress view, held. hangs, - /// `serverpod create` fails, with its output. + /// `serverpod create` fails with an error of its own. fails, + /// `serverpod create` crashes: an internal error, with a stack trace. + crashes, + /// The project reached disk but could not be configured for the preview. partlyCreated, } @@ -83,11 +135,14 @@ class FakeNewProject implements NewProjectView { onStatus?.call('Resolving dependencies…'); return Completer().future; case CreateOutcome.fails: - throw ProjectCreationException( - 'serverpod create failed (exit code 1).', - log: 'Creating project "$name"…\n' - 'Error: Directory $path already exists and is not empty.\n' - 'Pick another name or location and try again.', + throw ProjectCreationException.fromCliOutput( + kSamplePlainErrorOutput, + exitCode: 1, + ); + case CreateOutcome.crashes: + throw ProjectCreationException.fromCliOutput( + kSampleInternalErrorOutput, + exitCode: 1, ); case CreateOutcome.partlyCreated: throw ProjectCreationException( diff --git a/widgetbook/fakes/tools.dart b/widgetbook/fakes/tools.dart index 6cc34a1..31d272b 100644 --- a/widgetbook/fakes/tools.dart +++ b/widgetbook/fakes/tools.dart @@ -13,6 +13,7 @@ import 'package:appstudio/toolchain/install_plan.dart'; import 'package:appstudio/toolchain/install_progress.dart'; import 'package:appstudio/toolchain/tool_status.dart'; import 'package:appstudio/toolchain/tool_version.dart'; +import 'package:appstudio/toolchain/toolchain_installer.dart'; import 'package:appstudio/toolchain/toolchain_manifest.dart'; import 'package:appstudio/ui/toolchain/tools_view.dart'; @@ -332,6 +333,54 @@ final finishingProgress = InstallProgress( ], ); +// ----------------------------------------------------------------------------- +// A failed install +// ----------------------------------------------------------------------------- + +/// Output shaped like `dart install serverpod_cli` failing to compile — the +/// Windows case `windowsInstallPubCache` exists for, where the CLI is built at +/// the wrong language version. Illustrative, not captured verbatim: the +/// resolution lines come first and run long, the errors that explain it come +/// after, and the last line only says the build failed. +const kSampleDartInstallFailure = ''' +Resolving dependencies... +Downloading packages... ++ _fe_analyzer_shared 92.0.0 ++ analyzer 9.0.0 ++ archive 4.0.7 ++ args 2.7.0 ++ async 2.13.0 ++ cli_tools 0.13.2 ++ collection 1.19.1 ++ crypto 3.0.6 ++ http 1.5.0 ++ meta 1.17.0 ++ path 1.9.1 ++ pub_semver 2.2.0 ++ pubspec_parse 1.5.0 ++ serverpod_cli 4.1.2 ++ serverpod_shared 4.1.2 ++ source_span 1.10.1 ++ yaml 3.1.3 ++ yaml_edit 2.2.2 +Changed 92 dependencies! +Building package executable... +Compiling bin/serverpod_cli.dart... +../../hosted/pub.dev/serverpod_cli-4.1.2/lib/src/runner/runner_event.dart:41:12: Error: Can't have modifier 'final' here. + required final String event, + ^^^^^ +../../hosted/pub.dev/serverpod_cli-4.1.2/lib/src/runner/runner_event.dart:63:12: Error: Can't have modifier 'final' here. + required final String event, + ^^^^^ +Failed to build serverpod_cli:serverpod_cli. +'''; + +/// [kSampleDartInstallFailure] as the installer reports it. +final sampleInstallFailure = ToolInstallException.fromOutput( + 'Serverpod could not be installed.', + kSampleDartInstallFailure, +); + // ----------------------------------------------------------------------------- // Fakes // ----------------------------------------------------------------------------- @@ -346,6 +395,8 @@ class FakeToolsView extends ChangeNotifier implements ToolsView { InstallPlan? plan, this.progress, this.installError, + this.installErrorLog, + this.installErrorOutput, this.isBusy = false, this.isInstalling = false, this.preflightError, @@ -366,6 +417,10 @@ class FakeToolsView extends ChangeNotifier implements ToolsView { @override String? installError; @override + String? installErrorLog; + @override + String? installErrorOutput; + @override bool isBusy; @override bool isInstalling; diff --git a/widgetbook/use_cases/first_run.dart b/widgetbook/use_cases/first_run.dart index 8bf55e3..82e53ee 100644 --- a/widgetbook/use_cases/first_run.dart +++ b/widgetbook/use_cases/first_run.dart @@ -161,7 +161,9 @@ final firstRunFolder = WidgetbookFolder( 'After a failed install', FakeToolsView( inventory: emptyInventory, - installError: 'Serverpod could not be installed.', + installError: sampleInstallFailure.message, + installErrorLog: sampleInstallFailure.detail, + installErrorOutput: sampleInstallFailure.output, ), ), ( diff --git a/widgetbook/use_cases/settings.dart b/widgetbook/use_cases/settings.dart index a79614c..4f18d83 100644 --- a/widgetbook/use_cases/settings.dart +++ b/widgetbook/use_cases/settings.dart @@ -62,7 +62,9 @@ final settingsFolder = WidgetbookFolder( builder: (_) => _settings( FakeToolsView( inventory: mixedInventory, - installError: 'Serverpod could not be installed.', + installError: sampleInstallFailure.message, + installErrorLog: sampleInstallFailure.detail, + installErrorOutput: sampleInstallFailure.output, ), ), ), diff --git a/widgetbook/use_cases/start.dart b/widgetbook/use_cases/start.dart index c2b5371..0ed79f6 100644 --- a/widgetbook/use_cases/start.dart +++ b/widgetbook/use_cases/start.dart @@ -104,6 +104,15 @@ final startFolder = WidgetbookFolder( createOnOpen: true, ), ), + WidgetbookUseCase( + name: 'CLI crashed', + builder: (_) => _createProject( + FakeNewProject(outcome: CreateOutcome.crashes), + name: 'bookshelf', + ide: IdeIntegration.cursor, + createOnOpen: true, + ), + ), WidgetbookUseCase( name: 'Created but not configured', builder: (_) => _createProject(