Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

79.7 KB
Raw Blame
import 'dart:math' as math;
import 'dart:async';

import '../shared/widgets/labeled_field.dart';

import 'package:harness/shared/theme/app_icons.dart';

import '../shared/widgets/app_rating_star.dart';

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:harness/terminal/terminal_text.dart';

import '../core/dsh_catalog.dart';
import '../core/harness_catalog.dart';
import '../core/models.dart' show ConnectionStatus;
import '../core/test_run.dart';
import '../shared/layouts/widgets/sidebar_item.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/app_icon_button.dart';
import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
import '../state/app_state.dart';
import '../state/essential_harness_controller.dart';
import '../super_tabs/visible_tick.dart';
import '../widgets/dsh_install_panel.dart' show describeInstallFailure;
import '../widgets/engine_identity.dart';
import '../widgets/new_agent_dialog.dart';
import '../widgets/open_harness_intent.dart';
import 'experimental_harnesses.dart';
import 'store_category.dart';
import 'store_collections.dart';
import 'store_compact_nav.dart';
import 'store_controller.dart';
import 'store_discover.dart';
import 'store_editorial.dart';
import 'store_harness_actions.dart';
import 'store_host.dart';
import 'store_listing.dart';
import 'store_models.dart';
import 'store_search.dart';
import 'store_sessions.dart';
import 'store_showcase.dart';
import 'store_viewers.dart';
import '../widgets/laid_out_list.dart';

/// The Harness Store, the content of its tab: every harness the registry
/// knows and every built-in engine, as a shelf of cards; one becomes its page
/// — what it is, whose it is, where it is installed, what people think of it —
/// with Get, Resume Harness, New Harness and Remove. A tab, not a screen over
/// the window, so the strip stays where it is and browsing never blocks switching.
///
/// The catalogue and installation state come from this computer's daemon.
/// Browsing, Get and Remove refer to this computer; Resume can return to a
/// harness on any linked machine. Remote machines do not contribute packages
/// or installation state to the Store.
/// Ratings and reviews come from the control plane through
/// [StoreApi]; the screen works without them (a page simply has no stars).
class StoreTab extends StatefulWidget {
  const StoreTab({
    super.key,
    required this.notifier,
    this.source = 'unknown',
    this.api,
    this.initialHarness,
    this.recentHarnesses = const [],
  });

  final AppNotifier notifier;
  final List<String> recentHarnesses;
  final String source;

  /// The ratings backend; null takes the real one through the local CLI.
  final StoreApi? api;

  /// Open straight on this harness's page.
  final String? initialHarness;

  @override
  State<StoreTab> createState() => _StoreTabState();
}

/// What the rail selects: discovery, search, or a category.
sealed class _Shelf {
  const _Shelf();
}

class _Discover extends _Shelf {
  const _Discover();
}

class _Sessions extends _Shelf {
  const _Sessions();
}

class _Viewers extends _Shelf {
  const _Viewers();
}

/// Catalog shelves: the complete index, search, and disciplines.
sealed class _Listed extends _Shelf {
  const _Listed();
}

class _All extends _Listed {
  const _All();
}

class _Search extends _Listed {
  const _Search(this.query);
  final String query;
}

class _Category extends _Listed {
  const _Category(this.name);
  final String name;
}

/// Where a person was in the store, kept per window (the app has one store
/// tab). Only the visible tab is built, so switching away disposed the store's
/// state: coming back reset it to Discover, with the search and the open
/// product page gone. A tab should keep its place, as a browser tab does.
class _StoreVisit {
  const _StoreVisit(this.shelf, this.selected, this.query);
  final _Shelf shelf;
  final String? selected;
  final String query;
}

class _StorePlace {
  final back = <_StoreVisit>[];
  final forward = <_StoreVisit>[];
  final scroll = PageStorageBucket();
  _Shelf shelf = const _Discover();
  String? selected;
  String query = '';
}

final _storePlaces = Expando<_StorePlace>('store place');

