feat(app): start a pipeline from the detail view

Native Run action opens the web's prompt/workspace/notify dialog, sends the exact run_pipeline body against the pinned resolved version with one request key per confirmed attempt, keeps refusals in the dialog, reconciles a lost reply by key, and opens only the server-named run through the existing run route with one fresh Runs list read.

Adds a shared failure-reason helper so operators never see Dart runtime prefixes, and records the slice boundary in notes/P3-run.md.
This commit is contained in:
2026-10-22 02:07:49 +01:00
parent 92706a290e
commit 53a8f668ca
24 changed files with 2644 additions and 19 deletions
+1 -1
View File
@@ -25,7 +25,7 @@ or scratch servers only, never real operator sessions/runs/workflows.
| Native shell/run URLs | Preview | pipeline/version/stage/template/chat URLs, action/visit queries and native deep-link handling |
| Pipeline list/filter/sort/detail/source/versions | Preview | latest summary metadata/miniatures, pinned detail URLs |
| Definition graph | Source nodes/layout/routes/edges; active canvas71 | compose measured native nodes+labels, graph tab, pan/zoom, expanded view, definition stage pane |
| Start a pipeline | Missing | native prompt/workspace/notify dialog, exact pinned run request, response-loss intent |
| Start a pipeline | Preview: native Run action, prompt/workspace/notify dialog, pinned run request, response-loss check/retry | Report format, recent-directory suggestions, pending intent across a reload |
| Templates | Preview: gallery/detail/source, create-only dialog via Settings → Templates, list invalidated on create | run-detail template link, create refresh verified against a real server |
| Runs list/filter/sort/live fold | Preview | full time/status/provenance filters, recency/day groups, shell live/attention state |
| Run detail/input/output/copy/metrics | Preview | latest summary tabs/fields and exact empty/unknown states |
+17
View File
@@ -57,6 +57,10 @@ class _PipelinesAppState extends State<PipelinesApp> {
/// locally, so the next list reply is the only source of the new pipeline.
int _pipelinesRefresh = 0;
/// Advances when a launch was accepted. The Runs destination re-reads its
/// list once; the run itself is then opened from its route.
int _runsRefresh = 0;
@override
void initState() {
super.initState();
@@ -145,6 +149,17 @@ class _PipelinesAppState extends State<PipelinesApp> {
setState(() => _pipelinesRefresh++);
}
/// Opens the run id an accepted launch named and invalidates the Runs list.
///
/// The order is deliberate: the list token is already advanced when the Runs
/// screen mounts for the first time, so it performs one fresh `list_runs`
/// read and then opens the route's run. No row is inserted locally.
void _runStarted(int id) {
if (!mounted) return;
setState(() => _runsRefresh++);
_delegate.goTo(AppRoute.run(id));
}
Widget _buildShell(BuildContext context, AppRoute route) => AdaptiveShell(
cupertino: _cupertino,
destination: _destinationOf(route.kind),
@@ -156,11 +171,13 @@ class _PipelinesAppState extends State<PipelinesApp> {
session: _session,
server: widget.server,
refreshToken: _pipelinesRefresh,
onRunStarted: _runStarted,
),
AppDestination.runs: (_) => RunsDestination(
session: _session,
server: widget.server,
initialRunId: route.runId,
listRefreshToken: _runsRefresh,
onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)),
onBack: () => _delegate.goTo(AppRoute.runs),
),
@@ -18,6 +18,7 @@ class PipelinesDestination extends StatelessWidget {
required this.session,
required this.server,
this.refreshToken = 0,
this.onRunStarted,
});
final AppSession session;
@@ -28,6 +29,9 @@ class PipelinesDestination extends StatelessWidget {
/// accepted; the rows still come only from the server's next reply.
final int refreshToken;
/// Receives the run id an accepted launch named; the shell opens that route.
final ValueChanged<int>? onRunStarted;
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: session,
@@ -62,6 +66,7 @@ class PipelinesDestination extends StatelessWidget {
Widget _pipelinesScreen() => PipelinesScreen(
gateway: session.gateway,
embedded: true,
onRunStarted: onRunStarted,
// A reconnect or an accepted template create both advance this counter;
// either change re-reads through the mounted controller.
syncToken: session.connectionEpoch + refreshToken,
@@ -20,6 +20,7 @@ class RunsDestination extends StatelessWidget {
this.initialRunId,
this.onRunSelected,
this.onBack,
this.listRefreshToken = 0,
});
final AppSession session;
@@ -28,6 +29,10 @@ class RunsDestination extends StatelessWidget {
final ValueChanged<int>? onRunSelected;
final VoidCallback? onBack;
/// Advances when a launch was accepted elsewhere. The mounted Runs screen
/// re-reads its list once; no row is inserted locally.
final int listRefreshToken;
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: session,
@@ -64,6 +69,7 @@ class RunsDestination extends StatelessWidget {
gateway: session.gateway,
initialRunId: initialRunId,
syncToken: session.connectionEpoch,
listRefreshToken: listRefreshToken,
onRunSelected: onRunSelected,
onBack: onBack,
);
+26
View File
@@ -0,0 +1,26 @@
/// The reason text carried by a failed request, without runtime diagnostics.
///
/// The gateway fails pending requests with `StateError('Connection closed')`,
/// whose `toString()` is `Bad state: Connection closed`. The browser shows the
/// reason itself, never a Dart diagnostic, so those prefixes are stripped while
/// deliberate protocol/refusal messages stay untouched. [fallback] is the
/// honest sentence for a failure that carries no text at all.
String describeErrorReason(
Object error, {
required String fallback,
}) {
final raw = switch (error) {
StateError(:final message) => message.toString(),
_ => '$error',
};
var message = raw.trim();
for (final prefix in _runtimePrefixes) {
if (message.startsWith(prefix)) {
message = message.substring(prefix.length).trim();
}
}
return message.isEmpty ? fallback : message;
}
/// Dart runtime prefixes that never belong in operator-facing copy.
const _runtimePrefixes = ['Bad state:', 'Exception:'];
@@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
import 'pipeline_models.dart';
import 'pipeline_query.dart';
import 'pipeline_repository.dart';
import 'run_pipeline_intent.dart';
/// The user-facing message for a request failure, keeping server refusals
/// verbatim and removing only the generic `Exception:` prefix.
@@ -45,6 +46,14 @@ class PipelinesController extends ChangeNotifier {
List<PipelineRun>? _latestSource;
Map<int, PipelineRun>? _latestCache;
/// Launch intents whose reply never arrived, keyed by pinned identity.
///
/// Kept per pipeline/version like the browser's sessionStorage intent, so a
/// dialog reopened in this session still offers check/retry with the same
/// request key instead of minting a possible duplicate.
final Map<String, RunPipelineIntent> _pendingRuns =
<String, RunPipelineIntent>{};
List<PipelineSummary> get pipelines => _pipelines;
PipelineFilters get filters => _filters;
PipelineSort get sort => _sort;
@@ -203,6 +212,20 @@ class PipelinesController extends ChangeNotifier {
_notify();
}
/// The unresolved launch for one pinned definition, if any.
RunPipelineIntent? pendingRunFor(int pipelineId, int version) =>
_pendingRuns['$pipelineId@$version'];
/// Remembers an intent whose admission is unknown, or clears it once the
/// server's truth is known.
void rememberPendingRun(RunPipelineIntent intent) {
_pendingRuns['${intent.pipelineId}@${intent.version}'] = intent;
}
void clearPendingRun(int pipelineId, int version) {
_pendingRuns.remove('$pipelineId@$version');
}
bool _current(int sequence, int token) => !_disposed && sequence == token;
bool _currentDetail(int token, int id, int version) =>
@@ -0,0 +1,94 @@
import 'dart:math';
import '../../core/api_gateway.dart';
/// The browser's three notification choices for a started run. `auto` omits
/// the wire field so the pipeline definition applies.
enum RunNotifyMode {
pipelineDefault('Pipeline default'),
notify('Notify me'),
silent('Silent');
const RunNotifyMode(this.label);
final String label;
/// The `notify_mode` value, or null when the definition decides.
String? get wireValue => switch (this) {
RunNotifyMode.pipelineDefault => null,
RunNotifyMode.notify => 'on',
RunNotifyMode.silent => 'off',
};
}
/// One confirmed launch intent: the pinned pipeline identity, the operator's
/// fields and the idempotency key that belongs to them.
///
/// A lost reply leaves this intent in place, so checking or retrying reuses
/// [requestKey] and the server can dedupe it. A confirmed refusal clears it;
/// the corrected attempt mints a fresh key.
class RunPipelineIntent {
const RunPipelineIntent({
required this.pipelineId,
required this.version,
required this.prompt,
required this.workspace,
required this.notifyMode,
required this.requestKey,
});
final int pipelineId;
final int version;
final String prompt;
final String workspace;
final RunNotifyMode notifyMode;
final String requestKey;
/// The same key is only ever reused for the same pinned definition.
bool matches(int pipelineId, int version) =>
this.pipelineId == pipelineId && this.version == version;
}
/// The entropy bound for a fresh key, written as a literal because a web
/// bitwise `1 << 32` wraps to 0 and makes `Random.nextInt` reject every call.
const _entropyBound = 0x100000000;
/// A fresh `request_key` for one confirmed launch. The server caps keys at 128
/// characters; this stays well inside that bound and is unique per call.
String newRunPipelineRequestKey(
int pipelineId,
int version, {
DateTime? now,
int? random,
}) {
final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch;
final entropy = random ?? Random().nextInt(_entropyBound);
return 'app-run-$pipelineId-$version-$stamp-${entropy.toRadixString(36)}';
}
/// The id the server's run detail names, or null when it named no usable run.
int? runPipelineRunId(JsonMap run) {
final id = run['id'];
if (id is int && id > 0) return id;
if (id is num && id > 0) return id.toInt();
return null;
}
/// A launch attempt's outcome: either the server's run detail or a refusal
/// with the truth about whether admission is still unknown.
sealed class RunPipelineOutcome {
const RunPipelineOutcome();
}
class RunPipelineAccepted extends RunPipelineOutcome {
const RunPipelineAccepted(this.run);
final JsonMap run;
}
class RunPipelineRefused extends RunPipelineOutcome {
const RunPipelineRefused(this.message, {required this.admissionUnknown});
final String message;
final bool admissionUnknown;
}
+7
View File
@@ -26,6 +26,7 @@ class PipelinesScreen extends StatefulWidget {
required this.gateway,
this.embedded = false,
this.syncToken = 0,
this.onRunStarted,
});
final ApiGateway gateway;
@@ -37,6 +38,10 @@ class PipelinesScreen extends StatefulWidget {
/// reloads the list and the selected detail without losing the selection.
final int syncToken;
/// Receives the run id an accepted launch names, so the composition can open
/// the existing run route. The feature never navigates on its own.
final ValueChanged<int>? onRunStarted;
@override
State<PipelinesScreen> createState() => _PipelinesScreenState();
}
@@ -85,6 +90,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
controller: _controller,
gateway: widget.gateway,
showBack: true,
onRunStarted: widget.onRunStarted,
)
: PipelineListPanel(controller: _controller);
}
@@ -102,6 +108,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
controller: _controller,
gateway: widget.gateway,
showBack: false,
onRunStarted: widget.onRunStarted,
),
),
],
@@ -0,0 +1,174 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../core/transport/connection_state.dart';
import '../../runs/data/runs_repository.dart';
import '../pipeline_models.dart';
import '../pipelines_controller.dart';
import '../run_pipeline_intent.dart';
import '../widgets/pipeline_controls.dart';
import 'run_pipeline_dialog.dart';
import 'run_pipeline_wording.dart';
/// The pipeline detail's Run action.
///
/// Nothing is requested until the dialog's confirm. A confirmed attempt sends
/// the web's exact `run_pipeline` body against the pinned resolved version; a
/// lost reply keeps the intent so the next deliberate press checks by the same
/// request key before resending. Only the id the server names is opened.
class RunPipelineAction extends StatefulWidget {
const RunPipelineAction({
super.key,
required this.controller,
required this.detail,
required this.gateway,
this.onRunStarted,
});
final PipelinesController controller;
final PipelineDetail detail;
final ApiGateway gateway;
/// Receives the id from an accepted server reply. It is never called for a
/// guessed or malformed response.
final ValueChanged<int>? onRunStarted;
@override
State<RunPipelineAction> createState() => _RunPipelineActionState();
}
class _RunPipelineActionState extends State<RunPipelineAction> {
bool _dialogOpen = false;
int get _pipelineId => widget.detail.id;
int get _version => widget.detail.resolvedVersion;
Future<void> _open() async {
if (_dialogOpen) return;
_dialogOpen = true;
try {
await showRunPipelineDialog(
context: context,
detail: widget.detail,
pending: widget.controller.pendingRunFor(_pipelineId, _version),
onSubmit: _submit,
onPendingChanged: (intent) {
if (intent == null) {
widget.controller.clearPendingRun(_pipelineId, _version);
} else {
widget.controller.rememberPendingRun(intent);
}
},
onAccepted: _accepted,
);
} finally {
_dialogOpen = false;
}
}
void _accepted(JsonMap run) {
final id = runPipelineRunId(run);
if (id == null) return;
widget.controller.clearPendingRun(_pipelineId, _version);
widget.onRunStarted?.call(id);
}
Future<RunPipelineOutcome> _submit(RunPipelineIntent intent) async {
final repository = RunsRepository(widget.gateway);
final pending = widget.controller.pendingRunFor(
intent.pipelineId,
intent.version,
);
if (pending?.requestKey == intent.requestKey) {
// A previous send may have been admitted even though its reply was lost.
// Check before resending the same key; the server dedupes either way.
try {
final existing = await repository.runByRequestKey(intent.requestKey);
if (existing != null) return _accept(existing);
} catch (error) {
widget.controller.rememberPendingRun(intent);
return RunPipelineRefused(
'${describeRunPipelineError(error)}$runPipelineUnknownSuffix',
admissionUnknown: true,
);
}
}
try {
final run = await repository.startRun(
pipelineId: intent.pipelineId,
version: intent.version,
prompt: intent.prompt,
workspace: intent.workspace,
requestKey: intent.requestKey,
notifyMode: intent.notifyMode.wireValue,
);
final accepted = _accept(run);
if (accepted is RunPipelineAccepted) return accepted;
// A reply without a usable run id is not navigable: read the admitted run
// by key rather than inventing an id or starting another run.
return _refuse(repository, intent, 'The server returned no run id.');
} on ProtocolError catch (error) {
return _refuse(repository, intent, describeRunPipelineError(error));
} on RunsRepositoryException catch (error) {
return _refuse(repository, intent, describeRunPipelineError(error));
} catch (error) {
widget.controller.rememberPendingRun(intent);
return RunPipelineRefused(
'${describeRunPipelineError(error)}$runPipelineUnknownSuffix',
admissionUnknown: true,
);
}
}
/// A reply is only accepted when it names a usable run id.
RunPipelineOutcome _accept(JsonMap run) {
if (runPipelineRunId(run) == null) {
return const RunPipelineRefused(
'The server returned no run id.',
admissionUnknown: false,
);
}
widget.controller.clearPendingRun(widget.detail.id, _version);
return RunPipelineAccepted(run);
}
/// A confirmed refusal: prove by key that no run was admitted before letting
/// the operator correct the fields and try with a fresh key.
Future<RunPipelineOutcome> _refuse(
RunsRepository repository,
RunPipelineIntent intent,
String message,
) async {
try {
final existing = await repository.runByRequestKey(intent.requestKey);
if (existing != null) return _accept(existing);
widget.controller.clearPendingRun(intent.pipelineId, intent.version);
return RunPipelineRefused(message, admissionUnknown: false);
} catch (_) {
// Admission cannot be proven either way: keep the intent immutable.
widget.controller.rememberPendingRun(intent);
return RunPipelineRefused(
'$message$runPipelineUnknownSuffix',
admissionUnknown: true,
);
}
}
@override
Widget build(BuildContext context) {
final label = const Text(runPipelineActionLabel);
if (useCupertinoControls(context)) {
return CupertinoButton.filled(
key: runPipelineActionKey,
onPressed: _open,
child: label,
);
}
return FilledButton(
key: runPipelineActionKey,
onPressed: _open,
child: label,
);
}
}
@@ -0,0 +1,231 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../pipeline_models.dart';
import '../run_pipeline_intent.dart';
import 'run_pipeline_fields.dart';
import 'run_pipeline_wording.dart';
/// Opens the native start-a-run prompt; resolves when it closes.
///
/// Opening, typing and Cancel send nothing. Only the confirm action validates
/// and submits. [pending] restores an intent whose admission is still unknown,
/// so its fields are locked and the same request key is offered for check/retry.
Future<void> showRunPipelineDialog({
required BuildContext context,
required PipelineDetail detail,
required RunPipelineIntent? pending,
required Future<RunPipelineOutcome> Function(RunPipelineIntent intent)
onSubmit,
required ValueChanged<RunPipelineIntent?> onPendingChanged,
required ValueChanged<JsonMap> onAccepted,
}) {
final dialog = _RunPipelineDialog(
detail: detail,
pending: pending,
cupertino: usesCupertinoHost(context),
onSubmit: onSubmit,
onPendingChanged: onPendingChanged,
onAccepted: onAccepted,
);
return dialog.cupertino
? showCupertinoDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => dialog,
)
: showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => dialog,
);
}
class _RunPipelineDialog extends StatefulWidget {
const _RunPipelineDialog({
required this.detail,
required this.pending,
required this.cupertino,
required this.onSubmit,
required this.onPendingChanged,
required this.onAccepted,
});
final PipelineDetail detail;
final RunPipelineIntent? pending;
final bool cupertino;
final Future<RunPipelineOutcome> Function(RunPipelineIntent intent) onSubmit;
final ValueChanged<RunPipelineIntent?> onPendingChanged;
final ValueChanged<JsonMap> onAccepted;
@override
State<_RunPipelineDialog> createState() => _RunPipelineDialogState();
}
class _RunPipelineDialogState extends State<_RunPipelineDialog> {
late final TextEditingController _prompt;
late final TextEditingController _workspace;
late RunNotifyMode _notify;
late RunPipelineIntent? _intent;
bool _sending = false;
String? _error;
@override
void initState() {
super.initState();
final pending = widget.pending;
final restored =
pending != null &&
pending.matches(widget.detail.id, widget.detail.resolvedVersion)
? pending
: null;
_intent = restored;
_notify = restored?.notifyMode ?? RunNotifyMode.pipelineDefault;
_prompt = TextEditingController(text: restored?.prompt ?? '');
_workspace = TextEditingController(text: restored?.workspace ?? '');
_error = restored == null ? null : runPipelineUnknownAdmission;
}
@override
void dispose() {
_prompt.dispose();
_workspace.dispose();
super.dispose();
}
bool get _locked => _intent != null || _sending;
void _cancel() {
if (!_sending) Navigator.of(context).pop();
}
Future<void> _confirm() async {
if (_sending) return;
final prompt = _prompt.text.trim();
if (prompt.isEmpty) {
setState(() => _error = runPipelinePromptRequired);
return;
}
// The browser checks the field as typed; only the sent value is trimmed.
final workspace = _workspace.text;
if (!workspace.startsWith('/')) {
setState(() => _error = runPipelineWorkspaceAbsolute);
return;
}
final intent =
_intent ??
RunPipelineIntent(
pipelineId: widget.detail.id,
version: widget.detail.resolvedVersion,
prompt: prompt,
workspace: workspace.trim(),
notifyMode: _notify,
requestKey: newRunPipelineRequestKey(
widget.detail.id,
widget.detail.resolvedVersion,
),
);
setState(() {
_sending = true;
_error = null;
});
final outcome = await widget.onSubmit(intent);
if (!mounted) return;
switch (outcome) {
case RunPipelineAccepted(:final run):
widget.onPendingChanged(null);
widget.onAccepted(run);
Navigator.of(context).pop();
case RunPipelineRefused(:final message, :final admissionUnknown):
final keep = admissionUnknown ? intent : null;
widget.onPendingChanged(keep);
setState(() {
_intent = keep;
_sending = false;
_error = message;
});
}
}
@override
Widget build(BuildContext context) {
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
return PopScope(canPop: !_sending, child: dialog);
}
Widget _material(BuildContext context) {
return AlertDialog(
scrollable: true,
title: Text(runPipelineDialogTitle(widget.detail.name)),
content: _content(context),
actions: [
TextButton(
key: runPipelineCancelKey,
onPressed: _sending ? null : _cancel,
child: const Text(runPipelineCancelLabel),
),
FilledButton(
key: runPipelineConfirmKey,
onPressed: _sending ? null : _confirm,
child: Text(_confirmLabel),
),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoAlertDialog(
title: Text(runPipelineDialogTitle(widget.detail.name)),
content: _content(context),
actions: [
CupertinoDialogAction(
key: runPipelineCancelKey,
onPressed: _sending ? null : _cancel,
child: const Text(runPipelineCancelLabel),
),
CupertinoDialogAction(
key: runPipelineConfirmKey,
isDefaultAction: true,
onPressed: _sending ? null : _confirm,
child: Text(_confirmLabel),
),
],
);
}
String get _confirmLabel {
if (_sending) return runPipelineSendingLabel;
return _intent == null
? runPipelineConfirmLabel
: runPipelineCheckRetryLabel;
}
Widget _content(BuildContext context) {
final errorStyle = widget.cupertino
? TextStyle(color: CupertinoColors.systemRed.resolveFrom(context))
: TextStyle(color: Theme.of(context).colorScheme.error);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
RunPipelineFields(
prompt: _prompt,
workspace: _workspace,
notifyMode: _notify,
locked: _locked,
onNotifyChanged: (mode) => setState(() => _notify = mode),
),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Semantics(
liveRegion: true,
child: Text(error, key: runPipelineErrorKey, style: errorStyle),
),
),
],
);
}
}
@@ -0,0 +1,206 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../run_pipeline_intent.dart';
import 'run_pipeline_wording.dart';
/// The dialog's three web fields, in the host's native controls.
///
/// A confirmed launch locks every field: the request is immutable until its
/// admission is known, exactly like the browser's disabled inputs.
class RunPipelineFields extends StatelessWidget {
const RunPipelineFields({
super.key,
required this.prompt,
required this.workspace,
required this.notifyMode,
required this.locked,
required this.onNotifyChanged,
});
final TextEditingController prompt;
final TextEditingController workspace;
final RunNotifyMode notifyMode;
final bool locked;
final ValueChanged<RunNotifyMode> onNotifyChanged;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_FieldLabel(runPipelinePromptLabel, cupertino: cupertino),
_promptField(context, cupertino),
const SizedBox(height: 12),
_FieldLabel(runPipelineWorkspaceLabel, cupertino: cupertino),
_workspaceField(context, cupertino),
_helper(context, runPipelineWorkspaceHelper, cupertino),
const SizedBox(height: 12),
_FieldLabel(runPipelineNotifyLabel, cupertino: cupertino),
_notifyField(context, cupertino),
],
);
}
Widget _promptField(BuildContext context, bool cupertino) {
if (cupertino) {
return CupertinoTextField(
key: runPipelinePromptKey,
controller: prompt,
placeholder: runPipelinePromptPlaceholder,
placeholderStyle: _cupertinoPlaceholder(context),
style: CupertinoTheme.of(context).textTheme.textStyle,
minLines: 3,
maxLines: 5,
enabled: !locked,
autofocus: !locked,
padding: const EdgeInsets.all(8),
textCapitalization: TextCapitalization.sentences,
);
}
return TextField(
key: runPipelinePromptKey,
controller: prompt,
enabled: !locked,
autofocus: !locked,
minLines: 3,
maxLines: 5,
textCapitalization: TextCapitalization.sentences,
decoration: const InputDecoration(
hintText: runPipelinePromptPlaceholder,
border: OutlineInputBorder(),
),
);
}
Widget _workspaceField(BuildContext context, bool cupertino) {
if (cupertino) {
return CupertinoTextField(
key: runPipelineWorkspaceKey,
controller: workspace,
placeholder: runPipelineWorkspacePlaceholder,
placeholderStyle: _cupertinoPlaceholder(context),
style: CupertinoTheme.of(context).textTheme.textStyle,
enabled: !locked,
autocorrect: false,
padding: const EdgeInsets.all(8),
);
}
return TextField(
key: runPipelineWorkspaceKey,
controller: workspace,
enabled: !locked,
autocorrect: false,
decoration: const InputDecoration(
hintText: runPipelineWorkspacePlaceholder,
border: OutlineInputBorder(),
),
);
}
Widget _notifyField(BuildContext context, bool cupertino) {
if (cupertino) {
return CupertinoButton(
key: runPipelineNotifyKey,
padding: EdgeInsets.zero,
alignment: AlignmentDirectional.centerStart,
onPressed: locked ? null : () => _chooseNotify(context),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: Text(notifyMode.label)),
const SizedBox(width: 4),
const Icon(CupertinoIcons.chevron_down, size: 14),
],
),
);
}
return DropdownButtonFormField<RunNotifyMode>(
key: runPipelineNotifyKey,
initialValue: notifyMode,
decoration: const InputDecoration(border: OutlineInputBorder()),
items: [
for (final mode in RunNotifyMode.values)
DropdownMenuItem(value: mode, child: Text(mode.label)),
],
onChanged: locked
? null
: (mode) {
if (mode != null) onNotifyChanged(mode);
},
);
}
Future<void> _chooseNotify(BuildContext context) async {
final chosen = await showCupertinoModalPopup<RunNotifyMode>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: const Text(runPipelineNotifyLabel),
actions: [
for (final mode in RunNotifyMode.values)
CupertinoActionSheetAction(
onPressed: () => Navigator.of(sheetContext).pop(mode),
child: Text(mode.label),
),
],
cancelButton: CupertinoActionSheetAction(
isDefaultAction: true,
onPressed: () => Navigator.of(sheetContext).pop(),
child: const Text(runPipelineCancelLabel),
),
),
);
if (chosen != null) onNotifyChanged(chosen);
}
TextStyle _cupertinoPlaceholder(BuildContext context) {
// The host's own dynamic placeholder colour (light and dark), resolved for
// the dialog's inherited Cupertino brightness.
return TextStyle(color: CupertinoColors.placeholderText.resolveFrom(context));
}
Widget _helper(BuildContext context, String text, bool cupertino) {
return Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(text, style: _secondaryStyle(context, cupertino)),
);
}
}
/// Secondary copy under a field: the host's own secondary role, never a
/// borrowed palette or invented point size.
TextStyle _secondaryStyle(BuildContext context, bool cupertino) {
if (cupertino) {
return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
}
final theme = Theme.of(context);
return (theme.textTheme.bodySmall ?? const TextStyle()).copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
}
/// The label above each native field, using the web's exact words.
class _FieldLabel extends StatelessWidget {
const _FieldLabel(this.text, {required this.cupertino});
final String text;
final bool cupertino;
@override
Widget build(BuildContext context) {
// A theme label role with the primary label colour, matching the app's
// Cupertino form pattern; secondaryLabel is for helper copy only.
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.labelLarge;
return Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text(text, style: style),
);
}
}
@@ -0,0 +1,49 @@
import 'package:flutter/widgets.dart';
import '../../../core/error_reason.dart';
/// The browser client's start-a-run wording, kept verbatim.
String runPipelineDialogTitle(String name) =>
'Run ${name.isEmpty ? 'pipeline' : name}';
const runPipelineActionLabel = 'Run';
const runPipelinePromptLabel = 'Prompt';
const runPipelinePromptPlaceholder = 'What should this run do?';
const runPipelineWorkspaceLabel = 'Working directory (on the server)';
const runPipelineWorkspaceHelper =
'Choose a recent directory or type an absolute path.';
const runPipelineWorkspacePlaceholder = '/absolute/path/on/the/server';
const runPipelineNotifyLabel = 'Notifications for this run';
const runPipelineCancelLabel = 'Cancel';
const runPipelineConfirmLabel = 'Run';
const runPipelineSendingLabel = 'Starting…';
const runPipelineCheckRetryLabel = 'Check / retry';
/// Local validation, exactly the browser's two states.
const runPipelinePromptRequired = 'Enter a prompt for this run.';
const runPipelineWorkspaceAbsolute =
'Choose an absolute working directory on the server.';
/// Shown when a stored launch already has an unknown result.
const runPipelineUnknownAdmission =
'A previous launch has an unknown result. Check/retry reconciles that '
'same request; it will not start a duplicate.';
/// Appended to a transport failure whose admission cannot be proven either way.
const runPipelineUnknownSuffix =
'. Admission may be unknown. Check/retry uses the same request key.';
/// Stable test/semantics keys shared by the action and its prompt.
const runPipelineActionKey = ValueKey<String>('run-pipeline-action');
const runPipelinePromptKey = ValueKey<String>('run-pipeline-prompt');
const runPipelineWorkspaceKey = ValueKey<String>('run-pipeline-workspace');
const runPipelineNotifyKey = ValueKey<String>('run-pipeline-notify');
const runPipelineCancelKey = ValueKey<String>('run-pipeline-cancel');
const runPipelineConfirmKey = ValueKey<String>('run-pipeline-confirm');
const runPipelineErrorKey = ValueKey<String>('run-pipeline-error');
/// The server's refusal, verbatim. Only a blank error gets a sentence so the
/// prompt never claims a run that was not admitted.
String describeRunPipelineError(Object error) => describeErrorReason(
error,
fallback: 'The server did not start the run.',
);
@@ -7,6 +7,7 @@ import '../../graph/widgets/stage_definition_view.dart';
import '../pipeline_models.dart';
import '../pipeline_query.dart';
import '../pipelines_controller.dart';
import '../ui/run_pipeline_action.dart';
import 'pipeline_controls.dart';
import 'pipeline_detail_styles.dart';
import 'pipeline_graph_tab.dart';
@@ -28,12 +29,16 @@ class PipelineDetailPanel extends StatefulWidget {
required this.controller,
required this.gateway,
required this.showBack,
this.onRunStarted,
});
final PipelinesController controller;
final ApiGateway gateway;
final bool showBack;
/// A run started from this detail's Run action; receives the server's id.
final ValueChanged<int>? onRunStarted;
@override
State<PipelineDetailPanel> createState() => _PipelineDetailPanelState();
}
@@ -215,26 +220,39 @@ class _PipelineDetailPanelState extends State<PipelineDetailPanel> {
pipelineSubtitle(detail),
style: pipelineMutedStyle(context),
);
final heading = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [title, subtitle],
);
final action = Align(
alignment: AlignmentDirectional.centerStart,
child: RunPipelineAction(
controller: _controller,
detail: detail,
gateway: widget.gateway,
onRunStarted: widget.onRunStarted,
),
);
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: widget.showBack
? Row(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.showBack)
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
PipelineBackButton(onPressed: _controller.clearSelection),
const SizedBox(width: 4),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [title, subtitle],
),
),
Expanded(child: heading),
],
)
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [title, subtitle],
),
else
heading,
const SizedBox(height: 8),
action,
],
),
);
}
@@ -1,5 +1,7 @@
import 'package:flutter/widgets.dart';
import '../../../core/error_reason.dart';
/// The browser client's retry wording, kept verbatim.
const retryActionLabel = 'Retry';
const retryDialogMessage =
@@ -27,7 +29,7 @@ String restartDialogTitle(num runId) => 'Restart run $runId?';
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
/// so the prompt never claims a retry that did not happen.
String describeRetryError(Object error) {
final message = '$error'.trim();
return message.isEmpty ? 'The server did not retry the run.' : message;
}
String describeRetryError(Object error) => describeErrorReason(
error,
fallback: 'The server did not retry the run.',
);
@@ -74,6 +74,20 @@ class RunsRepository {
'run_detail',
);
/// Reads a run by the idempotency key of a launch whose reply was lost.
///
/// This is a read, not a launch: a server that never admitted the key answers
/// without a run detail, which is reported as null rather than invented.
Future<JsonMap?> runByRequestKey(String requestKey) async {
final key = requestKey.trim();
if (key.isEmpty) {
throw const RunsRepositoryException('A launch request key is required.');
}
final reply = await _gateway.call('get_run', {'request_key': key});
final detail = reply['run_detail'];
return detail is Map ? Map<String, dynamic>.from(detail) : null;
}
Future<JsonMap> startRun({
required num pipelineId,
required num version,
@@ -82,7 +96,7 @@ class RunsRepository {
required String requestKey,
String title = '',
String outputFormat = '',
String notifyMode = 'auto',
String? notifyMode,
}) async {
final fields = <String, dynamic>{
'pipeline_id': pipelineId,
@@ -93,7 +107,7 @@ class RunsRepository {
};
if (title.trim().isNotEmpty) fields['title'] = title.trim();
if (outputFormat.isNotEmpty) fields['output_format'] = outputFormat;
final mode = notifyMode.trim().toLowerCase();
final mode = (notifyMode ?? '').trim().toLowerCase();
if (mode == 'on' || mode == 'off') fields['notify_mode'] = mode;
return _required(await _gateway.call('run_pipeline', fields), 'run_detail');
}
+11
View File
@@ -18,6 +18,7 @@ class RunsScreen extends StatefulWidget {
required this.gateway,
this.initialRunId,
this.syncToken = 0,
this.listRefreshToken = 0,
this.onRunSelected,
this.onBack,
});
@@ -31,6 +32,10 @@ class RunsScreen extends StatefulWidget {
/// in place instead of being remounted, so its selection survives.
final int syncToken;
/// Advances when a launch accepted outside this screen must be reflected by a
/// fresh `list_runs` read. It never inserts a row of its own.
final int listRefreshToken;
final ValueChanged<int>? onRunSelected;
final VoidCallback? onBack;
@@ -57,6 +62,12 @@ class _RunsScreenState extends State<RunsScreen> {
if (widget.syncToken != oldWidget.syncToken) {
controller.resync();
}
// A launch accepted on another destination invalidates the list only. The
// route change below selects the returned run separately, so this is the
// one fresh server read that makes the new row appear.
if (widget.listRefreshToken != oldWidget.listRefreshToken) {
controller.load();
}
if (widget.initialRunId != oldWidget.initialRunId) {
final id = widget.initialRunId;
if (id == null) {
+166
View File
@@ -0,0 +1,166 @@
# P3 — Start a pipeline (native client)
## Outcome
The pipeline detail now has a native **Run** action that opens the browser's
prompt/workspace/notify dialog. Confirming sends the web's exact `run_pipeline`
request against the pipeline detail's resolved (pinned) version, opens only the
run id the server returns on the existing `/runs/:id` route, and makes the Runs
destination re-read its list exactly once. Nothing is sent while opening,
typing, cancelling or for either local validation failure.
## Behavior
- **Dialog**: title `Run <name>` (`Run pipeline` when the name is empty).
Fields and words match `web/src/views/pipelines.js`:
- `Prompt` / placeholder `What should this run do?`
- `Working directory (on the server)` / placeholder
`/absolute/path/on/the/server` plus
`Choose a recent directory or type an absolute path.`
- `Notifications for this run` with `Pipeline default`, `Notify me` and
`Silent`.
- `Cancel` and `Run`; while sending the primary action reads `Starting…`.
- **Validation**: `Enter a prompt for this run.` for a blank prompt;
`Choose an absolute working directory on the server.` unless the workspace as
typed starts with `/` (the sent value is trimmed, matching the browser's raw
check plus `String(workspace).trim()` request body). Neither sends
`run_pipeline`.
- **Request identity**: `pipeline_id` is the detail id and `version` is
`detail.resolvedVersion`, so a historical selection pins that recorded
version (not latest). `input.prompt` is trimmed; `workspace` is trimmed;
`notify_mode` is present only for `on`/`off`. No `title` or `output_format`
is sent. The request key is `app-run-<pipeline>-<version>-<stamp>-<entropy>`,
bounded well under 128 characters.
- **One key per confirmed attempt**: the first confirmation mints it; a second
confirmation while the first is in flight is ignored, so a double tap sends
once. A confirmed refusal clears the intent and the corrected attempt mints
a fresh key.
- **Refusal**: the dialog stays open with the server's own reason. Before
treating it as a correctable refusal, the client reads
`get_run {request_key}`; if that read finds an admitted run, that run opens
instead. If the read itself fails, admission is still unknown.
- **Lost reply**: a transport failure keeps the dialog open with the web's
honest wording (`… Admission may be unknown. Check/retry uses the same
request key.`), locks the fields and offers `Check / retry`. The deliberate
retry reads by the same key first and resends with that same key only when no
run is found. The pending intent is held per pinned identity in
`PipelinesController`, so closing and reopening the dialog in the session
restores the same check/retry state.
- **Acceptance**: only a reply that names a usable run id is opened. The action
reports that id to composition; `PipelinesApp` advances a Runs list token and
navigates to `AppRoute.run(id)`. The Runs destination performs one fresh
`list_runs` read (or its mount read if it was not mounted yet). No row is
inserted from the run reply.
## Deliberate slice boundary / remaining parity
- This slice implements the three fields named in the task. The browser dialog
also has a **Report format** select and loads `chat_directories` for workspace
suggestions, seeding the workspace from Settings/recent directories. Those are
**not** implemented here; the workspace starts empty on both hosts. This is a
known remaining gap for full dialog parity, not a silent fallback.
- Pending launch intents survive dialog close/reopen in the running app
(`PipelinesController`) but not a page reload. The browser persists them in
sessionStorage. No automatic replay exists in either case.
## Files
Added:
- `lib/features/pipelines/run_pipeline_intent.dart` — intent, notify mapping,
request-key minting, accepted/refused outcome.
- `lib/core/error_reason.dart` — shared failure-reason text without runtime
diagnostics (used by the launch dialog and retry action).
- `lib/features/pipelines/ui/run_pipeline_wording.dart` — verbatim browser copy
and stable keys.
- `lib/features/pipelines/ui/run_pipeline_fields.dart` — native Material /
Cupertino prompt, workspace and notification controls.
- `lib/features/pipelines/ui/run_pipeline_dialog.dart` — dialog state,
validation, locked immutable request, refusal/unknown handling.
- `lib/features/pipelines/ui/run_pipeline_action.dart` — submit/reconcile
transport, pending intent use, navigation callback.
- `test/features/pipelines/ui/run_pipeline_launch_test.dart`
- `test/application/run_start_wiring_test.dart`
- `test/features/runs/ui/runs_list_refresh_test.dart`
- `test/core/error_reason_test.dart`
- `tool/run_pipeline_probe.dart`, `tool/run_pipeline_probe.mjs`
Changed:
- `lib/features/pipelines/pipelines_controller.dart` — pending launch intents
keyed by pipeline/version.
- `lib/features/pipelines/widgets/pipeline_detail_panel.dart` — Run action in
the detail header and the `onRunStarted` callback.
- `lib/features/pipelines/screen.dart` — forwards `onRunStarted`.
- `lib/features/runs/data/runs_repository.dart` — adds the read-only
`runByRequestKey` (`get_run {request_key}`) used to reconcile a lost reply;
`startRun` takes the nullable notify wire value so the default omits the field.
- `lib/features/runs/actions/retry_wording.dart` — uses the shared reason text,
so the retry prompt no longer leaks `Bad state:` either.
- `lib/features/runs/screen.dart` — optional `listRefreshToken`.
- `lib/application/pipelines_destination.dart`, `runs_destination.dart`,
`pipelines_app.dart` — route wiring: accepted launch → `/runs/:id` + one Runs
list invalidation. This is the small composition wiring the task allowed; no
new route helper was added — the existing `AppRoute.run(id)` is used.
- `lib/features/runs/screen.dart` is the Runs route screen (not the run-detail
UI): it accepts the one-shot list invalidation token.
- `test/features/pipelines/pipeline_graph_tab_test.dart` — scrolls the
content-driven header to the Graph tab before tapping it. The header gained
the native Run action; the canvas assertion is unchanged.
## Review fixes
The UI review found two rendered defects; both are corrected here.
- **Readable Cupertino labels.** Field labels now use the host theme's label
text style (primary label colour, no invented point size), matching
`schedules/ui/editor/schedule_editor_fields.dart`. Only helper copy uses
`secondaryLabel` via `tabLabelTextStyle`. The placeholder now uses
`CupertinoColors.placeholderText.resolveFrom(context)` instead of copied
light/dark constants. A widget test asserts the label role, helper role and
placeholder source colour.
- **No Dart diagnostics in copy.** New `lib/core/error_reason.dart` reduces a
failure to its reason: `StateError` contributes only its message (not
`Bad state: `), and `Exception:`/`Bad state:` prefixes are stripped. Both
`describeRunPipelineError` and the shared `describeRetryError` use it, with
their existing fallbacks. The unknown-admission suffix is unchanged, and a
test asserts the dialog renders `Connection closed` with no `Bad state`.
- **Smaller review cleanup.** The run action now sends
`RunNotifyMode.wireValue` (the unused duplicate mapping is gone), and the
workspace check is the browser's raw check while the request keeps the
trimmed value.
- **Coverage added.** `Starting…` is asserted while submitting; closing and
reopening an unknown launch restores `Check / retry` with the same key; a
refusal whose by-key read finds an admitted run opens it without a second
launch; `test/core/error_reason_test.dart` covers diagnostic stripping.
## Checks (actual)
- `flutter analyze` — **No issues found**.
- `flutter test` — **999 passed** (full suite; includes the new launch, app
wiring, error-reason and runs-list tests). The focused
`flutter test test/features/pipelines test/application test/features/runs`
run also passed (274 tests).
- `flutter build web` — **succeeded** (normal app entrypoint).
- `flutter build web --target=tool/run_pipeline_probe.dart -o
build/run_probe_web` — **succeeded**.
- `node tool/run_pipeline_probe.mjs build/run_probe_web` — **passed** for both
host control sets against the isolated loopback fixture. The original capture
set is in
`/Users/alan/.local/share/pipelines/data/artifacts/97/public/run-pipeline-probe/`;
post-review frames are in `…/public/code-fix-p3-run/`.
Probe checks:
- Cupertino: Cancel sent nothing; both validation messages; exact payload
(`input`, `pipeline_id`, `request_key`, `version`, `workspace` only;
`pipeline_id=1`, `version=2`, `/work/release`,
`Review the release.`, key prefix `app-run-1-2-`); route `/runs/100`;
one fresh `list_runs` read after acceptance.
- Material: validation, exact payload, route `/runs/101`, one fresh
`list_runs` read.
Not verified: Android/iOS builds or device behavior (development is web-only in
this phase). No live production run was started; the probe fixture creates the
runs. No commit, push or deployment was performed; the candidate is left as
working-tree changes for the manager to land.
@@ -0,0 +1,177 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/pipelines/ui/run_pipeline_wording.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
import '../features/pipelines/fixtures.dart';
import 'pipelines_app_test.dart' show webServer;
import 'pipelines_replies.dart';
List<Map<String, dynamic>> requestsOf(FakeChannel channel, String type) =>
channel.outgoing
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
.where((frame) => frame['type'] == type)
.toList();
Future<List<Map<String, dynamic>>> waitForCount(
WidgetTester tester,
FakeChannel channel,
String type,
int count,
) async {
for (
var attempt = 0;
attempt < 150 && requestsOf(channel, type).length < count;
attempt++
) {
await tester.pump(const Duration(milliseconds: 10));
}
final requests = requestsOf(channel, type);
expect(
requests.length,
greaterThanOrEqualTo(count),
reason: 'Timed out waiting for $type #$count',
);
return requests;
}
Future<void> reply(
WidgetTester tester,
FakeChannel channel,
String type,
int count,
Map<String, dynamic> body,
) async {
final requests = await waitForCount(tester, channel, type, count);
channel.incoming.add(jsonEncode({'id': requests[count - 1]['id'], ...body}));
await tester.pump();
await tester.pump();
}
void main() {
testWidgets('an accepted launch opens the returned run and re-reads the '
'runs list exactly once', (tester) async {
tester.view.physicalSize = const Size(1100, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final fixture = PipelineFixture();
final channel = FakeChannel()..readyCompleter.complete();
var sockets = 0;
final client = PipelinesClient(
channelFactory: (_) {
sockets++;
return channel;
},
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')),
);
addTearDown(provider.dispose);
await tester.pumpWidget(
PipelinesApp(
server: webServer(),
client: client,
cupertino: false,
routeInformationProvider: provider,
),
);
await tester.pump();
await replyPipelines(tester, channel, fixture);
// The pipeline browser's own last-run join read is the boot list read.
expect(requestsOf(channel, 'list_runs'), hasLength(1));
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pump();
await replyPipelineDetail(tester, channel, fixture);
await reply(tester, channel, 'list_schedules', 1, {
'type': 'schedules',
'schedules': <dynamic>[],
});
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(runPipelinePromptKey),
'Review the change.',
);
await tester.enterText(find.byKey(runPipelineWorkspaceKey), '/work/alpha');
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pump();
final launches = await waitForCount(tester, channel, 'run_pipeline', 1);
final launch = launches.single;
expect(launch['pipeline_id'], 1);
expect(launch['version'], 2);
expect(launch['workspace'], '/work/alpha');
expect(launch['input'], {'prompt': 'Review the change.'});
expect(launch.containsKey('notify_mode'), isFalse);
channel.incoming.add(
jsonEncode({
'id': launch['id'],
'type': 'run_started',
'run_detail': {
'id': 77,
'pipeline_id': 1,
'title': 'Started from the browser',
'status': 'running',
},
}),
);
await tester.pump();
await tester.pump();
expect(provider.value.uri.path, '/runs/77');
// The Runs destination mounted after the accepted launch and performed the
// one fresh list read; no row came from the run reply.
final lists = await waitForCount(tester, channel, 'list_runs', 2);
expect(lists, hasLength(2));
channel.incoming.add(
jsonEncode({
'id': lists[1]['id'],
'type': 'runs',
'runs': [
...fixture.runs,
{
'id': 77,
'pipeline_id': 1,
'title': 'Started from the browser',
'status': 'running',
},
],
}),
);
final detail = await waitForCount(tester, channel, 'get_run', 1);
expect(detail.single['run_id'], 77);
channel.incoming.add(
jsonEncode({
'id': detail.single['id'],
'type': 'run',
'run_detail': {
'id': 77,
'pipeline_id': 1,
'title': 'Started from the browser',
'status': 'running',
},
}),
);
await tester.pump();
await tester.pumpAndSettle();
expect(find.text('Started from the browser'), findsWidgets);
expect(provider.value.uri.path, '/runs/77');
expect(requestsOf(channel, 'list_runs'), hasLength(2));
expect(requestsOf(channel, 'run_pipeline'), hasLength(1));
expect(sockets, 1);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
}
+38
View File
@@ -0,0 +1,38 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/error_reason.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
void main() {
const fallback = 'The server did not do it.';
test('runtime diagnostics are reduced to the reason itself', () {
expect(
describeErrorReason(StateError('Connection closed'), fallback: fallback),
'Connection closed',
);
expect(
describeErrorReason(Exception('Connection closed'), fallback: fallback),
'Connection closed',
);
});
test('protocol and repository messages stay verbatim', () {
expect(
describeErrorReason(
const ProtocolError('workspace is not allowed'),
fallback: fallback,
),
'workspace is not allowed',
);
expect(
describeErrorReason(' spaced reason ', fallback: fallback),
'spaced reason',
);
});
test('a failure with no text uses the honest fallback', () {
expect(describeErrorReason('', fallback: fallback), fallback);
expect(describeErrorReason(StateError(''), fallback: fallback), fallback);
expect(describeErrorReason('Bad state: ', fallback: fallback), fallback);
});
}
@@ -58,6 +58,11 @@ Future<void> _pumpScreen(
Future<void> _openGraphTab(WidgetTester tester, int pipelineId) async {
await tester.tap(find.byKey(Key('pipeline-row-$pipelineId')));
await tester.pumpAndSettle();
// The detail header scrolls when content-driven title/tab height needs it
// (the header gained the native Run action), so reach the tab like an
// operator would instead of requiring it to fit without scrolling.
await tester.ensureVisible(find.text('Graph'));
await tester.pumpAndSettle();
await tester.tap(find.text('Graph'));
await tester.pump();
await tester.pump();
@@ -0,0 +1,507 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'package:pipelines_app/features/pipelines/ui/run_pipeline_wording.dart';
import '../fixtures.dart';
typedef LaunchHandler = FutureOr<JsonMap> Function(JsonMap fields);
typedef LookupHandler = FutureOr<JsonMap> Function(JsonMap fields);
FakeGateway launchGateway(
PipelineFixture fixture, {
required LaunchHandler onLaunch,
LookupHandler? onLookup,
}) => FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(fixture.summaries),
'list_runs' => runListReply(fixture.runs),
'get_pipeline' => pipelineDetailReply(
fixture.detailFor(
fields['pipeline_id'] as int,
fields['version'] as int,
)!,
),
'list_schedules' => {'type': 'schedules', 'schedules': <dynamic>[]},
'run_pipeline' => onLaunch(fields),
'get_run' when onLookup != null => onLookup(fields),
_ => errorReply('unexpected $type'),
},
);
JsonMap acceptedRun(int id) => {
'type': 'run',
'run_detail': {'id': id, 'status': 'running', 'title': 'Run $id'},
};
JsonMap noRun() => {'type': 'run', 'run_detail': null};
Future<void> pumpScreen(
WidgetTester tester,
FakeGateway gateway,
List<int> navigated, {
bool cupertino = false,
}) async {
tester.view.physicalSize = const Size(1100, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final screen = PipelinesScreen(gateway: gateway, onRunStarted: navigated.add);
await tester.pumpWidget(
cupertino ? CupertinoApp(home: screen) : MaterialApp(home: screen),
);
await tester.pumpAndSettle();
}
Future<void> openDetail(WidgetTester tester) async {
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
}
Future<void> fillFields(
WidgetTester tester, {
String prompt = 'Review the change.',
String workspace = '/work/alpha',
}) async {
await tester.enterText(find.byKey(runPipelinePromptKey), prompt);
await tester.enterText(find.byKey(runPipelineWorkspaceKey), workspace);
await tester.pump();
}
void main() {
testWidgets('the detail Run action sends the web request for the pinned '
'version and opens only the reply run', (tester) async {
final fixture = PipelineFixture();
final navigated = <int>[];
final gateway = launchGateway(
fixture,
onLaunch: (fields) => acceptedRun(77),
);
await pumpScreen(tester, gateway, navigated);
await openDetail(tester);
expect(find.byKey(runPipelineActionKey), findsOneWidget);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
expect(find.text('Run Alpha review'), findsOneWidget);
expect(find.text(runPipelinePromptLabel), findsOneWidget);
expect(find.text(runPipelineWorkspaceLabel), findsOneWidget);
expect(find.text(runPipelineNotifyLabel), findsOneWidget);
expect(find.text(runPipelineCancelLabel), findsOneWidget);
expect(
find.descendant(
of: find.byType(AlertDialog),
matching: find.text(runPipelineConfirmLabel),
),
findsOneWidget,
);
expect(gateway.callsOf('run_pipeline'), isEmpty);
await fillFields(tester, prompt: ' Review the change. ');
await tester.enterText(
find.byKey(runPipelineWorkspaceKey),
'/work/alpha ',
);
await tester.tap(find.byKey(runPipelineNotifyKey));
await tester.pumpAndSettle();
await tester.tap(find.text('Silent').last);
await tester.pumpAndSettle();
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
final fields = gateway.callsOf('run_pipeline').single.fields;
expect(fields, {
'pipeline_id': 1,
'version': 2,
'request_key': fields['request_key'],
'workspace': '/work/alpha',
'input': {'prompt': 'Review the change.'},
'notify_mode': 'off',
});
expect(fields['request_key'], startsWith('app-run-1-2-'));
expect('${fields['request_key']}'.length, lessThanOrEqualTo(128));
expect(navigated, [77]);
expect(find.byType(AlertDialog), findsNothing);
});
testWidgets('a historical version is pinned and Pipeline default omits '
'notify_mode', (tester) async {
final fixture = PipelineFixture();
final navigated = <int>[];
final gateway = launchGateway(
fixture,
onLaunch: (fields) => acceptedRun(78),
);
await pumpScreen(tester, gateway, navigated);
await openDetail(tester);
await tester.tap(find.byKey(const Key('pipeline-version-1')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
await fillFields(tester);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
final fields = gateway.callsOf('run_pipeline').single.fields;
expect(fields['pipeline_id'], 1);
expect(fields['version'], 1);
expect(fields['request_key'], startsWith('app-run-1-1-'));
expect(fields.containsKey('notify_mode'), isFalse);
expect(fields.containsKey('title'), isFalse);
expect(fields.containsKey('output_format'), isFalse);
expect(navigated, [78]);
});
testWidgets(
'prompt and workspace validation match the web and send nothing',
(tester) async {
final fixture = PipelineFixture();
final navigated = <int>[];
final gateway = launchGateway(
fixture,
onLaunch: (fields) => acceptedRun(79),
);
await pumpScreen(tester, gateway, navigated);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(find.text(runPipelinePromptRequired), findsOneWidget);
expect(gateway.callsOf('run_pipeline'), isEmpty);
await fillFields(tester, prompt: 'Do work', workspace: 'relative/path');
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(find.text(runPipelineWorkspaceAbsolute), findsOneWidget);
expect(gateway.callsOf('run_pipeline'), isEmpty);
expect(navigated, isEmpty);
// The browser checks the field as typed, so a leading space is not an
// absolute path even though the sent workspace is trimmed.
await fillFields(tester, prompt: 'Do work', workspace: ' /work/alpha');
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(find.text(runPipelineWorkspaceAbsolute), findsOneWidget);
expect(gateway.callsOf('run_pipeline'), isEmpty);
expect(navigated, isEmpty);
await fillFields(tester, prompt: 'Do work', workspace: '/work/alpha ');
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(gateway.callsOf('run_pipeline'), hasLength(1));
expect(
gateway.callsOf('run_pipeline').single.fields['workspace'],
'/work/alpha',
);
expect(navigated, [79]);
},
);
testWidgets('a double confirmation sends exactly one request', (
tester,
) async {
final fixture = PipelineFixture();
final navigated = <int>[];
final pending = Completer<JsonMap>();
final gateway = launchGateway(fixture, onLaunch: (_) => pending.future);
await pumpScreen(tester, gateway, navigated);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
await fillFields(tester);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pump();
expect(find.text(runPipelineSendingLabel), findsOneWidget);
expect(gateway.callsOf('run_pipeline'), hasLength(1));
pending.complete(acceptedRun(80));
await tester.pumpAndSettle();
expect(gateway.callsOf('run_pipeline'), hasLength(1));
expect(navigated, [80]);
});
testWidgets('a server refusal keeps the dialog with its own reason and a '
'corrected attempt uses a fresh key', (tester) async {
final fixture = PipelineFixture();
final navigated = <int>[];
var attempts = 0;
final keys = <String>[];
final gateway = launchGateway(
fixture,
onLaunch: (fields) {
attempts++;
keys.add(fields['request_key'] as String);
if (attempts == 1) {
throw const ProtocolError('workspace is not allowed');
}
return acceptedRun(81);
},
onLookup: (_) => noRun(),
);
await pumpScreen(tester, gateway, navigated);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
await fillFields(tester);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text('workspace is not allowed'), findsOneWidget);
expect(find.text(runPipelineCheckRetryLabel), findsNothing);
expect(navigated, isEmpty);
// The refusal was proven not admitted, so the fields unlock and a new
// deliberate attempt mints its own key.
await tester.enterText(
find.byKey(runPipelineWorkspaceKey),
'/work/allowed',
);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(keys, hasLength(2));
expect(keys[0], isNot(equals(keys[1])));
expect(navigated, [81]);
expect(find.byType(AlertDialog), findsNothing);
});
testWidgets('a lost reply is honest and the same key reconciles before one '
'resend', (tester) async {
final fixture = PipelineFixture();
final navigated = <int>[];
final keys = <String>[];
final lookups = <String>[];
var attempts = 0;
final gateway = launchGateway(
fixture,
onLaunch: (fields) {
attempts++;
keys.add(fields['request_key'] as String);
if (attempts == 1) throw StateError('Connection closed');
return acceptedRun(82);
},
onLookup: (fields) {
lookups.add(fields['request_key'] as String);
return noRun();
},
);
await pumpScreen(tester, gateway, navigated);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
await fillFields(tester);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.textContaining('Admission may be unknown'), findsOneWidget);
expect(find.textContaining('Bad state'), findsNothing);
expect(
find.text('Connection closed$runPipelineUnknownSuffix'),
findsOneWidget,
);
expect(find.text(runPipelineCheckRetryLabel), findsOneWidget);
expect(navigated, isEmpty);
// The fields stay locked while admission is unknown.
final prompt = tester.widget<TextField>(find.byKey(runPipelinePromptKey));
expect(prompt.enabled, isFalse);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(lookups, hasLength(1));
expect(lookups.single, keys.first);
expect(keys, hasLength(2));
expect(keys[1], keys[0]);
expect(navigated, [82]);
expect(find.byType(AlertDialog), findsNothing);
});
testWidgets('an admitted run found by key opens without a second launch', (
tester,
) async {
final fixture = PipelineFixture();
final navigated = <int>[];
var attempts = 0;
final gateway = launchGateway(
fixture,
onLaunch: (fields) {
attempts++;
throw StateError('Connection closed');
},
onLookup: (_) => acceptedRun(83),
);
await pumpScreen(tester, gateway, navigated);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
await fillFields(tester);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(attempts, 1);
expect(gateway.callsOf('run_pipeline'), hasLength(1));
expect(navigated, [83]);
});
testWidgets('a refusal whose by-key read finds an admitted run opens it', (
tester,
) async {
final fixture = PipelineFixture();
final navigated = <int>[];
final gateway = launchGateway(
fixture,
onLaunch: (_) => throw const ProtocolError('workspace is not allowed'),
onLookup: (_) => acceptedRun(85),
);
await pumpScreen(tester, gateway, navigated);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
await fillFields(tester);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(gateway.callsOf('run_pipeline'), hasLength(1));
expect(navigated, [85]);
expect(find.byType(AlertDialog), findsNothing);
});
testWidgets('closing and reopening an unknown launch restores check/retry', (
tester,
) async {
final fixture = PipelineFixture();
final navigated = <int>[];
final keys = <String>[];
var attempts = 0;
final gateway = launchGateway(
fixture,
onLaunch: (fields) {
attempts++;
keys.add(fields['request_key'] as String);
if (attempts == 1) throw StateError('Connection closed');
return acceptedRun(86);
},
onLookup: (_) => noRun(),
);
await pumpScreen(tester, gateway, navigated);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
await fillFields(tester);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(find.text(runPipelineCheckRetryLabel), findsOneWidget);
// Cancel only closes the dialog; the unresolved intent stays with it.
await tester.tap(find.byKey(runPipelineCancelKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
expect(find.text(runPipelineUnknownAdmission), findsOneWidget);
expect(find.text(runPipelineCheckRetryLabel), findsOneWidget);
expect(
tester
.widget<TextField>(find.byKey(runPipelinePromptKey))
.controller
?.text,
'Review the change.',
);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
expect(keys, hasLength(2));
expect(keys[1], keys[0]);
expect(navigated, [86]);
});
testWidgets('the Cupertino host shows the same native prompt and words', (
tester,
) async {
final fixture = PipelineFixture();
final navigated = <int>[];
final gateway = launchGateway(
fixture,
onLaunch: (fields) => acceptedRun(84),
);
await pumpScreen(tester, gateway, navigated, cupertino: true);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
expect(find.text('Run Alpha review'), findsOneWidget);
expect(find.text(runPipelinePromptLabel), findsOneWidget);
expect(find.text(runPipelineWorkspaceLabel), findsOneWidget);
expect(find.text(runPipelineNotifyLabel), findsOneWidget);
expect(
find.descendant(
of: find.byType(CupertinoAlertDialog),
matching: find.text(runPipelineConfirmLabel),
),
findsOneWidget,
);
expect(find.text(runPipelineCancelLabel), findsOneWidget);
expect(gateway.callsOf('run_pipeline'), isEmpty);
await tester.tap(find.byKey(runPipelineCancelKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsNothing);
expect(gateway.callsOf('run_pipeline'), isEmpty);
});
testWidgets('Cupertino field labels and helper use theme label roles', (
tester,
) async {
final fixture = PipelineFixture();
final gateway = launchGateway(
fixture,
onLaunch: (fields) => acceptedRun(87),
);
await pumpScreen(tester, gateway, <int>[], cupertino: true);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
final context = tester.element(find.byType(CupertinoAlertDialog));
final theme = CupertinoTheme.of(context);
final labelStyle = theme.textTheme.textStyle;
for (final label in [
runPipelinePromptLabel,
runPipelineWorkspaceLabel,
runPipelineNotifyLabel,
]) {
final style = tester.widget<Text>(find.text(label)).style;
expect(style?.color, labelStyle.color, reason: label);
expect(style?.fontSize, labelStyle.fontSize, reason: label);
}
final helper = tester
.widget<Text>(find.text(runPipelineWorkspaceHelper))
.style;
expect(
helper?.color,
CupertinoColors.secondaryLabel.resolveFrom(context),
);
expect(
helper?.fontSize,
theme.textTheme.tabLabelTextStyle.fontSize,
);
});
}
@@ -0,0 +1,70 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/screen.dart';
class _Gateway implements ApiGateway {
final listRequests = <Completer<JsonMap>>[];
final detailRequests = <num>[];
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'list_runs') {
final request = Completer<JsonMap>();
listRequests.add(request);
return request.future;
}
if (type == 'get_run') {
detailRequests.add(fields['run_id'] as num);
return Completer<JsonMap>().future;
}
return Future.error(UnsupportedError(type));
}
}
Widget _screen(_Gateway gateway, int token) => MaterialApp(
home: Scaffold(
body: RunsScreen(gateway: gateway, listRefreshToken: token),
),
);
void main() {
testWidgets('an accepted launch invalidates a mounted list with one fresh '
'read and no detail read', (tester) async {
final gateway = _Gateway();
await tester.pumpWidget(_screen(gateway, 0));
await tester.pump();
expect(gateway.listRequests, hasLength(1));
gateway.listRequests[0].complete({
'runs': [
{'id': 1, 'title': 'Old run', 'status': 'succeeded'},
],
});
await tester.pump();
await tester.pump();
expect(find.text('Old run'), findsOneWidget);
await tester.pumpWidget(_screen(gateway, 1));
await tester.pump();
expect(gateway.listRequests, hasLength(2));
// No row is invented while the fresh read is outstanding.
expect(find.text('New run'), findsNothing);
gateway.listRequests[1].complete({
'runs': [
{'id': 2, 'title': 'New run', 'status': 'running'},
{'id': 1, 'title': 'Old run', 'status': 'succeeded'},
],
});
await tester.pump();
await tester.pump();
expect(find.text('New run'), findsOneWidget);
expect(gateway.listRequests, hasLength(2));
expect(gateway.detailRequests, isEmpty);
});
}
+20
View File
@@ -0,0 +1,20 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:pipelines_app/application/bootstrap.dart';
/// Browser acceptance entrypoint for the start-a-pipeline wiring probe.
///
/// This is the normal app composition; pipelines, the run reply and the fresh
/// runs list come from the isolated loopback fixture in
/// `tool/run_pipeline_probe.mjs`, never from app-side fake data.
void main() {
FlutterError.onError = (details) {
debugPrint('FLUTTER ERROR: ${details.exceptionAsString()}');
FlutterError.presentError(details);
};
runZonedGuarded(
runPipelinesApp,
(error, stack) => debugPrint('ZONE ERROR: $error\n$stack'),
);
}
+759
View File
@@ -0,0 +1,759 @@
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, rm, writeFile, readFile, realpath, stat } from 'node:fs/promises';
import { once } from 'node:events';
import { createServer } from 'node:http';
import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import { extname, join, resolve, sep } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
// Real-browser acceptance for starting a pipeline run.
//
// Usage (from app/):
// flutter build web --target=tool/run_pipeline_probe.dart -o build/run_probe_web
// OPENCODE_ARTIFACT_DIR=<dir> node tool/run_pipeline_probe.mjs build/run_probe_web
//
// The fixture serves the real bundle over loopback and answers the same
// websocket protocol as the app server: one pipeline, its detail, an empty run
// list, and `run_pipeline`/`get_run`. It records the exact launch payload and
// creates the run only after that request, so the real app must open the id the
// server named and re-read its runs list. Both host control sets are exercised.
const output = process.env.OPENCODE_ARTIFACT_DIR;
if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures');
await mkdir(output, { recursive: true });
const chromePath =
process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const root = await realpath(process.argv[2] ?? 'build/run_probe_web');
const PIPELINE = {
id: 1,
name: 'Release review',
version: 2,
stages: 1,
created_at: '2026-10-20T09:00:00Z',
updated_at: '2026-10-21T09:00:00Z',
scheduled: false,
schedule_count: 0,
enabled_schedule_count: 0,
};
const DETAIL = {
...PIPELINE,
latest_version: 2,
version_created_at: '2026-10-21T09:00:00Z',
content_hash: 'probe-hash',
source: 'name: Release review\nstages:\n publish:\n type: model',
versions: [{ version: 2, stages: 1, created_at: '2026-10-21T09:00:00Z' }],
};
const runs = new Map();
const admittedByKey = new Map();
const launches = [];
const counters = { listRuns: 0, getRun: 0, getByKey: 0 };
let nextRunId = 100;
function runRow(run) {
return {
id: run.id,
pipeline_id: run.pipeline_id,
title: run.title,
name: run.name,
version: run.version,
status: run.status,
executing: run.executing,
created_at: run.created_at,
finished_at: run.finished_at,
};
}
function runDetail(run) {
return {
...runRow(run),
input: { prompt: run.prompt },
steps: [],
};
}
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.wasm': 'application/wasm',
'.css': 'text/css; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
function accept(key) {
return createHash('sha1')
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
.digest('base64');
}
function frame(opcode, payload) {
const length = payload.length;
let header;
if (length < 126) {
header = Buffer.from([0x80 | opcode, length]);
} else if (length < 65536) {
header = Buffer.alloc(4);
header[0] = 0x80 | opcode;
header[1] = 126;
header.writeUInt16BE(length, 2);
} else {
header = Buffer.alloc(10);
header[0] = 0x80 | opcode;
header[1] = 127;
header.writeBigUInt64BE(BigInt(length), 2);
}
return Buffer.concat([header, payload]);
}
class Connection {
constructor(socket) {
this.socket = socket;
this.buffer = Buffer.alloc(0);
}
push(chunk) {
if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]);
while (this.buffer.length >= 2) {
const first = this.buffer[0];
const second = this.buffer[1];
const opcode = first & 0x0f;
let length = second & 0x7f;
let offset = 2;
if (length === 126) {
if (this.buffer.length < 4) return;
length = this.buffer.readUInt16BE(2);
offset = 4;
} else if (length === 127) {
if (this.buffer.length < 10) return;
length = Number(this.buffer.readBigUInt64BE(2));
offset = 10;
}
const masked = (second & 0x80) !== 0;
const maskOffset = offset;
if (masked) {
if (this.buffer.length < offset + 4) return;
offset += 4;
}
if (this.buffer.length < offset + length) return;
let payload = Buffer.from(this.buffer.subarray(offset, offset + length));
if (masked) {
const mask = this.buffer.subarray(maskOffset, maskOffset + 4);
for (let index = 0; index < payload.length; index++) {
payload[index] ^= mask[index % 4];
}
}
this.buffer = this.buffer.subarray(offset + length);
if (opcode === 0x8) return this.close();
if (opcode === 0x9) {
this.socket.write(frame(0x0a, payload));
continue;
}
if (opcode !== 0x1) continue;
let request;
try {
request = JSON.parse(payload.toString('utf8'));
} catch {
continue;
}
this.message(request);
}
}
message(request) {
if (request.type === 'unsubscribe') return;
if (request.type === 'subscribe') {
this.send({ id: request.id, type: 'subscribe' });
return;
}
if (request.type === 'ping') {
this.send({ id: request.id, type: 'pong', build: { version: 'Run fixture' } });
return;
}
if (request.type === 'list_pipelines') {
this.send({ id: request.id, type: 'pipelines', pipelines: [PIPELINE] });
return;
}
if (request.type === 'get_pipeline') {
if (request.pipeline_id !== PIPELINE.id || request.version !== 2) {
this.send({ id: request.id, type: 'error', error: 'pipeline not found' });
return;
}
this.send({ id: request.id, type: 'pipeline', detail: DETAIL });
return;
}
if (request.type === 'list_schedules') {
this.send({ id: request.id, type: 'schedules', schedules: [] });
return;
}
if (request.type === 'list_runs') {
counters.listRuns++;
this.send({
id: request.id,
type: 'runs',
runs: [...runs.values()].map(runRow),
usage: null,
});
return;
}
if (request.type === 'get_run') {
if (typeof request.request_key === 'string') {
counters.getByKey++;
const admitted = admittedByKey.get(request.request_key);
this.send({
id: request.id,
type: 'run',
run_detail: admitted ? runDetail(admitted) : null,
});
return;
}
counters.getRun++;
const run = runs.get(request.run_id);
if (!run) {
this.send({ id: request.id, type: 'error', error: `no run ${request.run_id}` });
return;
}
this.send({ id: request.id, type: 'run', run_detail: runDetail(run) });
return;
}
if (request.type === 'run_pipeline') {
const record = {
keys: Object.keys(request).filter((key) => !['type', 'id'].includes(key)).sort(),
pipeline_id: request.pipeline_id,
version: request.version,
request_key: request.request_key,
workspace: request.workspace,
input: request.input,
};
launches.push(record);
if (!request.request_key) {
this.send({ id: request.id, type: 'error', error: 'run_pipeline requires a request key' });
return;
}
// The server's idempotency contract: one admitted run per request key.
let run = admittedByKey.get(request.request_key);
if (!run) {
const id = nextRunId++;
run = {
id,
pipeline_id: request.pipeline_id,
title: `Probe run ${id}`,
name: PIPELINE.name,
version: request.version,
status: 'running',
executing: true,
created_at: '2026-10-22T00:00:00Z',
finished_at: '',
prompt: request.input?.prompt ?? '',
};
runs.set(id, run);
admittedByKey.set(request.request_key, run);
}
this.send({ id: request.id, type: 'run_started', run_detail: runDetail(run) });
this.send({
type: 'run_event',
run_id: run.id,
pipeline_id: run.pipeline_id,
name: run.name,
title: run.title,
version: run.version,
status: run.status,
created_at: run.created_at,
finished_at: '',
});
return;
}
this.send({ id: request.id, type: 'error', error: `Fixture does not implement ${request.type}` });
}
send(value) {
if (!this.socket.destroyed) {
this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value))));
}
}
close() {
if (!this.socket.destroyed) this.socket.end();
}
}
async function staticFile(base, pathname, res) {
let file = resolve(base, `.${pathname}`);
if (file !== base && !file.startsWith(base + sep)) {
res.writeHead(403).end();
return;
}
try {
if ((await stat(file)).isDirectory()) file = join(file, 'index.html');
} catch {
if (extname(pathname)) {
res.writeHead(404).end('not found');
return;
}
file = join(base, 'index.html');
}
try {
const body = await readFile(file);
res
.writeHead(200, {
'content-type': MIME[extname(file)] ?? 'application/octet-stream',
'cache-control': 'no-store',
})
.end(body);
} catch {
res.writeHead(404).end('not found');
}
}
const sockets = new Set();
const server = createServer(async (req, res) => {
const pathname = new URL(req.url, 'http://fixture').pathname;
if (pathname === '/fixture/state') {
res
.writeHead(200, { 'content-type': 'application/json' })
.end(JSON.stringify({ launches, runs: [...runs.values()], ...counters }));
return;
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405).end();
return;
}
await staticFile(root, pathname, res);
});
server.on('upgrade', (req, socket, head) => {
const url = new URL(req.url, 'http://fixture');
if (
url.pathname !== '/connect' ||
req.headers.upgrade?.toLowerCase() !== 'websocket' ||
!req.headers['sec-websocket-key']
) {
socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
return;
}
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
`Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`,
);
const connection = new Connection(socket);
socket.on('data', (chunk) => connection.push(chunk));
socket.on('error', () => socket.destroy());
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
connection.push(head);
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const fixtureUrl = `http://127.0.0.1:${server.address().port}`;
const profile = await mkdtemp(join(tmpdir(), 'p3-run-chrome-'));
const chrome = spawn(
chromePath,
[
'--headless=new',
'--no-first-run',
'--no-default-browser-check',
'--disable-gpu',
'--remote-debugging-port=0',
`--user-data-dir=${profile}`,
'about:blank',
],
{ stdio: ['ignore', 'ignore', 'pipe'] },
);
let stderr = '';
chrome.stderr.on('data', (data) => {
stderr += data;
});
async function waitFor(check, label, attempts = 200) {
for (let attempt = 0; attempt < attempts; attempt++) {
const value = await check();
if (value) return value;
await delay(100);
}
throw new Error(`Timed out waiting for ${label}\n${stderr.slice(-1200)}`);
}
let ws;
try {
const endpoint = await waitFor(
() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
'Chrome DevTools',
);
ws = new WebSocket(endpoint);
await once(ws, 'open');
let id = 0;
const pending = new Map();
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') {
console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails));
}
if (message.method === 'Runtime.consoleAPICalled') {
const values = (message.params?.args ?? []).map((arg) => arg.value ?? arg.description);
if (values.some((value) => String(value).includes('ERROR'))) {
console.error('PAGE CONSOLE', values.join(' '));
}
}
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
});
const send = (method, params = {}, sessionId) =>
new Promise((resolveCall) => {
const callId = ++id;
pending.set(callId, resolveCall);
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId;
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
const evaluate = async (expression) => {
const response = await send(
'Runtime.evaluate',
{ expression, returnByValue: true, awaitPromise: true },
session,
);
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
if (response.result?.exceptionDetails) {
throw new Error(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`);
}
return response.result?.result?.value;
};
const enableSemantics = async () => {
await waitFor(
() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),
'Flutter semantics placeholder',
);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(700);
};
const semanticText = () =>
evaluate(`(() => {
const chunks = [];
for (const el of document.querySelectorAll('flt-semantics')) {
const label = el.getAttribute('aria-label');
if (label) chunks.push(label);
const value = el.getAttribute('aria-valuetext');
if (value) chunks.push(value);
if (el.value) chunks.push(String(el.value));
if (!el.children.length && el.innerText) chunks.push(el.innerText);
}
for (const el of document.querySelectorAll('input, textarea')) {
const label = el.getAttribute('aria-label');
if (label) chunks.push(label);
if (el.placeholder) chunks.push(el.placeholder);
if (el.value) chunks.push(String(el.value));
}
if (document.body?.innerText) chunks.push(document.body.innerText);
return [...new Set(chunks)].join('\\n');
})()`);
const assertBody = async (text) => {
try {
await waitFor(
async () => (await semanticText()).includes(text),
`body to contain ${JSON.stringify(text)}`,
);
} catch (error) {
throw new Error(`${error.message}\nBody now:\n${(await semanticText()).slice(0, 3000)}`);
}
};
const clickText = async (text, { last = false } = {}) => {
const attemptClick = () => evaluate(`(() => {
const wanted = ${JSON.stringify(text)};
const all = [...document.querySelectorAll('flt-semantics')].filter((el) => {
const label = (el.getAttribute('aria-label') || el.innerText || '').trim();
return label === wanted;
});
const candidates = all.filter((el) =>
['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')),
);
const pool = candidates.length ? candidates : all;
const target = ${last ? 'pool.at(-1)' : 'pool[0]'};
if (!target) return false;
target.click();
return true;
})()`);
let clicked = false;
for (let attempt = 0; attempt < 25 && !clicked; attempt++) {
clicked = await attemptClick();
if (!clicked) await delay(120);
}
if (!clicked) {
const labels = await evaluate(`[...document.querySelectorAll('flt-semantics')]
.map((el) => (el.getAttribute('aria-label') || el.innerText || '').trim()).filter(Boolean)`);
throw new Error(`Could not click ${JSON.stringify(text)}. Labels: ${JSON.stringify(labels)}`);
}
await delay(400);
};
const clickContains = async (text) => {
const clicked = await evaluate(`(() => {
const wanted = ${JSON.stringify(text)};
const all = [...document.querySelectorAll('flt-semantics')].filter((el) => {
const label = (el.getAttribute('aria-label') || el.innerText || '').trim();
return label.includes(wanted);
});
const target = all.find((el) =>
['button', 'link', 'tab', 'row'].includes(el.getAttribute('role')),
) ?? all.at(-1);
if (!target) return false;
target.click();
return true;
})()`);
if (!clicked) throw new Error(`Could not click a row containing ${JSON.stringify(text)}`);
await delay(500);
};
const capture = async (name) => {
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
const path = join(output, `${name}.png`);
await writeFile(path, Buffer.from(data, 'base64'));
return path;
};
const focusField = async (hint) => {
const focused = await evaluate(`(() => {
const nodes = [...document.querySelectorAll('input, textarea')];
const wanted = ${JSON.stringify(hint)};
const node = nodes.find((el) =>
(el.placeholder || '').includes(wanted) ||
(el.getAttribute('aria-label') || '').includes(wanted)
) ?? (wanted.includes('absolute')
? nodes.find((el) => el.tagName === 'INPUT')
: nodes.find((el) => el.tagName === 'TEXTAREA'))
?? nodes.find((el) => el.tagName === 'INPUT')
?? nodes[0];
if (!node) return false;
window.__probeField = node;
node.focus();
node.setSelectionRange?.(0, (node.value || '').length);
return true;
})()`);
if (!focused) throw new Error(`No editable node for ${JSON.stringify(hint)}`);
await delay(250);
};
const typeText = async (text) => {
await send('Input.insertText', { text }, session);
await delay(350);
};
const clearAndType = async (hint, text) => {
await focusField(hint);
const selected = await evaluate(`(() => {
const node = window.__probeField;
if (!node) return false;
node.focus();
node.setSelectionRange?.(0, (node.value || '').length);
return true;
})()`);
if (!selected) throw new Error(`Could not select the ${JSON.stringify(hint)} field`);
await typeText(text);
};
const state = async () => (await (await fetch(`${fixtureUrl}/fixture/state`)).json());
const setView = async ({ width, height, deviceScaleFactor = 1 }) => {
await send(
'Emulation.setDeviceMetricsOverride',
{ width, height, deviceScaleFactor, mobile: width < 600 },
session,
);
await send(
'Emulation.setEmulatedMedia',
{ features: [{ name: 'prefers-color-scheme', value: 'dark' }] },
session,
);
await delay(500);
};
const openPipelines = async () => {
const navigation = await send(
'Page.navigate',
{ url: `${fixtureUrl}/pipelines` },
session,
);
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
await enableSemantics();
await assertBody('Release review');
};
const openPipelineDetail = async () => {
await clickContains('Release review');
await assertBody('Summary');
await assertBody('Run');
if ((await evaluate('location.pathname')) !== '/pipelines') {
throw new Error(`Detail moved to ${await evaluate('location.pathname')}`);
}
};
const dialogOpen = async () => (await semanticText()).includes('Run Release review');
const dialogClosed = async () => !(await dialogOpen());
const assertPayload = (record, check) => {
if (!record) throw new Error(`${check}: no launch recorded`);
const expected = ['input', 'pipeline_id', 'request_key', 'version', 'workspace'];
if (JSON.stringify(record.keys) !== JSON.stringify(expected)) {
throw new Error(`${check}: unexpected request fields ${JSON.stringify(record)}`);
}
if (record.pipeline_id !== 1 || record.version !== 2) {
throw new Error(`${check}: wrong pinned identity ${JSON.stringify(record)}`);
}
if (record.workspace !== '/work/release') {
throw new Error(`${check}: wrong workspace ${JSON.stringify(record)}`);
}
if (record.input?.prompt !== 'Review the release.') {
throw new Error(`${check}: wrong prompt ${JSON.stringify(record.input)}`);
}
if (!String(record.request_key).startsWith('app-run-1-2-')) {
throw new Error(`${check}: wrong request key ${record.request_key}`);
}
if (String(record.request_key).length > 128) {
throw new Error(`${check}: request key too long ${record.request_key}`);
}
return record;
};
const waitRun = async (id) => {
await waitFor(
async () => (await evaluate('location.pathname')) === `/runs/${id}`,
`the route to open run ${id}`,
);
await assertBody(`Probe run ${id}`);
};
const captures = [];
const checks = [];
await setView({ width: 420, height: 900 });
await openPipelines();
captures.push(await capture('p3-run-cupertino-list'));
await openPipelineDetail();
captures.push(await capture('p3-run-cupertino-detail'));
// Opening and Cancel send nothing.
await clickText('Run');
await waitFor(dialogOpen, 'the launch dialog');
await assertBody('Prompt');
await assertBody('Working directory (on the server)');
await assertBody('Notifications for this run');
await assertBody('Cancel');
captures.push(await capture('p3-run-cupertino-dialog'));
await clickText('Cancel');
await waitFor(dialogClosed, 'the cancelled dialog');
if ((await state()).launches.length !== 0) throw new Error('Cancel sent run_pipeline');
checks.push({ check: 'Cupertino Cancel sent nothing', sent: 0 });
// Both local validations, exactly as the web.
await clickText('Run');
await waitFor(dialogOpen, 'the launch dialog again');
await clickText('Run', { last: true });
await assertBody('Enter a prompt for this run.');
captures.push(await capture('p3-run-cupertino-prompt-validation'));
if ((await state()).launches.length !== 0) throw new Error('Validation sent run_pipeline');
await focusField('What should this run do?');
await typeText('Review the release.');
await clearAndType('/absolute/path/on/the/server', 'relative/path');
await clickText('Run', { last: true });
await assertBody('Choose an absolute working directory on the server.');
captures.push(await capture('p3-run-cupertino-workspace-validation'));
if ((await state()).launches.length !== 0) throw new Error('Workspace validation sent run_pipeline');
await clearAndType('/absolute/path/on/the/server', '/work/release');
const beforeRunsList = (await state()).listRuns;
await clickText('Run', { last: true });
await waitFor(async () => (await state()).launches.length === 1, 'the Cupertino launch request');
const cupertinoLaunch = assertPayload((await state()).launches[0], 'Cupertino launch');
await waitRun(100);
const afterRunsList = (await state()).listRuns;
if (afterRunsList <= beforeRunsList) {
throw new Error('The accepted launch did not trigger a fresh runs list read');
}
captures.push(await capture('p3-run-cupertino-run-detail'));
checks.push({
check: 'Cupertino dialog → validation → accepted run detail',
launch: cupertinoLaunch,
listReads: afterRunsList - beforeRunsList,
path: await evaluate('location.pathname'),
});
// Material host: the same normal bundle after a Linux browser identity.
await send(
'Emulation.setUserAgentOverride',
{
userAgent:
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
platform: 'Linux x86_64',
},
session,
);
await openPipelines();
await openPipelineDetail();
captures.push(await capture('p3-run-material-detail'));
await clickText('Run');
await waitFor(dialogOpen, 'the material launch dialog');
await assertBody('Prompt');
captures.push(await capture('p3-run-material-dialog'));
await clickText('Run', { last: true });
await assertBody('Enter a prompt for this run.');
captures.push(await capture('p3-run-material-validation'));
if ((await state()).launches.length !== 1) throw new Error('Material validation sent run_pipeline');
await focusField('What should this run do?');
await typeText('Review the release.');
await clearAndType('/absolute/path/on/the/server', 'relative/path');
await clickText('Run', { last: true });
await assertBody('Choose an absolute working directory on the server.');
await clearAndType('/absolute/path/on/the/server', '/work/release');
const beforeMaterialList = (await state()).listRuns;
await clickText('Run', { last: true });
await waitFor(async () => (await state()).launches.length === 2, 'the Material launch request');
const materialLaunch = assertPayload((await state()).launches[1], 'Material launch');
await waitRun(101);
const afterMaterialList = (await state()).listRuns;
if (afterMaterialList <= beforeMaterialList) {
throw new Error('The Material acceptance did not trigger a fresh runs list read');
}
captures.push(await capture('p3-run-material-run-detail'));
checks.push({
check: 'Material dialog → validation → accepted run detail',
launch: materialLaunch,
listReads: afterMaterialList - beforeMaterialList,
path: await evaluate('location.pathname'),
});
const finalState = await state();
if (finalState.launches.length !== 2) {
throw new Error(`Expected two launches, saw ${JSON.stringify(finalState.launches)}`);
}
if (finalState.runs.length !== 2) {
throw new Error(`Expected two server-created runs, saw ${JSON.stringify(finalState.runs)}`);
}
console.log(JSON.stringify({ ok: true, fixture: fixtureUrl, checks, captures }, null, 2));
} finally {
ws?.close();
for (const socket of sockets) socket.destroy();
await new Promise((resolveClose) => server.close(resolveClose));
chrome.kill('SIGTERM');
await Promise.race([once(chrome, 'exit'), delay(3000)]);
await rm(profile, { recursive: true, force: true });
}