diff --git a/app/lib/features/runs/actions/title_action.dart b/app/lib/features/runs/actions/title_action.dart new file mode 100644 index 00000000..7a5b9b97 --- /dev/null +++ b/app/lib/features/runs/actions/title_action.dart @@ -0,0 +1,109 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'title_dialog.dart'; +import 'title_wording.dart'; + +/// The run detail's rename entry point, mirroring the browser's rename row. +/// +/// The prompt starts with [run]'s stored title exactly as the server sent it +/// (never a prompt or output fallback). Typing and Cancel send nothing; only +/// Save sends `set_run_title` with the exact run id and title text. A refusal is +/// returned verbatim to the kept-open prompt, and only the server's returned +/// `run_detail` is delivered through [onRunChanged], once. +class RunTitleAction extends StatefulWidget { + const RunTitleAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RunTitleActionState(); +} + +class _RunTitleActionState extends State { + bool _dialogOpen = false; + bool _saving = false; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = runTitleId(widget.run); + if (id == null || _dialogOpen) return; + _dialogOpen = true; + try { + await showRunTitlePrompt( + context: context, + runId: id, + initialTitle: storedRunTitle(widget.run), + cupertino: _usesCupertino(context), + onSubmit: (title) => _submit(id, title), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, String title) async { + if (_saving) return const ActionRefusal(actionAlreadySending); + _saving = true; + try { + final run = await RunsRepository(widget.gateway).setRunTitle(id, title); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal(describeTitleError(error)); + } finally { + _saving = false; + } + } + + bool _owns(num id) => mounted && runTitleId(widget.run) == id; + + @override + Widget build(BuildContext context) { + if (runTitleId(widget.run) == null) return const SizedBox.shrink(); + if (_usesCupertino(context)) { + return CupertinoButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } + return OutlinedButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } +} + +/// The run id used by the rename request, or null for a malformed run. +num? runTitleId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} + +/// The run's stored title exactly as the browser reads it +/// (`String(d.title ?? "")`); never inferred from the prompt or output. +String storedRunTitle(JsonMap run) { + final title = run['title']; + return title == null ? '' : '$title'; +} diff --git a/app/lib/features/runs/actions/title_dialog.dart b/app/lib/features/runs/actions/title_dialog.dart new file mode 100644 index 00000000..9ae03a11 --- /dev/null +++ b/app/lib/features/runs/actions/title_dialog.dart @@ -0,0 +1,183 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'title_wording.dart'; + +/// Sends the typed title. Returns null once the server has accepted it, or an +/// [ActionRefusal] carrying the server's words verbatim; the prompt then stays +/// open with the typed title intact. +typedef TitleSubmit = Future Function(String title); + +/// Opens the native rename prompt for [runId], seeded with the run's stored +/// [initialTitle]. +/// +/// Typing and the dismiss action send nothing; only Save sends the title. The +/// title is passed through exactly as typed, including surrounding whitespace, +/// matching `setRunTitle` in `web/src/repository.js`; the server decides whether +/// a blank title is acceptable. +Future showRunTitlePrompt({ + required BuildContext context, + required num runId, + required String initialTitle, + required bool cupertino, + required TitleSubmit onSubmit, +}) { + final prompt = _TitlePrompt( + runId: runId, + initialTitle: initialTitle, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _TitlePrompt extends StatefulWidget { + const _TitlePrompt({ + required this.runId, + required this.initialTitle, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final String initialTitle; + final bool cupertino; + final TitleSubmit onSubmit; + + @override + State<_TitlePrompt> createState() => _TitlePromptState(); +} + +class _TitlePromptState extends State<_TitlePrompt> { + late final TextEditingController _title = TextEditingController( + text: widget.initialTitle, + ); + bool _sending = false; + String? _error; + + @override + void dispose() { + _title.dispose(); + super.dispose(); + } + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _save() async { + if (_sending) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(_title.text); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _sending = false; + _error = refusal.message; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: const Text(runTitleDialogTitle), + content: _body( + field: TextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + decoration: const InputDecoration(labelText: runTitleFieldLabel), + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle(color: theme.colorScheme.error), + ), + actions: [ + TextButton( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + FilledButton( + key: runTitleSaveKey, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: const Text(runTitleDialogTitle), + content: _body( + field: CupertinoTextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + placeholder: runTitleFieldLabel, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + CupertinoDialogAction( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + CupertinoDialogAction( + key: runTitleSaveKey, + isDefaultAction: true, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _body({required Widget field, required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + field, + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: runTitleErrorKey, style: errorStyle), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/title_wording.dart b/app/lib/features/runs/actions/title_wording.dart new file mode 100644 index 00000000..8fa85891 --- /dev/null +++ b/app/lib/features/runs/actions/title_wording.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's rename wording, kept verbatim. +const runTitleActionLabel = 'Rename'; +const runTitleDialogTitle = 'Rename'; +const runTitleFieldLabel = 'Run title'; +const runTitleSaveLabel = 'Save'; +const runTitleCancelLabel = 'Cancel'; + +/// Stable test/semantics keys shared by the action and its prompt. +const runTitleActionKey = ValueKey('rename-run-action'); +const runTitleFieldKey = ValueKey('rename-run-field'); +const runTitleSaveKey = ValueKey('rename-run-save'); +const runTitleCancelKey = ValueKey('rename-run-cancel'); +const runTitleErrorKey = ValueKey('rename-run-error'); + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a rename that did not happen. +String describeTitleError(Object error) { + final message = '$error'; + return message.trim().isEmpty + ? 'The server did not rename the run.' + : message; +} diff --git a/app/notes/R2d.md b/app/notes/R2d.md new file mode 100644 index 00000000..c262351f --- /dev/null +++ b/app/notes/R2d.md @@ -0,0 +1,93 @@ +# R2d — native run title rename + +## What changed + +New `lib/features/runs/actions/title*` slice plus its tests and this note. No +existing source file was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/title_wording.dart` | 24 | Web-verbatim words, test keys, refusal wording | +| `lib/features/runs/actions/title_dialog.dart` | 183 | Native Material/Cupertino text-field prompt and inline refusal | +| `lib/features/runs/actions/title_action.dart` | 109 | `RunTitleAction`, stored-title seeding, send/deliver orchestration | +| `test/features/runs/actions/title_test_support.dart` | 110 | Fake gateway, run fixtures, stateful host, app wrappers | +| `test/features/runs/actions/title_action_test.dart` | 244 | Both-platform open/cancel/exact-save and stored-title seeding | +| `test/features/runs/actions/title_resilience_test.dart` | 243 | Refusal retention, double save, disposal, stale owner, 2x/narrow | + +`RunTitleAction(run: …, gateway: …, onRunChanged: …)` renders one native +`OutlinedButton` (`Rename`) on Material and one plain `CupertinoButton` on +Cupertino, and nothing for a run without a numeric id. Platform style follows the +enclosing app (`MaterialLocalizations` presence). No style overrides, fixed +component sizes or new dependencies. + +## Behaviour and web parity + +The prompt is seeded with the run's actual stored title exactly as the browser +reads it, `String(d.title ?? "")` in `web/src/views/runDetail.js`. It is never +derived from `input.prompt`, stage output or a placeholder. A missing title seeds +an empty field. + +Typing, opening and the dismiss action send nothing. Only `Save` calls the +existing `RunsRepository.setRunTitle(id, title)`, which sends the exact envelope: + +``` +set_run_title {"run_id": , "title": } +``` + +The field text is passed through untrimmed, matching `repo.setRunTitle(id, +String(state.renameValue ?? ""))` in `web/src/repository.js`. Leading/trailing +spaces and Unicode are preserved, and a blank title is sent as `""` so the server, +not the client, decides whether it is acceptable. There is no local +`canSubmit` gate on blank text. + +A refusal (including a blank-title refusal) is shown verbatim below the field and +the prompt stays open with the typed draft intact. Nothing is updated locally. +Only an accepted reply closes the prompt and passes the server's returned +`run_detail` once through `onRunChanged`; the action never fabricates a run or a +title. A second Save tap while sending is ignored, both dialog actions disable +until the reply, and every asynchronous resume checks `mounted`. A reply for a run +the widget no longer owns is dropped. + +## Checks actually run + +``` +dart format lib/features/runs/actions/title*.dart \ + test/features/runs/actions/title*.dart # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions/title_action_test.dart \ + test/features/runs/actions/title_resilience_test.dart # 11 passed +flutter test test/features/runs # 45 passed +flutter test # 63 passed +flutter build web # Built build/web (16.2s) +``` + +Focused acceptance coverage: + +- both platforms: native button and dialog, stored title in the field, typing and + Cancel produce zero gateway calls, Save sends exact `set_run_title` fields; +- exact field values: Unicode plus leading/trailing whitespace preserved; blank + title sent as `""` and the server refusal shown with the blank draft retained; +- failed save: server words verbatim, draft retained, dialog open, no callback and + no local title change; transport failure likewise; +- double Save: one request, action buttons disabled while in flight; +- disposal: a late reply after the tree is replaced throws nothing and delivers + nothing; a reply after the widget's run id changes is not delivered; +- 320x480 at 2x text: both prompts open, show a long title and a refusal, and close + with no rendering exception; +- malformed run: no rename button, and the stored-title helper ignores prompts. + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no run-detail screen or + controller; the manager owns integration. No real browser interaction or + capture was performed, so rendered feature parity is not claimed. `flutter build + web` proves compilation of the existing entrypoint, not that this widget is + reachable or visible. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses portable Flutter/Cupertino/Material widgets only. +- No real server, operator run or chat was touched. Tests use a local fake gateway + with no socket. +- No repository/domain/controller/shell/main/pubspec, `web/`, Go server, + installer or deployment file was changed. +- Nothing was committed, pushed or deployed; the files above are the candidate in + the working tree, per the stage instruction not to commit. diff --git a/app/test/features/runs/actions/title_action_test.dart b/app/test/features/runs/actions/title_action_test.dart new file mode 100644 index 00000000..110fda20 --- /dev/null +++ b/app/test/features/runs/actions/title_action_test.dart @@ -0,0 +1,244 @@ +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/runs/actions/title_action.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'title_test_support.dart'; + +String _materialFieldText(WidgetTester tester) => + tester.widget(find.byKey(runTitleFieldKey)).controller!.text; + +String _cupertinoFieldText(WidgetTester tester) => tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + +void main() { + testWidgets( + 'material rename starts from the stored title, typing sends nothing, ' + 'Cancel sends nothing and Save sends the exact text', + (tester) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(OutlinedButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(runTitleDialogTitle), findsWidgets); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(_materialFieldText(tester), 'Nightly build'); + + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.pump(); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Nightly build'); + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' 发布 🚀 — nightly ', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Release build', + ); + }, + ); + + testWidgets('cupertino rename is native and sends only on Save', ( + tester, + ) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: true, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(OutlinedButton), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(_cupertinoFieldText(tester), 'Nightly build'); + + await tester.enterText(find.byKey(runTitleFieldKey), 'Typed only'); + await tester.pump(); + expect(gateway.calls, isEmpty); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(runTitleFieldKey), 'Release build'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Release build', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }); + + testWidgets('a blank title is sent exactly and the server refusal is shown', ( + tester, + ) async { + const refusal = 'title must not be blank'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(runTitleFieldKey), ''); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.single.fields, {'run_id': 7, 'title': ''}); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_materialFieldText(tester), ''); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + expect( + tester.widget(find.byKey(runTitleSaveKey)).onPressed, + isNotNull, + ); + }); + + testWidgets('the prompt is seeded from the stored title, never the prompt', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + final changed = []; + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun( + title: 'Stored title', + prompt: 'prompt fallback must not appear', + ), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Stored title'); + expect(find.text('prompt fallback must not appear'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(title: null, prompt: 'prompt is not a title'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), ''); + expect(find.text('prompt is not a title'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); + + testWidgets('a malformed run has no rename entry point', (tester) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: {'title': 'No id'}, + changed: [], + ), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsNothing); + expect(gateway.calls, isEmpty); + expect(runTitleId({'title': 'No id'}), isNull); + expect(storedRunTitle({'title': 'Kept'}), 'Kept'); + expect(storedRunTitle({}), ''); + }); +} diff --git a/app/test/features/runs/actions/title_resilience_test.dart b/app/test/features/runs/actions/title_resilience_test.dart new file mode 100644 index 00000000..32a566c3 --- /dev/null +++ b/app/test/features/runs/actions/title_resilience_test.dart @@ -0,0 +1,243 @@ +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/runs/actions/title_wording.dart'; + +import 'title_test_support.dart'; + +Future _pump( + WidgetTester tester, + FakeTitleGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: run ?? titledRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _open(WidgetTester tester) async { + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); +} + +String _fieldText(WidgetTester tester, {required bool cupertino}) { + if (cupertino) { + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + } + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; +} + +void main() { + testWidgets('a failed save keeps the prompt open with the draft intact', ( + tester, + ) async { + const refusal = 'rename refused: the run is locked'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), ' Renamed draft '); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' Renamed draft ', + }); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: false), ' Renamed draft '); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + }); + + testWidgets('a transport failure keeps the server words and the draft', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => throw const NotConnectedError(), + ); + final changed = []; + await _pump(tester, gateway, changed, cupertino: true); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Unsent title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: true), 'Unsent title'); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(changed, isEmpty); + }); + + testWidgets('Save cannot send twice while the rename is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'One title'); + final save = find.byKey(runTitleSaveKey); + await tester.tap(save); + await tester.tap(save); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'set_run_title'), + hasLength(1), + ); + expect(tester.widget(save).onPressed, isNull); + expect( + tester.widget(find.byKey(runTitleCancelKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': renamedRun(title: 'One title')}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + expect(changed.single['title'], 'One title'); + }); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': renamedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a reply for a run the widget no longer owns is not delivered', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Run seven title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(id: 8, title: 'Another run'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.pump(); + reply.complete({'run_detail': renamedRun(title: 'Run seven title')}); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Run seven title', + }); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Another run', + ); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + const refusal = 'the title is too long for this run; shorten it'; + for (final cupertino in [false, true]) { + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await _open(tester); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.enterText( + find.byKey(runTitleFieldKey), + 'A deliberately long title that must scroll rather than overflow', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(refusal), findsOneWidget); + expect( + _fieldText(tester, cupertino: cupertino), + 'A deliberately long title that must scroll rather than overflow', + ); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byType(CupertinoAlertDialog), findsNothing); + } + }); +} diff --git a/app/test/features/runs/actions/title_test_support.dart b/app/test/features/runs/actions/title_test_support.dart new file mode 100644 index 00000000..b566a2d8 --- /dev/null +++ b/app/test/features/runs/actions/title_test_support.dart @@ -0,0 +1,110 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/title_action.dart'; + +typedef TitleHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeTitleGateway implements ApiGateway { + FakeTitleGateway(this.handler); + + final TitleHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap titledRun({ + num id = 7, + String? title = 'Nightly build', + String status = 'succeeded', + String prompt = 'the submitted prompt', +}) => { + 'id': id, + 'title': title, + 'status': status, + 'input': {'prompt': prompt}, +}; + +JsonMap renamedRun({num id = 7, String title = 'Release build'}) => + titledRun(id: id, title: title, status: 'succeeded'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. Re-pumping with a different +/// initial run updates the action in place, as a refreshed detail does. +class TitleHost extends StatefulWidget { + const TitleHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeTitleGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _TitleHostState(); +} + +class _TitleHostState extends State { + late JsonMap _run = widget.initial; + + @override + void didUpdateWidget(covariant TitleHost oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.initial, widget.initial)) { + _run = widget.initial; + } + } + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('${_run['title'] ?? ''}', key: titleHostTitleKey), + RunTitleAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ), + ], + ); + } +} + +const titleHostTitleKey = ValueKey('rename-host-title'); + +Widget titleApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + final body = Center(child: child); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: body), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: body), + ); +}