class _StoreTabState extends State<StoreTab>
    with WidgetsBindingObserver, VisibleTick<StoreTab> {
  late final StoreController _store = StoreController(
    widget.api ?? ApiStoreApi(widget.notifier.api),
  );
  late final _StorePlace _place = _storePlaces[widget.notifier] ??=
      _StorePlace();
  late _Shelf _shelf = widget.initialHarness == null
      ? _place.shelf
      : const _Discover();
  late String? _selected =
      widget.initialHarness ??
      widget.notifier.takePendingStoreHarness() ??
      _place.selected;
  late final _search = TextEditingController(
    text: widget.initialHarness == null ? _place.query : '',
  );
  final _searchFocus = FocusNode(debugLabel: 'Store search');
  final _browseFocus = FocusNode(debugLabel: 'Store navigation');
  bool _catalogPolls = false;

  void _remember() {
    _place
      ..shelf = _shelf
      ..selected = _selected
      ..query = _search.text;
  }

  @override
  void setState(VoidCallback fn) {
    super.setState(fn);
    _remember();
  }

  @override
  void initState() {
    super.initState();
    _remember();
    // Deferred a frame: both calls notify listeners at once, and this screen
    // is built while the shell underneath — which listens to the same
    // notifier — is mid-build.
    // Under test, only an injected [StoreApi] loads: the real one is an HTTP
    // call with a timeout, which is a Timer a widget test cannot let end.
    if (widget.api == null && kUnderTest) return;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      unawaited(_store.loadRatings());
      // Refresh installs made from a local terminal while the Store was closed.
      // Taken whether or not this computer is here yet, so the mark never lands on a later Store.
      final opened = widget.notifier.takeStoreOpened();
      final local = widget.notifier.localMachineState;
      if (local != null) _ask(local, userAction: opened);
      widget.notifier.addListener(_onAppChanged);
      // A Store left open picks up new publications; engines do not need reprobes.
      // The daemon caches catalog HTTP requests for five minutes. Only while the Store can be
      // seen, and once as it is seen again.
      _catalogPolls = true;
      visibleTick(const Duration(minutes: 1));
    });
  }

  @override
  void onTick() {
    final local = widget.notifier.localMachineState;
    if (local?.connectionStatus == ConnectionStatus.connected) {
      unawaited(
        widget.notifier.probeDsh(local!.machine.machineId, force: true),
      );
    }
  }

  @override
  void onScreenChanged(bool onScreen) {
    if (onScreen && _catalogPolls) onTick();
  }

  /// Machines asked since they last connected.
  ///
  /// A store tab restored when the app launches is built before any machine
  /// has connected: the first ask fails, and nothing asked again — the shelf
  /// showed the three engines, each offering Get, over a machine with 21
  /// harnesses installed. So a machine is asked again each time it connects.
  final _askedWhileConnected = <String>{};

  void _ask(MachineState machine, {bool userAction = false}) {
    final id = machine.machine.machineId;
    if (machine.connectionStatus == ConnectionStatus.connected) {
      _askedWhileConnected.add(id);
    }
    unawaited(
      widget.notifier.probeDsh(id, force: true, userAction: userAction),
    );
    // The engine rows read the same probe the New Harness dialog does; a
    // machine that has never been asked would show Claude Code as absent.
    unawaited(widget.notifier.probeEngines(id, force: true));
  }

  void _onAppChanged() {
    // A door asked for a harness page while this tab was already open: the
    // constructor's read is too late for that, so the page turns here.
    final pending = widget.notifier.takePendingStoreHarness();
    if (pending != null && pending != _selected) _openPage(pending);
    final connecting = <MachineState>[];
    for (final machine in [?widget.notifier.localMachineState]) {
      final id = machine.machine.machineId;
      if (machine.connectionStatus != ConnectionStatus.connected) {
        _askedWhileConnected.remove(id);
      } else if (!_askedWhileConnected.contains(id)) {
        connecting.add(machine);
      }
    }
    if (connecting.isEmpty) return;
    // Out of the notification: asking notifies the same listeners again.
    scheduleMicrotask(() {
      if (!mounted) return;
      for (final machine in connecting) {
        if (machine.connectionStatus == ConnectionStatus.connected &&
            identical(machine, widget.notifier.localMachineState) &&
            !_askedWhileConnected.contains(machine.machine.machineId)) {
          _ask(machine);
        }
      }
    });
  }

  @override
  void dispose() {
    widget.notifier.removeListener(_onAppChanged);
    _search.dispose();
    _searchFocus.dispose();
    _browseFocus.dispose();
    _store.dispose();
    super.dispose();
  }

  /// The local daemon's catalog carries the registry, plus one row per
  /// built-in engine, because a person looking for "Claude Code" in a store
  /// should find it beside Marp, not learn that it is a different kind of thing.
  Map<String, DshEntry> get _catalog {
    final rows = <String, DshEntry>{};
    final local = widget.notifier.localMachineState;
    for (final identity in allEngines) {
      rows[identity.id] = DshEntry(
        id: identity.id,
        name: identity.label,
        engine: identity.id,
        kind: 'engine',
        category: identity.category ?? 'Code',
        author: identity.creator,
        description: identity.blurb,
        homepage: identity.homepage,
        installed: _installedOnMachine(local, identity.id),
      );
    }
    for (final entry in storeVisibleHarnesses(
      currentHarnessCatalog(local?.dsh.entries ?? const <DshEntry>[]),
      widget.notifier.experimentalFeatures,
    )) {
      rows.putIfAbsent(entry.id, () => entry);
    }
    return rows;
  }

  /// Store installation facts are local, including shared viewer packages.
  List<MachineState> _installedOn(String id) => [
    for (final state in [?widget.notifier.localMachineState])
      if (_installedOnMachine(state, id)) state,
  ];

  List<String> get _categories {
    final names = <String>{
      for (final entry in _catalog.values)
        if (!entry.isViewerPackage) storeCategoryFor(entry),
    };
    return [
      ...storeCategoryDomains.keys,
      'Other',
    ].where(names.contains).toList();
  }

  List<DshEntry> _shelved(_Shelf shelf) {
    final all = _catalog.values.toList()
      ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
    return switch (shelf) {
      _Discover() ||
      _Sessions() ||
      _All() => all.where((e) => !e.isViewerPackage).toList(),
      _Search(:final query) => storeSearch(
        all.where((e) => !e.isViewerPackage),
        query,
      ),
      _Viewers() => all.where((e) => e.isViewerPackage).toList(),
      _Category(:final name) =>
        all
            .where((e) => !e.isViewerPackage && storeCategoryFor(e) == name)
            .toList(),
    };
  }

  _StoreVisit get _visit => _StoreVisit(_shelf, _selected, _place.query);

  String _shelfKey(_Shelf shelf) => switch (shelf) {
    _Discover() => 'discover',
    _Sessions() => 'sessions',
    _All() => 'all',
    _Search(:final query) => 'search:$query',
    _Category(:final name) => 'category:$name',
    _Viewers() => 'viewers',
  };

  bool get _canGoBack =>
      _place.back.isNotEmpty || _selected != null || _shelf is! _Discover;

  void _restore(_StoreVisit visit) {
    _shelf = visit.shelf;
    _selected = visit.selected;
    _search.value = TextEditingValue(
      text: visit.query,
      selection: TextSelection.collapsed(offset: visit.query.length),
    );
  }

  void _navigate(_StoreVisit next) {
    if (_shelfKey(next.shelf) == _shelfKey(_shelf) &&
        next.selected == _selected) {
      return;
    }
    _browseFocus.requestFocus();
    setState(() {
      _place.back.add(_visit);
      if (_place.back.length > 80) {
        _place.back.removeAt(0);
      }
      _place.forward.clear();
      _restore(next);
    });
  }

  void _goBack() {
    if (!_canGoBack) return;
    _browseFocus.requestFocus();
    setState(() {
      _place.forward.add(_visit);
      _restore(
        _place.back.isEmpty
            ? const _StoreVisit(_Discover(), null, '')
            : _place.back.removeLast(),
      );
    });
  }

  void _goForward() {
    if (_place.forward.isEmpty) return;
    _browseFocus.requestFocus();
    setState(() {
      _place.back.add(_visit);
      _restore(_place.forward.removeLast());
    });
  }

  void _show(_Shelf shelf) => _navigate(_StoreVisit(shelf, null, ''));

  void _openPage(String id) {
    _navigate(_StoreVisit(_shelf, id, _search.text));
  }

  /// An Essential opens the one that exists or creates it, in one click and with no New Harness form.
  Future<void> _openEssential(String id) async {
    final error = await widget.notifier.essential(id)?.open();
    if (error != null && mounted) {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text(error)));
    }
  }

  void _searchChanged(String query) {
    if (query.trim().isEmpty) {
      _clearSearch();
      return;
    }
    // One history entry per search, not one per keystroke. A product opened
    // from results is a separate stop and keeps the original query intact.
    setState(() {
      if (_shelf is! _Search || _selected != null) _place.back.add(_visit);
      _place.forward.clear();
      _selected = null;
      _shelf = _Search(query);
    });
  }

  void _clearSearch() {
    // Return to the discipline where this search began, including its scroll.
    final origin = _place.back.lastIndexWhere(
      (visit) => visit.shelf is! _Search,
    );
    setState(() {
      _place.forward.add(_visit);
      final next = origin < 0
          ? const _StoreVisit(_Discover(), null, '')
          : _place.back[origin];
      if (origin >= 0) _place.back.removeRange(origin, _place.back.length);
      _restore(next);
    });
    _searchFocus.requestFocus();
  }

  void _focusSearch() {
    _searchFocus.requestFocus();
    _search.selection = TextSelection(
      baseOffset: 0,
      extentOffset: _search.text.length,
    );
  }

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    return KeymapRegion(
      contextKind: KeymapContext.workspace,
      actions: {
        'navigation.back': _goBack,
        'navigation.forward': _goForward,
        'terminal.find': _focusSearch,
      },
      child: Focus(
        focusNode: _browseFocus,
        skipTraversal: true,
        child: ColoredBox(
          color: grid.AppPalette.windowBg,
          child: ListenableBuilder(
            listenable: Listenable.merge([
              widget.notifier,
              widget.notifier.experimentalFeatures,
              _store,
            ]),
            builder: (context, _) {
              final catalog = _catalog;
              final selected = _selected == null
                  ? null
                  : catalog[canonicalHarnessId(_selected!)];
              final category = selected != null
                  ? storeCategoryFor(selected)
                  : (_shelf is _Category ? (_shelf as _Category).name : null);
              final compact = storeIsCompact(context);
              final nav = _Nav(
                shelf: _shelf,
                selectedCategory: category,
                hasProduct: selected != null,
                sessionCount: storeRecordedSessions(catalog.values).length,
                counts: {
                  for (final name in _categories)
                    name: catalog.values
                        .where(
                          (e) =>
                              !e.isViewerPackage && storeCategoryFor(e) == name,
                        )
                        .length,
                },
                categories: _categories,
                onSelect: _show,
              );
              final search = StoreSearch(
                controller: _search,
                focusNode: _searchFocus,
                onChanged: _searchChanged,
                autofocus: _selected == null,
                onClear: _clearSearch,
                onBack: _canGoBack ? _goBack : null,
                onForward: _place.forward.isEmpty ? null : _goForward,
                compact: compact,
              );
              final page = Expanded(
                child: PageStorage(
                  bucket: _place.scroll,
                  child: KeyedSubtree(
                    key: PageStorageKey(
                      'store-location:${_shelfKey(_shelf)}:${_selected ?? ''}',
                    ),
                    child: selected != null
                        ? _ProductPage(
                            key: ValueKey('store-page:${selected.id}'),
                            entry: selected,
                            notifier: widget.notifier,
                            recentHarnesses: widget.recentHarnesses,
                            store: _store,
                          )
                        : _shelf is _Viewers
                        ? StoreViewers(
                            viewers: _shelved(const _Viewers()),
                            agents:
                                widget
                                    .notifier
                                    .localMachineState
                                    ?.dsh
                                    .entries ??
                                const [],
                            installedOn: (id) => _installedOn(id)
                                .map((machine) => machine.machine.displayName)
                                .toList(),
                            onOpenAgent: _openPage,
                            loaded:
                                widget.notifier.localMachineState?.dsh.loaded ??
                                false,
                          )
                        : _shelf is _Sessions
                        ? StoreSessions(
                            sessions: storeRecordedSessions(
                              _shelved(const _Sessions()),
                            ),
                            onOpen: _openPage,
                          )
                        : _shelf is _Discover
                        ? StoreDiscover(
                            entries: _shelved(const _Discover()),
                            loaded:
                                widget.notifier.localMachineState?.dsh.loaded ??
                                false,
                            ratingFor: (entry) =>
                                _store.ratingOf(StoreController.keyFor(entry)),
                            onOpen: _openPage,
                            onCategory: (name) => _show(_Category(name)),
                            onAll: () => _show(const _All()),
                            onEngines: () => _show(const _Category('Coding')),
                            essentialLabel: (id) =>
                                widget.notifier.essential(id)?.exists == true
                                ? 'Open'
                                : 'Create',
                            onEssential: (id) => unawaited(_openEssential(id)),
                          )
                        : _Shelf$View(
                            shelf: _shelf as _Listed,
                            categories: _categories,
                            onCategory: (name) => _show(_Category(name)),
                            entries: _shelved(_shelf),
                            store: _store,
                            installedOn: _installedOn,
                            loaded:
                                widget.notifier.localMachineState?.dsh.loaded ??
                                false,
                            onOpen: _openPage,
                          ),
                  ),
                ),
              );
              if (compact) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    search,
                    _StoreChips(nav: nav),
                    page,
                  ],
                );
              }
              return Row(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  _StoreNav(nav: nav),
                  VerticalDivider(width: 1, color: grid.AppPalette.divider),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [search, page],
                    ),
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }
}

