Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 `<name>_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.
Expand Down
159 changes: 129 additions & 30 deletions lib/process/project_creator.dart
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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';

Expand All @@ -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`.
///
Expand Down Expand Up @@ -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;
Expand All @@ -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<String> 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<String> 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 {
Expand Down Expand Up @@ -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,
);
}
Expand Down Expand Up @@ -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;
Expand Down
41 changes: 31 additions & 10 deletions lib/toolchain/toolchain_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 =>
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand All @@ -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);
Expand All @@ -309,18 +324,24 @@ 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);
}
report();
// 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 {
Expand Down
Loading
Loading