// ─── the rail ────────────────────────────────────────────────────────────────

/// What the rail, or a phone's chip row, offers and which entry is open.
class _Nav {
  const _Nav({
    required this.shelf,
    required this.categories,
    required this.selectedCategory,
    required this.hasProduct,
    required this.sessionCount,
    required this.counts,
    required this.onSelect,
  });

  final _Shelf shelf;
  final List<String> categories;
  final String? selectedCategory;
  final bool hasProduct;
  final int sessionCount;
  final Map<String, int> counts;
  final ValueChanged<_Shelf> onSelect;

  /// Every shelf the Store offers, in order: the rail and a phone's chip row
  /// both draw this list.
  List<_ShelfChoice> get choices => [
    _ShelfChoice(
      id: 'discover',
      kind: _ShelfKind.browse,
      icon: AppIcons.sparkles,
      label: 'Discover',
      selected: !hasProduct && shelf is _Discover,
      onTap: () => onSelect(const _Discover()),
    ),
    _ShelfChoice(
      id: 'all',
      kind: _ShelfKind.browse,
      icon: AppIcons.layoutGrid,
      label: 'All harnesses',
      selected: !hasProduct && shelf is _All,
      onTap: () => onSelect(const _All()),
    ),
    if (sessionCount > 0 || shelf is _Sessions)
      _ShelfChoice(
        id: 'sessions',
        kind: _ShelfKind.browse,
        icon: AppIcons.play,
        label: 'Featured',
        tooltip: '$sessionCount recorded runs',
        selected: !hasProduct && shelf is _Sessions,
        onTap: () => onSelect(const _Sessions()),
      ),
    for (final name in categories)
      _ShelfChoice(
        id: 'category:$name',
        kind: _ShelfKind.discipline,
        icon: _categoryIcon(name),
        label: name,
        tooltip: name,
        count: counts[name],
        selected: selectedCategory == name,
        onTap: () => onSelect(_Category(name)),
      ),
    _ShelfChoice(
      id: 'viewers',
      kind: _ShelfKind.viewers,
      icon: AppIcons.panelsTopLeft,
      label: 'Viewers',
      selected: shelf is _Viewers,
      onTap: () => onSelect(const _Viewers()),
    ),
  ];
}

/// Where the rail puts a shelf: the browse entries, the disciplines under
/// their heading, and Viewers at its foot.
enum _ShelfKind { browse, discipline, viewers }

class _ShelfChoice {
  const _ShelfChoice({
    required this.id,
    required this.kind,
    required this.icon,
    required this.label,
    required this.selected,
    required this.onTap,
    this.tooltip,
    this.count,
  });

  /// Keys the rail's entry `store-shelf-<id>` and the chip `store-chip:<id>`.
  final String id;
  final _ShelfKind kind;
  final IconData icon;
  final String label;
  final bool selected;
  final VoidCallback onTap;
  final String? tooltip;
  final int? count;
}

class _StoreNav extends StatelessWidget {
  const _StoreNav({required this.nav});

  final _Nav nav;

  @override
  Widget build(BuildContext context) {
    TerminalFontScope.watch(context);
    final choices = nav.choices;
    Iterable<_ShelfChoice> of(_ShelfKind kind) =>
        choices.where((choice) => choice.kind == kind);
    final viewers = of(_ShelfKind.viewers).single;
    final textScale = grid.appTextScaleOf(context).clamp(1.0, 1.5);
    return Container(
      width:
          (MediaQuery.sizeOf(context).width < 1000 ? 184 : 216) +
          (textScale - 1) * 64,
      color: grid.AppSurface.recess,
      child: Column(
        children: [
          Expanded(
            child: LaidOutListView(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 22),
              children: [
                for (final choice in of(_ShelfKind.browse))
                  SidebarItem(
                    key: ValueKey('store-shelf-${choice.id}'),
                    icon: choice.icon,
                    label: choice.label,
                    tooltip: choice.tooltip,
                    selected: choice.selected,
                    onTap: choice.onTap,
                  ),
                const SizedBox(height: 22),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
                  child: Text(
                    'Disciplines',
                    style: grid.AppType.caption(
                      fontWeight: grid.AppFont.medium,
                      color: grid.AppPalette.textFaint,
                    ),
                  ),
                ),
                for (final choice in of(_ShelfKind.discipline))
                  SidebarItem(
                    key: ValueKey('store-shelf-${choice.id}'),
                    icon: choice.icon,
                    label: choice.label,
                    tooltip: choice.tooltip,
                    selected: choice.selected,
                    trailingAlwaysVisible: true,
                    trailingWidth: 22,
                    trailing: textScale > 1.2
                        ? null
                        : Align(
                            alignment: Alignment.centerRight,
                            child: Text(
                              '${choice.count}',
                              style: grid.AppType.caption(
                                color: grid.AppPalette.textFaint,
                              ),
                            ),
                          ),
                    onTap: choice.onTap,
                  ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(18, 10, 18, 16),
            child: Align(
              alignment: Alignment.centerLeft,
              child: AppIconButton(
                key: const ValueKey('store-viewers-button'),
                icon: viewers.icon,
                size: 17,
                color: viewers.selected
                    ? grid.AppPalette.textPrimary
                    : grid.AppPalette.textFaint,
                tooltip: viewers.label,
                onPressed: viewers.onTap,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// The rail as a row of chips above the content, for a phone.
class _StoreChips extends StatelessWidget {
  const _StoreChips({required this.nav});

  final _Nav nav;

  @override
  Widget build(BuildContext context) => StoreChipRow(
    chips: [
      for (final choice in nav.choices)
        StoreChip(
          id: choice.id,
          icon: choice.icon,
          label: choice.label,
          count: choice.count,
          selected: choice.selected,
          onTap: choice.onTap,
        ),
    ],
  );
}

IconData _categoryIcon(String category) => switch (category) {
  'Design' => AppIcons.box,
  'Engineering' => AppIcons.cpu,
  'Media' => AppIcons.film,
  'Music' => AppIcons.music,
  'Productivity' => AppIcons.fileText,
  'Science & Data' => AppIcons.flaskConical,
  'Simulation' => AppIcons.bot,
  'Research' => AppIcons.search,
  'Local AI' => AppIcons.brainCircuit,
  'Coding' => AppIcons.terminal,
  'Games' => AppIcons.gamepad2,
  _ => AppIcons.shapes,
};

// Search and the complete index stay compact; disciplines and collections
// invite exploration through larger previews.
class _Shelf$View extends StatelessWidget {
  const _Shelf$View({
    required this.shelf,
    required this.categories,
    required this.onCategory,
    required this.entries,
    required this.store,
    required this.installedOn,
    required this.loaded,
    required this.onOpen,
  });

  final _Listed shelf;
  final List<String> categories;
  final ValueChanged<String> onCategory;
  final List<DshEntry> entries;
  final StoreController store;
  final List<MachineState> Function(String id) installedOn;
  final bool loaded;
  final ValueChanged<String> onOpen;

  String get _title => switch (shelf) {
    _All() => 'All harnesses',
    _Search() => 'Search results',
    _Category(:final name) => name,
  };

  String get _subtitle => switch (shelf) {
    _All() => 'Find something you have always wanted to make.',
    _Search() => '${entries.length} result${entries.length == 1 ? '' : 's'}',
    _Category() =>
      '${entries.length} harness${entries.length == 1 ? '' : 'es'} to explore.',
  };

  @override
  Widget build(BuildContext context) {
    if (shelf is _Category) {
      return StoreCategory(
        name: _title,
        categories: categories,
        onCategory: onCategory,
        entries: entries,
        loaded: loaded,
        ratingFor: (entry) => store.ratingOf(StoreController.keyFor(entry)),
        installed: (id) => installedOn(id).isNotEmpty,
        onOpen: onOpen,
      );
    }
    return SingleChildScrollView(
      key: ValueKey('store-catalog:$_title'),
      padding: const EdgeInsets.fromLTRB(28, 28, 28, 48),
      child: Align(
        alignment: Alignment.topCenter,
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 1440),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text(
                _title,
                style: grid.AppType.display(color: grid.AppPalette.textPrimary),
              ),
              const SizedBox(height: 8),
              Text(
                _subtitle,
                style: grid.AppType.body(color: grid.AppPalette.textSecondary),
              ),
              const SizedBox(height: 24),
              if (entries.isEmpty)
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 48),
                  child: Text(
                    shelf is _Search
                        ? 'No matching harnesses. Try a name or something you want to make.'
                        : storeRunsNoHarness(context)
                        ? kStoreOnAComputer
                        : loaded
                        ? 'Nothing here yet.'
                        : 'Asking this computer…',
                    style: grid.AppType.body(
                      height: 1.5,
                      color: grid.AppPalette.textSecondary,
                    ),
                  ),
                )
              else
                StoreListing(
                  entries: entries,
                  ratingFor: (entry) =>
                      store.ratingOf(StoreController.keyFor(entry)),
                  onOpen: onOpen,
                ),
              if (entries.isEmpty && shelf is _Search)
                Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  children: [
                    for (final category in categories.take(6))
                      ActionChip(
                        key: ValueKey('store-search-explore:$category'),
                        label: Text('Explore $category'),
                        onPressed: () => onCategory(category),
                      ),
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }
}

class _Stars extends StatelessWidget {
  const _Stars({super.key, required this.value, this.size = 14, this.onPick});

  /// 0..5; a half counts as a half star.
  final double value;
  final double size;

  /// When set, the stars are a picker: tapping the n-th picks n.
  final ValueChanged<int>? onPick;

  static const _amber = Color(0xffF5A623);

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        for (var i = 1; i <= 5; i++)
          MouseRegion(
            cursor: onPick == null
                ? SystemMouseCursors.basic
                : SystemMouseCursors.click,
            child: GestureDetector(
              onTap: onPick == null ? null : () => onPick!(i),
              child: Semantics(
                label: '$i ${i == 1 ? 'star' : 'stars'}',
                button: onPick != null,
                child: SizedBox.square(
                  dimension: onPick == null ? size : math.max(32, size),
                  child: Center(
                    child: AppRatingStar(
                      fraction: (value - i + 1).clamp(0, 1),
                      size: size,
                      color: _amber,
                      outlineColor: value >= i - 0.5
                          ? _amber
                          : grid.AppPalette.textFaint,
                    ),
                  ),
                ),
              ),
            ),
          ),
      ],
    );
  }
}

// ─── the page ────────────────────────────────────────────────────────────────

bool _installedOnMachine(MachineState? machine, String id) => isHarnessId(id)
    ? _machineHarness(machine, id)?.installed == true
    : machine?.engines[id]?.installed == true;

DshEntry? _machineHarness(MachineState? machine, String id) =>
    harnessForOperation(machine?.dsh.entries ?? const <DshEntry>[], id);

String _operationId(MachineState? machine, String id) =>
    _machineHarness(machine, id)?.id ?? canonicalHarnessId(id);

bool _canGetOnMachine(MachineState machine, DshEntry entry) {
  if (machine.needsLink || machine.nodeOnline == false) return false;
  if (entry.isEngine) {
    return machine.engines.loaded &&
        machine.engines[entry.id]?.installable == true;
  }
  final id = _operationId(machine, entry.id);
  return machine.dsh.loaded &&
      machine.dsh[id] != null &&
      machine.dsh.runs[id]?.inProgress != true;
}

/// Open a bundled app workspace, or the New Harness dock with this product and
/// machine chosen.
/// A successful start opens a new tab; reviewing or cancelling allocates none.
///
/// Public because it is the ONE way a harness is opened from anywhere — the
/// Store page, and the model picker's "Open Grid" — so the two cannot drift
/// into two definitions of what opening a harness means.
Future<void> openStoreAgent(
  BuildContext context,
  AppNotifier notifier,
  String harnessId,
  String machineId, {
  String? prompt,
}) async {
  final workspace = ExperimentalStoreHarness.forId(harnessId);
  if (workspace != null) {
    // Recheck at activation as the account/flag can change after rendering.
    if (!workspace.enabled(notifier.experimentalFeatures)) return;
    switch (workspace) {
      case ExperimentalStoreHarness.devices:
        notifier.openDevices();
      case ExperimentalStoreHarness.companions:
        notifier.openCompanions();
        notifier.syncCompanionViewer(
          enabled: true,
          machineId: notifier.localMachineState?.machine.machineId,
        );
    }
    return;
  }
  harnessId = _operationId(notifier.machineStates[machineId], harnessId);
  final intent = OpenHarnessIntent(harnessId, machineId, task: prompt);
  if (Actions.maybeFind<OpenHarnessIntent>(context) != null) {
    final opening = Actions.maybeInvoke(context, intent);
    if (opening is Future) await opening;
    return;
  }
  final navigator = Navigator.of(context);
  final origin = notifier.activeSwarmId;
  notifier.newSwarm(draft: true);
  final target = notifier.activeSwarmId;
  // Let the new tab mount and finish autofocus before the dialog claims focus.
  // Otherwise its search can take focus behind the dialog, swallowing Escape.
  // The Store subtree is disposed by this switch, so use the surviving navigator.
  await WidgetsBinding.instance.endOfFrame;
  if (!navigator.mounted) return;
  final result = await showNewAgentDialog(
    navigator.context,
    notifier,
    machineId,
    source: 'store',
    initialEngine: harnessId,
    initialPrompt: prompt,
    swarmId: target,
  );
  if (result != null) return;
  // Dismissed: back to the store page. A tab made for this is a draft and cancelling it returns there;
  // but newSwarm hands over an empty New Tab the window already had instead of making a second one,
  // and that tab is the person's own — it stays, and the store is selected again.
  if (!notifier.cancelSwarmDraft(target) &&
      notifier.activeSwarmId == target &&
      target != origin) {
    notifier.selectSwarm(origin);
  }
}

class _ProductPage extends StatefulWidget {
  const _ProductPage({
    super.key,
    required this.entry,
    required this.notifier,
    required this.store,
    required this.recentHarnesses,
  });

  final DshEntry entry;
  final AppNotifier notifier;
  final StoreController store;
  final List<String> recentHarnesses;

  @override
  State<_ProductPage> createState() => _ProductPageState();
}

class _ProductPageState extends State<_ProductPage> {
  /// Machines with a Get or Remove in flight, so a double click cannot start two.
  final Set<String> _busy = {};

  String get _key => StoreController.keyFor(widget.entry);

  @override
  void initState() {
    super.initState();
    // Deferred a frame: the load's first notification would otherwise land
    // inside the build that is putting this page on screen.
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) unawaited(widget.store.loadReviews(_key));
    });
  }

  void _say(String text) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(text)));
  }

  Future<void> _openEssential(EssentialHarnessController essential) async {
    setState(() {});
    final error = await essential.open();
    if (!mounted) return;
    setState(() {});
    if (error != null) _say(error);
  }

  Future<void> _get(String machineId) async {
    final local = widget.notifier.localMachineState;
    if (local == null ||
        local.machine.machineId != machineId ||
        !_canGetOnMachine(local, widget.entry)) {
      return;
    }
    // An engine is installed by the daemon on the way to the first harness
    // that needs it (`installIfMissing` on create), so Get is Open.
    if (widget.entry.isEngine) return _open(machineId);
    if (_busy.contains(machineId)) return;
    final trusted = _unverified(local);
    if (trusted && !await _confirmUnverified(local, update: false)) return;
    if (!mounted || !_busy.add(machineId)) return;
    setState(() {});
    final failure = await widget.notifier.installDsh(
      machineId,
      _operationId(local, widget.entry.id),
      trustUnverified: trusted,
    );
    _busy.remove(machineId);
    if (mounted) setState(() {});
    if (failure != null) _say(_failureSentence(local, failure));
  }

  /// The toast for a failed Get/Update: what kind of failure and what to do,
  /// not the two thousand characters git printed — those stay on the page,
  /// under the button, where they can be read at leisure.
  String _failureSentence(MachineState local, String fallback) {
    final run = local.dsh.runs[_operationId(local, widget.entry.id)];
    if (run == null || !run.failed) return fallback;
    final failure = describeInstallFailure(run, widget.entry.name);
    final hint = failure.hint;
    return hint == null ? failure.title : '${failure.title} $hint';
  }

  Future<void> _update(String machineId) async {
    final local = widget.notifier.localMachineState;
    if (local == null ||
        local.machine.machineId != machineId ||
        _machineHarness(local, widget.entry.id)?.hasUpdate != true ||
        _busy.contains(machineId)) {
      return;
    }
    final trusted = _unverified(local);
    if (trusted && !await _confirmUnverified(local, update: true)) return;
    if (!mounted || !_busy.add(machineId)) return;
    setState(() {});
    final failure = await widget.notifier.updateDsh(
      machineId,
      _operationId(local, widget.entry.id),
      trustUnverified: trusted,
    );
    _busy.remove(machineId);
    if (mounted) setState(() {});
    if (failure != null) _say(_failureSentence(local, failure));
  }

  /// Harness has not reviewed this package ([DshEntry.unverified]), on the
  /// machine's word or the page's.
  bool _unverified(MachineState local) =>
      widget.entry.unverified ||
      _machineHarness(local, widget.entry.id)?.unverified == true;

  /// Asks before a package Harness has not reviewed is installed or updated:
  /// both run its setup script as the person, and Update fetches whatever its
  /// repository holds now. True only when they confirm.
  Future<bool> _confirmUnverified(
    MachineState local, {
    required bool update,
  }) async {
    final source =
        _machineHarness(local, widget.entry.id)?.repo ??
        widget.entry.repo ??
        'its own repository';
    final ok = await showAppDialog<bool>(
      context: context,
      builder: (context) => _ConfirmCard(
        title: 'Harness has not reviewed ${widget.entry.name}',
        detail:
            'Its code comes from $source, not from Harness. '
            '${update ? 'Updating fetches its latest code and runs its setup script again' : 'Installing runs its setup script'} '
            'on ${local.machine.displayName} as you, with access to your files '
            'and credentials. Continue only if you trust its author.',
        action: update ? 'Update anyway' : 'Install anyway',
      ),
    );
    return ok == true && mounted;
  }

  Future<void> _remove(String machineId, String machineName) async {
    final local = widget.notifier.localMachineState;
    final installation = _machineHarness(local, widget.entry.id);
    if (local?.machine.machineId != machineId ||
        installation?.installed != true) {
      return;
    }
    final ok = await showAppDialog<bool>(
      context: context,
      builder: (context) => _ConfirmCard(
        title: 'Remove ${widget.entry.name} from $machineName?',
        detail: installation!.linked
            ? 'This is linked to a checkout on that machine; only the link goes. Harnesses already open keep running.'
            : 'Its files and toolchain on that machine go. Harnesses already open keep running.',
        action: 'Remove',
      ),
    );
    if (ok != true || !mounted) return;
    // No second Remove can be in flight: the dialog above is modal, and while
    // one runs the row shows progress instead of the button.
    _busy.add(machineId);
    setState(() {});
    final failure = await widget.notifier.removeDsh(
      machineId,
      installation!.id,
    );
    _busy.remove(machineId);
    if (mounted) setState(() {});
    if (failure != null) _say(failure);
  }

  /// Open from the Store with this product and machine. An example's [prompt]
  /// becomes the editable task in the same dock before the person presses Start.
  Future<void> _open(String machineId, {String? prompt}) async {
    if (ExperimentalStoreHarness.forId(widget.entry.id) == null &&
        widget.notifier.localMachineState?.machine.machineId != machineId) {
      return;
    }
    await openStoreAgent(
      context,
      widget.notifier,
      widget.entry.id,
      machineId,
      prompt: prompt,
    );
  }

  Future<void> _review() async {
    final page = widget.store.reviews[_key];
    final draft = await showAppDialog<_ReviewDraft>(
      context: context,
      builder: (context) =>
          _ReviewDialog(name: widget.entry.name, existing: page?.mine),
    );
    if (draft == null || !mounted) return;
    final failure = draft.delete
        ? await widget.store.remove(_key)
        : await widget.store.submit(
            _key,
            rating: draft.rating,
            title: draft.title,
            body: draft.body,
          );
    if (failure != null) _say(failure);
  }

  /// Where the reviews start, so the rating under the name can take a person there.
  final _reviewsKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    final entry = widget.entry;
    final workspace = ExperimentalStoreHarness.forId(entry.id);
    final identity = engineIdentity(entry.id, displayName: entry.name);
    final author = entry.author ?? identity.creator;
    final category = entry.category ?? identity.category;
    final rating = widget.store.ratingOf(_key);
    final page = widget.store.reviews[_key];
    final local = widget.notifier.localMachineState;
    final localInstalled = _installedOnMachine(local, entry.id);
    final operationId = _operationId(local, entry.id);
    final hasUpdate =
        workspace == null &&
        _machineHarness(local, entry.id)?.hasUpdate == true;
    final base = entry.engine.isNotEmpty
        ? entry.engine
        : (knownHarnessBase[entry.id] ?? '');
    final baseLabel = base.isEmpty ? null : engineIdentity(base).label;
    final description = entry.description ?? identity.blurb;
    final installing = local?.dsh.runs[operationId]?.inProgress == true;
    final failed = local?.dsh.runs[operationId]?.failed == true;
    final busy = local != null && _busy.contains(local.machine.machineId);
    // New Harness installs a harness the machine lacks before it creates, so
    // an example can be tried from here whether or not Get was pressed.
    // An Essential's examples are read, not tried: trying one opens the New Harness form.
    final canTry =
        widget.notifier.essential(entry.id) == null &&
        workspace == null &&
        !entry.isViewerPackage &&
        local != null &&
        !busy &&
        !installing &&
        (localInstalled || _canGetOnMachine(local, entry));
    // An Essential has one button, Create or Open, and never the New Harness form.
    final essential = hasUpdate ? null : widget.notifier.essential(entry.id);
    final showLaunch =
        essential == null &&
        workspace == null &&
        !entry.isViewerPackage &&
        !hasUpdate &&
        localInstalled;
    // A package that has not published its own examples yet still leads with
    // prompts — the editorial ones — so every page reads the same way.
    final examples = entry.examples.isNotEmpty
        ? entry.examples
        : [
            for (final prompt
                in storeStories[entry.id]?.prompts ?? const <String>[])
              StoreExample(prompt: prompt),
          ];
    final screenshots = entry.examples.isEmpty
        ? entry.screenshots
        : const <String>[];
    // A viewer package is never opened on its own: once it is here there is
    // nothing more to press, and Remove sits in the line beneath.
    final showAction =
        workspace != null ||
        (local != null &&
            (hasUpdate || !(entry.isViewerPackage && localInstalled)));

    return LayoutBuilder(
      builder: (context, constraints) {
        final wide = constraints.maxWidth >= 820;
        final side = wide ? 56.0 : 24.0;
        return SingleChildScrollView(
          padding: EdgeInsets.fromLTRB(side, 12, side, 140),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // The name in its own light: a soft glow of the harness's colour behind the hero.
              DecoratedBox(
                decoration: BoxDecoration(
                  gradient: RadialGradient(
                    center: const Alignment(0, -0.12),
                    radius: wide ? 0.44 : 0.5,
                    colors: [
                      identity.color.withValues(alpha: 0.16),
                      identity.color.withValues(alpha: 0),
                    ],
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    SizedBox(height: wide ? 44 : 20),
                    Center(
                      child: EngineMark(
                        engine: entry.id,
                        displayName: entry.name,
                        size: wide ? 96 : 72,
                      ),
                    ),
                    const SizedBox(height: 26),
                    Text(
                      entry.name,
                      textAlign: TextAlign.center,
                      style: grid.AppType.display(
                        height: 1.1,
                        color: grid.AppPalette.textPrimary,
                      ),
                    ),
                    if (description != null) ...[
                      const SizedBox(height: 18),
                      Center(
                        child: ConstrainedBox(
                          constraints: const BoxConstraints(maxWidth: 640),
                          child: Text(
                            description,
                            textAlign: TextAlign.center,
                            style: grid.AppType.body(
                              height: 1.45,
                              color: grid.AppPalette.textSecondary,
                            ),
                          ),
                        ),
                      ),
                    ],
                    const SizedBox(height: 22),
                    Text(
                      [
                        ?author,
                        ?category,
                        if (workspace != null)
                          'Included with Harness'
                        else if (entry.isViewerPackage)
                          'Viewer package'
                        else if (entry.isEngine)
                          'Coding agent'
                        else if (baseLabel != null)
                          'Runs on $baseLabel',
                      ].join(' · '),
                      textAlign: TextAlign.center,
                      style: grid.AppType.body(
                        color: grid.AppPalette.textFaint,
                      ),
                    ),
                    const SizedBox(height: 12),
                    Wrap(
                      alignment: WrapAlignment.center,
                      crossAxisAlignment: WrapCrossAlignment.center,
                      spacing: 20,
                      runSpacing: 8,
                      children: [
                        if (!rating.isEmpty)
                          _QuietLink(
                            key: const ValueKey('store-rating-link'),
                            onTap: () {
                              final target = _reviewsKey.currentContext;
                              if (target != null) {
                                unawaited(
                                  Scrollable.ensureVisible(
                                    target,
                                    duration: Duration.zero,
                                    curve: Curves.easeInOutCubic,
                                  ),
                                );
                              }
                            },
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                _Stars(value: rating.average, size: 14),
                                const SizedBox(width: 6),
                                Text(
                                  '${rating.average.toStringAsFixed(1)} · ${rating.count} rating${rating.count == 1 ? '' : 's'}',
                                ),
                              ],
                            ),
                          ),
                        if (entry.homepage != null)
                          _QuietLink(label: 'Website', url: entry.homepage!),
                        if (entry.upstream != null)
                          _QuietLink(label: 'Source', url: entry.upstream!),
                        if (entry.repo != null)
                          _QuietLink(label: 'Package', url: entry.repo!),
                        if (entry.license != null)
                          _QuietLink(label: '${entry.license} licence'),
                      ],
                    ),
                    const SizedBox(height: 34),
                    if (essential != null) ...[
                      Center(
                        child: FilledButton(
                          key: const ValueKey('store-primary-action'),
                          onPressed: local == null || essential.opening
                              ? null
                              : () => unawaited(_openEssential(essential)),
                          style: FilledButton.styleFrom(
                            backgroundColor: grid.AppPalette.textPrimary,
                            foregroundColor: grid.AppPalette.windowBg,
                            minimumSize: const Size(148, 50),
                            padding: const EdgeInsets.symmetric(horizontal: 30),
                            textStyle: grid.AppType.label(
                              fontWeight: grid.AppFont.semibold,
                            ),
                            shape: const StadiumBorder(),
                          ),
                          child: Text(essential.exists ? 'Open' : 'Create'),
                        ),
                      ),
                      const SizedBox(height: 10),
                      Text(
                        'Free on OpenCode. Switch to any agent from the pane.',
                        key: const ValueKey('store-essential-note'),
                        textAlign: TextAlign.center,
                        style: grid.AppType.body(
                          color: grid.AppPalette.textSecondary,
                        ),
                      ),
                    ] else if (showAction && !showLaunch)
                      Center(
                        child: FilledButton(
                          key: const ValueKey('store-primary-action'),
                          onPressed: workspace != null
                              ? () => _open(local?.machine.machineId ?? '')
                              : local == null ||
                                    busy ||
                                    installing ||
                                    (!localInstalled &&
                                        !_canGetOnMachine(local, entry))
                              ? null
                              : () => hasUpdate
                                    ? _update(local.machine.machineId)
                                    : _get(local.machine.machineId),
                          style: FilledButton.styleFrom(
                            backgroundColor: grid.AppPalette.textPrimary,
                            foregroundColor: grid.AppPalette.windowBg,
                            minimumSize: const Size(148, 50),
                            padding: const EdgeInsets.symmetric(horizontal: 30),
                            textStyle: grid.AppType.label(
                              fontWeight: grid.AppFont.semibold,
                            ),
                            shape: const StadiumBorder(),
                          ),
                          child: Text(
                            workspace != null
                                ? 'Open'
                                : installing || busy
                                ? 'Working…'
                                : hasUpdate
                                ? 'Update'
                                : failed
                                ? 'Try again'
                                : 'Get',
                          ),
                        ),
                      ),
                    if (hasUpdate) ...[
                      const SizedBox(height: 10),
                      Text(
                        'Your projects and files are kept.',
                        textAlign: TextAlign.center,
                        style: grid.AppType.body(
                          color: grid.AppPalette.textSecondary,
                        ),
                      ),
                    ],
                    if (showLaunch) ...[
                      Center(
                        child: StoreHarnessActions(
                          notifier: widget.notifier,
                          harnessId: entry.id,
                          recent: widget.recentHarnesses,
                          prominent: true,
                          newButtonKey: const ValueKey('store-primary-action'),
                          onNew: local != null && !busy && !installing
                              ? () => _open(local.machine.machineId)
                              : null,
                        ),
                      ),
                    ],
                    const SizedBox(height: 14),
                    if (workspace == null)
                      Center(
                        child: local == null
                            ? Text(
                                storeRunsNoHarness(context)
                                    ? 'Get it in the Harness app on a computer.'
                                    : 'Connecting to this computer…',
                                style: grid.AppType.body(
                                  color: grid.AppPalette.textFaint,
                                ),
                              )
                            : _InstallLine(
                                key: ValueKey(
                                  'store-machine:${local.machine.machineId}',
                                ),
                                state: local,
                                entry: entry,
                                busy: busy,
                                onRemove: () => _remove(
                                  local.machine.machineId,
                                  local.machine.displayName,
                                ),
                              ),
                      ),
                    const SizedBox(height: 24),
                  ],
                ),
              ),
              if (examples.isNotEmpty) ...[
                SizedBox(height: wide ? 136 : 88),
                StoreExampleFlow(
                  entry: entry,
                  examples: examples,
                  onTry: canTry
                      ? (prompt) =>
                            _open(local.machine.machineId, prompt: prompt)
                      : null,
                ),
              ],
              for (final (i, url) in screenshots.indexed) ...[
                SizedBox(height: i == 0 ? (wide ? 120 : 72) : 48),
                Center(
                  child: ConstrainedBox(
                    constraints: const BoxConstraints(maxWidth: 1120),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(wide ? 28 : 18),
                      child: Image.network(
                        url,
                        fit: BoxFit.cover,
                        errorBuilder: (_, _, _) => const SizedBox.shrink(),
                      ),
                    ),
                  ),
                ),
              ],
              if (page != null || !rating.isEmpty) ...[
                SizedBox(height: wide ? 160 : 96),
                Center(
                  child: ConstrainedBox(
                    key: _reviewsKey,
                    constraints: const BoxConstraints(maxWidth: 720),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Text(
                          'Ratings and reviews',
                          textAlign: TextAlign.center,
                          style: grid.AppType.heading(
                            color: grid.AppPalette.textPrimary,
                          ),
                        ),
                        const SizedBox(height: 6),
                        Center(
                          child: TextButton(
                            key: const ValueKey('store-write-review'),
                            onPressed: _review,
                            child: Text(
                              page?.mine == null
                                  ? 'Write a review'
                                  : 'Edit your review',
                            ),
                          ),
                        ),
                        const SizedBox(height: 20),
                        if (!rating.isEmpty) _RatingSummary(rating: rating),
                        if (widget.store.reviewsError[_key] != null) ...[
                          const SizedBox(height: 8),
                          Text(
                            'Reviews are unavailable right now.',
                            textAlign: TextAlign.center,
                            style: grid.AppType.body(
                              color: grid.AppPalette.textSecondary,
                            ),
                          ),
                        ],
                        const SizedBox(height: 16),
                        if (page != null && page.reviews.isEmpty)
                          Text(
                            'No reviews yet. Be the first.',
                            textAlign: TextAlign.center,
                            style: grid.AppType.body(
                              color: grid.AppPalette.textFaint,
                            ),
                          ),
                        for (final review
                            in page?.reviews ?? const <StoreReview>[])
                          Padding(
                            padding: const EdgeInsets.only(bottom: 10),
                            child: _ReviewCard(
                              key: ValueKey('store-review:${review.id}'),
                              review: review,
                              onEdit: review.mine ? _review : null,
                            ),
                          ),
                      ],
                    ),
                  ),
                ),
              ],
            ],
          ),
        );
      },
    );
  }
}

/// The one line under the page's action: where this is, and what it is doing there — asking,
/// installing, installed, failed — with Remove once there is something to remove.
class _InstallLine extends StatelessWidget {
  const _InstallLine({
    super.key,
    required this.state,
    required this.entry,
    required this.busy,
    required this.onRemove,
  });

  final MachineState state;
  final DshEntry entry;
  final bool busy;
  final VoidCallback onRemove;

  String _engineStatus() {
    final installed = state.engines[entry.id]?.installed == true;
    if (!installed && state.needsLink) return 'Link required';
    if (!installed && state.nodeOnline == false) return 'Offline';
    if (!state.engines.loaded) return 'Asking…';
    return installed ? 'Installed' : 'Not installed';
  }

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    TerminalFontScope.watch(context);
    final row = _machineHarness(state, entry.id);
    final run = state.dsh.runs[_operationId(state, entry.id)];
    final installing = run != null && run.inProgress;
    final installed = !entry.isEngine && row?.installed == true;
    final String status;
    // On a failure: what the machine said, in full, a hover away. The line
    // itself says which kind of thing went wrong and what to do about it —
    // a bare "Install failed" over a fetch the network dropped left nothing to
    // tell it apart from a broken package (issue #109).
    String? failureTooltip;
    if (entry.isEngine) {
      status = _engineStatus();
    } else if (installing) {
      status = switch (run.phase) {
        'clone' => 'Fetching…',
        'setup' => 'Setting up the toolchain…',
        'doctor' => 'Checking…',
        _ => 'Installing…',
      };
    } else if (run != null && run.failed) {
      final failure = describeInstallFailure(run, entry.name);
      status = failure.hint == null
          ? failure.title
          : '${failure.title} ${failure.hint}';
      final words = [
        if (failure.body != null && failure.body != failure.title) failure.body,
        if (failure.command != null) failure.command,
        if (run.detail != null &&
            run.detail != failure.body &&
            run.detail != failure.title)
          run.detail,
      ].whereType<String>().join('\n');
      if (words.isNotEmpty) failureTooltip = words;
    } else if (installed) {
      status = row?.linked == true
          ? 'Installed · linked to a checkout'
          : row?.hasUpdate == true
          ? 'Update available'
          : 'Installed';
    } else if (state.needsLink) {
      // Why a machine cannot take this package right now, when it cannot. An
      // offline or unlinked machine answers nothing, so without these the line
      // said "Asking…" forever; a machine whose CLI predates the package lists
      // no row for it, and a Get there would only fail.
      status = 'Link required';
    } else if (state.nodeOnline == false) {
      status = 'Offline';
    } else if (state.dsh.loaded && state.dsh.error == null && row == null) {
      status = 'Update Harness CLI on this machine to get it';
    } else if (!state.dsh.loaded) {
      // `dsh_list` refused by a CLI that predates it arrives as the bare wire
      // code; the line says what to do about it instead.
      status = switch (state.dsh.error) {
        null => 'Asking…',
        'UNSUPPORTED' || 'UNSUPPORTED_ON_REMOTE' =>
          'Update the harness CLI on this machine to install harnesses',
        final error => error,
      };
    } else {
      status = 'Not installed';
    }
    final faint = grid.AppType.body(color: grid.AppPalette.textFaint);
    return Wrap(
      alignment: WrapAlignment.center,
      crossAxisAlignment: WrapCrossAlignment.center,
      spacing: 8,
      runSpacing: 4,
      children: [
        if (installing || busy)
          const SizedBox(
            width: 12,
            height: 12,
            child: CircularProgressIndicator(strokeWidth: 1.6),
          ),
        Text('${state.machine.displayName} · this computer', style: faint),
        Text('·', style: faint),
        _maybeTooltip(
          failureTooltip,
          Text(
            status,
            key: const ValueKey('store-install-status'),
            style: grid.AppType.body(
              color: run?.failed == true
                  ? grid.AppPalette.warn
                  : grid.AppPalette.textSecondary,
            ),
          ),
        ),
        if (installed && row?.installedCommit != null)
          Tooltip(
            message: row?.availableCommit == null
                ? 'Installed version: ${row!.installedCommit}'
                : 'Installed: ${row!.installedCommit}\nAvailable: ${row.availableCommit}',
            child: Text(
              row.installedCommit!.substring(0, 8),
              style: grid.AppType.monoLabel(
                fontWeight: grid.AppFont.regular,
                color: grid.AppPalette.textFaint,
              ),
            ),
          ),
        if (installed && !installing && !busy) ...[
          Text('·', style: faint),
          _QuietLink(
            key: ValueKey('store-remove:${state.machine.machineId}'),
            label: 'Remove',
            onTap: onRemove,
          ),
        ],
      ],
    );
  }
}

Widget _maybeTooltip(String? message, Widget child) => message == null
    ? child
    : Tooltip(
        key: const ValueKey('store-install-failure-detail'),
        message: message,
        waitDuration: const Duration(milliseconds: 300),
        child: child,
      );

/// A link that stays out of the way: secondary text, brighter under the pointer, an arrow when it
/// leaves the app. Without a destination it is plain text (the licence).
class _QuietLink extends StatefulWidget {
  const _QuietLink({super.key, this.label, this.url, this.onTap, this.child})
    : assert(label != null || child != null);

  final String? label;
  final String? url;
  final VoidCallback? onTap;
  final Widget? child;

  @override
  State<_QuietLink> createState() => _QuietLinkState();
}

class _QuietLinkState extends State<_QuietLink> {
  var _hovering = false;

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    final url = widget.url;
    final VoidCallback? tap = url != null
        ? () => unawaited(
            launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication),
          )
        : widget.onTap;
    final color = tap == null
        ? grid.AppPalette.textFaint
        : _hovering
        ? grid.AppPalette.textPrimary
        : grid.AppPalette.textSecondary;
    final content = DefaultTextStyle.merge(
      style: grid.AppType.label(color: color),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          widget.child ?? Text(widget.label!),
          if (url != null) ...[
            const SizedBox(width: 3),
            Icon(AppIcons.arrowUpRight, size: 14, color: color),
          ],
        ],
      ),
    );
    if (tap == null) return content;
    if (storeIsCompact(context)) {
      return StoreHitArea(
        onTap: tap,
        onHover: (hovering) => setState(() => _hovering = hovering),
        child: content,
      );
    }
    return MouseRegion(
      cursor: SystemMouseCursors.click,
      onEnter: (_) => setState(() => _hovering = true),
      onExit: (_) => setState(() => _hovering = false),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: tap,
        child: content,
      ),
    );
  }
}

/// Drawn only for a rating somebody has given.
class _RatingSummary extends StatelessWidget {
  const _RatingSummary({required this.rating});
  final StoreRating rating;

  @override
  Widget build(BuildContext context) {
    TerminalFontScope.watch(context);
    final max = rating.histogram.fold<int>(0, (a, b) => a > b ? a : b);
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              rating.average.toStringAsFixed(1),
              style: grid.AppType.title(
                height: 1,
                color: grid.AppPalette.textPrimary,
                fontFeatures: grid.AppFont.tabularFigures,
              ),
            ),
            const SizedBox(height: 6),
            Text(
              'out of 5 · ${rating.count} rating${rating.count == 1 ? '' : 's'}',
              style: grid.AppType.body(color: grid.AppPalette.textFaint),
            ),
          ],
        ),
        const SizedBox(width: 28),
        Expanded(
          child: Column(
            children: [
              for (var stars = 5; stars >= 1; stars--)
                Padding(
                  padding: const EdgeInsets.only(bottom: 4),
                  child: Row(
                    children: [
                      SizedBox(
                        width: 16,
                        child: Text(
                          '$stars',
                          textAlign: TextAlign.right,
                          style: grid.AppType.caption(
                            color: grid.AppPalette.textFaint,
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(4),
                          child: LinearProgressIndicator(
                            minHeight: 6,
                            value: max == 0
                                ? 0
                                : rating.histogram[stars - 1] / max,
                            backgroundColor: grid.AppSurface.selectedFill,
                            color: _Stars._amber,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
            ],
          ),
        ),
      ],
    );
  }
}

class _ReviewCard extends StatelessWidget {
  const _ReviewCard({super.key, required this.review, this.onEdit});
  final StoreReview review;
  final VoidCallback? onEdit;

  static String _when(DateTime at) {
    final days = DateTime.now().difference(at).inDays;
    if (days <= 0) return 'today';
    if (days == 1) return 'yesterday';
    if (days < 30) return '$days days ago';
    if (days < 365) {
      return '${days ~/ 30} month${days ~/ 30 == 1 ? '' : 's'} ago';
    }
    return '${days ~/ 365} year${days ~/ 365 == 1 ? '' : 's'} ago';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: grid.AppPalette.cardBg,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: grid.AppPalette.divider),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              _Stars(value: review.rating.toDouble(), size: 13),
              const SizedBox(width: 8),
              if (review.title != null)
                Expanded(
                  child: Text(
                    review.title!,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: grid.AppType.label(
                      color: grid.AppPalette.textPrimary,
                    ),
                  ),
                )
              else
                const Spacer(),
              if (onEdit != null)
                TextButton(
                  onPressed: onEdit,
                  style: TextButton.styleFrom(
                    foregroundColor: grid.AppPalette.textSecondary,
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    minimumSize: const Size(0, 28),
                  ),
                  child: const Text('Edit'),
                ),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            '${review.mine ? 'You' : review.authorName} · ${_when(review.updatedAt)}',
            style: grid.AppType.body(color: grid.AppPalette.textFaint),
          ),
          if (review.body != null) ...[
            const SizedBox(height: 8),
            Text(
              review.body!,
              style: grid.AppType.body(
                height: 1.45,
                color: grid.AppPalette.textPrimary,
              ),
            ),
          ],
        ],
      ),
    );
  }
}

// ─── dialogs ─────────────────────────────────────────────────────────────────

class _ReviewDraft {
  const _ReviewDraft({
    required this.rating,
    this.title,
    this.body,
    this.delete = false,
  });
  final int rating;
  final String? title;
  final String? body;
  final bool delete;
}

class _ReviewDialog extends StatefulWidget {
  const _ReviewDialog({required this.name, this.existing});
  final String name;
  final StoreReview? existing;

  @override
  State<_ReviewDialog> createState() => _ReviewDialogState();
}

class _ReviewDialogState extends State<_ReviewDialog> {
  late int _rating = widget.existing?.rating ?? 0;
  late final _title = TextEditingController(text: widget.existing?.title ?? '');
  late final _body = TextEditingController(text: widget.existing?.body ?? '');

  @override
  void dispose() {
    _title.dispose();
    _body.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _DialogCard(
      width: 460,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            widget.existing == null
                ? 'Rate ${widget.name}'
                : 'Your review of ${widget.name}',
            style: grid.AppType.heading(color: grid.AppPalette.textPrimary),
          ),
          const SizedBox(height: 14),
          _Stars(
            key: const ValueKey('store-review-stars'),
            value: _rating.toDouble(),
            size: 30,
            onPick: (n) => setState(() => _rating = n),
          ),
          const SizedBox(height: 14),
          const FieldLabel('Title (optional)'),
          TextField(
            key: const ValueKey('store-review-title'),
            controller: _title,
            maxLength: 80,
            decoration: const InputDecoration(counterText: ''),
          ),
          const SizedBox(height: 10),
          const FieldLabel('What was it like?'),
          TextField(
            key: const ValueKey('store-review-body'),
            controller: _body,
            maxLength: 2000,
            minLines: 3,
            maxLines: 8,
            decoration: const InputDecoration(counterText: ''),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              if (widget.existing != null)
                TextButton(
                  key: const ValueKey('store-review-delete'),
                  onPressed: () =>
                      Navigator.of(context)
                          .pop(const _ReviewDraft(rating: 0, delete: true)),
                  style: TextButton.styleFrom(
                    foregroundColor: grid.AppPalette.warn,
                  ),
                  child: const Text('Delete review'),
                ),
              const Spacer(),
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('Cancel'),
              ),
              const SizedBox(width: 8),
              FilledButton(
                key: const ValueKey('store-review-post'),
                onPressed: _rating == 0
                    ? null
                    : () => Navigator.of(context).pop(
                        _ReviewDraft(
                          rating: _rating,
                          title: _title.text,
                          body: _body.text,
                        ),
                      ),
                child: Text(widget.existing == null ? 'Post' : 'Save'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _ConfirmCard extends StatelessWidget {
  const _ConfirmCard({
    required this.title,
    required this.detail,
    required this.action,
  });
  final String title;
  final String detail;
  final String action;

  @override
  Widget build(BuildContext context) {
    return _DialogCard(
      width: 420,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            title,
            style: grid.AppType.heading(color: grid.AppPalette.textPrimary),
          ),
          const SizedBox(height: 8),
          Text(
            detail,
            style: grid.AppType.body(
              height: 1.4,
              color: grid.AppPalette.textSecondary,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('Cancel'),
              ),
              const SizedBox(width: 8),
              FilledButton(
                key: const ValueKey('store-confirm'),
                onPressed: () => Navigator.of(context).pop(true),
                style: FilledButton.styleFrom(
                  backgroundColor: grid.AppPalette.dangerFill,
                ),
                child: Text(action),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _DialogCard extends StatelessWidget {
  const _DialogCard({required this.width, required this.child});
  final double width;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Material(
        color: grid.AppPalette.panelBg,
        borderRadius: BorderRadius.circular(16),
        clipBehavior: Clip.antiAlias,
        child: Container(
          width: width,
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: grid.AppPalette.divider),
          ),
          child: child,
        ),
      ),
    );
  }
}