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.

50.9 KB
Raw Blame
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:package_info_plus/package_info_plus.dart';

import 'package:harness_mobile/core/app_settings.dart';
import 'package:harness_mobile/core/app_version.dart';
import 'package:harness_mobile/demo/sample_mode.dart'
    show SampleMode, SampleSession, openSampleMode;
import 'package:harness_mobile/core/device_name.dart';
import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
import 'package:harness_mobile/measurement/product_measurement.dart';
import 'package:harness_mobile/shared/widgets/app_dialog.dart';
import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/appearance_prefs_store.dart';
import 'package:harness_mobile/shared/theme/color_palette.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/swarm/swarm_start.dart' show SwarmIntroPage;
import 'package:harness_mobile/swarm/swarm_style.dart'
    show
        SwarmAvatar,
        SwarmBackButton,
        SwarmCaption,
        SwarmRowGlyph,
        SwarmTopBar;
import 'package:harness_mobile/terminal/terminal_font_store.dart';
import 'package:harness_mobile/terminal/terminal_theme_store.dart';

import 'add_device/add_device_page.dart';
import 'approve_sign_in.dart';
import 'connectors_page.dart';
import 'devices_page.dart';
import 'machine_index.dart' show visibleMachines;
import 'machine_profile_picker.dart';
import 'machines_tab.dart';
import 'out_of_sight.dart';
import 'phone_navigation.dart' show phoneRoute;
import 'phone_name_store.dart';
import 'phone_sheet.dart';
import 'settings_row.dart';
import 'privacy_page.dart';
import 'privacy_policy.dart';
import 'welcome/how_it_works.dart';
import 'welcome/focus_hints.dart';
import 'tty_controls.dart';
import 'tty.dart';
import 'usage_entry.dart';
import 'voice_language.dart';
import 'voice_language_store.dart';
import '../swarm/swarm_session.dart' show SwarmScope;
import 'account_profile_dialog.dart';

/// The phone's Settings tab.
///
/// DELIBERATELY not the desktop's eight sections. Three of them cannot work in a viewer build and
/// would each be a screen that opens on nothing:
///
///  - **Autonomous devices** flashes an ESP32 over a serial port, through the CLI. A viewer has no
///    CLI and a phone has no serial port.
///  - **Keyboard shortcuts** is a list of ⌘ combinations for a keyboard that is not there.
///  - **Check for updates** belongs to the desktop updater; a phone build is updated by its store.
///
/// **Usage** used to be on that list, for a reason that was true of the desktop reader and not of
/// the setting: it counts by reading `~/.claude/projects`, `~/.codex` and OpenCode's SQLite file ON
/// THIS DISK, and a phone has none of them. What a phone can do is ask the machine that does — so
/// the section is kept, and its row comes from elsewhere: `usage_entry.dart` reads each linked
/// machine's rate limits over `usage_read`.
///
/// What a phone shows that the desktop splits across panes:
///
///  - **Appearance** carries the [HarnessPalette] choices the desktop keeps in its own Customize
///    pane — six dark, two light. They are not decoration here: the phone's tab bar, cards and
///    terminal ground are all drawn from the chosen palette, a light one is how the phone goes
///    light, and until now the phone shipped whichever one the desktop had last written to
///    `~/.harness`.
///  - **Terminal** carries the colour scheme beside the face and the size, because on a phone all
///    three answer the same question — what the pane looks like at arm's length.
///  - **Voice** carries the language the mic is transcribed in. A section of one row, and it earns
///    it: on a phone the mic is a way of typing, not a decoration on the terminal, and a person
///    whose words came back in the wrong language looks for the word "Voice".
///
/// The desktop's **Debug** screen has no counterpart here on purpose. It reads an in-memory ring
/// that only a debug build fills, so on a shipped phone the row would open on an empty page — and
/// the log files it mirrors are written either way, which is what a fault report actually needs.
///
/// What a phone adds instead is the account and the machine links, which the desktop keeps in its
/// rail footer — on a phone there is no rail, so this is the only way to reach either.

class SettingsPage extends StatelessWidget {
  const SettingsPage({
    super.key,
    required this.notifier,
    this.large = true,
    this.experiments,
    this.appearance,
    this.swarm = false,
  });

  final AppNotifier notifier;

  /// Drawn as Swarm's pages are ([SettingsSwarmLook]): opened from Swarm's You. Swarm's top bar
  /// then stands in for the big title, whatever [large] says, and the list is Swarm's shorter one —
  /// fewer rows and captions (`docs/design/2026-11-03-swarm-settings.md`). Notifications and Theme
  /// are not in it: they sit on You itself, one tap nearer (Tony 2026-11-04, `SwarmYouPage`).
  final bool swarm;

  /// What Experimental switches: [experimentalFeaturesStore] unless a test hands in its own, so a
  /// tap there never writes to the developer's own state file.
  final ExperimentalFeaturesStore? experiments;

  /// What Appearance changes: [appearancePrefsStore] unless a test hands in its own, for the same
  /// reason as [experiments].
  final AppearancePrefsStore? appearance;

  /// The tab's big title. Off when the page is pushed from a terminal's menu, where it needs the
  /// back chevron a large header does not draw.
  final bool large;

  // While out of sight (the You tab under another), it follows the app no more, and catches up
  // once shown.
  @override
  Widget build(BuildContext context) => ListenWhileInSight(
    listenable: notifier,
    builder: (context) {
      AppTheme.watch(context);
      final tty = Tty.of(context);
      final body = _Body(
        notifier: notifier,
        experiments: experiments ?? experimentalFeaturesStore,
        appearance: appearance ?? appearancePrefsStore,
      );
      // In the app's face, as Swarm's pages are; only the bar's title is the terminal's.
      if (swarm) {
        return Scaffold(
          backgroundColor: tty.ground,
          body: SafeArea(
            bottom: false,
            child: SettingsSwarmLook(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  SwarmTopBar(
                    leading: SwarmBackButton(
                      onPressed: () => Navigator.of(context).maybePop(),
                    ),
                    title: 'Settings',
                  ),
                  Expanded(child: body),
                ],
              ),
            ),
          ),
        );
      }
      return Scaffold(
        backgroundColor: tty.ground,
        body: SafeArea(
          bottom: false,
          // The terminal's face for every row below, as on every other screen of the phone.
          // Through the theme, not only a DefaultTextStyle: every Material in the rows resets the
          // default text style from the theme's text theme.
          child: Theme(
            data: Theme.of(context).copyWith(
              textTheme: Theme.of(context).textTheme.apply(
                fontFamily: tty.fontFamily,
                fontFamilyFallback: tty.fontFallback,
              ),
            ),
            child: DefaultTextStyle.merge(
              style: TextStyle(
                fontFamily: tty.fontFamily,
                fontFamilyFallback: tty.fontFallback,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  if (!large)
                    Align(
                      alignment: Alignment.centerLeft,
                      child: TtyBackButton(
                        onPressed: () => Navigator.of(context).maybePop(),
                      ),
                    ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(
                      Tty.origin,
                      8,
                      Tty.origin,
                      0,
                    ),
                    child: TtyText(
                      'Settings',
                      size: TtySize.display,
                      weight: FontWeight.w600,
                    ),
                  ),
                  Expanded(child: body),
                ],
              ),
            ),
          ),
        ),
      );
    },
  );
}

class _Body extends StatelessWidget {
  const _Body({
    required this.notifier,
    required this.experiments,
    required this.appearance,
  });

  final AppNotifier notifier;
  final ExperimentalFeaturesStore experiments;
  final AppearancePrefsStore appearance;

  @override
  Widget build(BuildContext context) => ListView(
    padding: EdgeInsets.fromLTRB(
      Tty.origin,
      // Zero: the first caption brings its own 22pt top, and any padding here would stack on it —
      // the gap under the big "Settings" title would then be a header gap plus a between-groups
      // gap, wider than every other gap on the screen.
      0,
      Tty.origin,
      MediaQuery.paddingOf(context).bottom + 24,
    ),
    children: [
      if (SettingsSwarmLook.of(context))
        ..._swarmAccount(context)
      else ...[
        SettingsCaption(_sample(context) == null ? 'Account' : 'Sample'),
        // Who you are, what you have used, the computers you reach and what they call this phone —
        // one group, so no row stands alone under a heading that only repeats it.
        SettingsGroup(
          children: [
            _accountRow(context),
            // ⚠️ Usage sits right under the account, above everything that is set once and left
            // alone, and that is deliberate: it is the only row here anybody opens twice.
            // No Stats row: counters this app keeps about itself are nobody's daily question.
            buildUsageSettingsRow(context, notifier),
            ?_privacyRow(context),
            _computersRow(context),
            ?_profileRow(context),
            _connectorsRow(context),
            _signInRow(context),
            _addDeviceRow(context),
            _devicesRow(context),
            // Under Your devices: a new device on the account is one of the two things a notice
            // says.
            ?_notificationsRow(context),
            // The name those computers show when this phone takes a harness over — which makes it
            // a fact about the account's computers, not about how the terminal looks.
            _PhoneNameRow(notifier: notifier),
          ],
        ),
      ],
      const SettingsCaption('Terminal'),
      SettingsGroup(
        children: [
          _FontPreview(),
          _FontRow(),
          _SizeRow(),
          _TerminalThemeRow(),
          // In Swarm's look the mic's language closes Terminal's card instead of a Voice section
          // of its own: there every row leads with a glyph, and the mic's says what the row is
          // about where the plain rows below needed a caption to.
          // See docs/design/2026-11-03-swarm-settings.md.
          if (SettingsSwarmLook.of(context)) _VoiceLanguageRow(),
        ],
      ),
      // ⚠️ **Its own section, not a row under Terminal.** The rows above answer
      // what the pane LOOKS like — face, size, colours. This one answers what the mic HEARS, which is
      // the other half of the terminal and the one people go looking for when
      // the transcript comes back in the wrong language. Under a Terminal
      // caption it read as another thing about the type. (Swarm's look aside, above.)
      if (!SettingsSwarmLook.of(context)) ...[
        const SettingsCaption('Voice'),
        SettingsGroup(children: [_VoiceLanguageRow()]),
      ],
      const SettingsCaption('Appearance'),
      SettingsGroup(
        children: [
          // The terminal's Settings offers the eight palettes. Swarm's asks light or dark instead,
          // on You itself (its Theme), so its Appearance is the text size alone.
          if (!SettingsSwarmLook.of(context)) _PaletteRow(store: appearance),
          _TextSizeRow(),
        ],
      ),
      // The desktop's Labs ▸ Experimental, and in the same place: after how the app looks, before
      // Help. Features still being built, each off until turned on here.
      const SettingsCaption('Experimental'),
      SettingsGroup(
        children: [
          for (final experiment in PhoneExperiment.values)
            _ExperimentRow(experiment: experiment, store: experiments),
        ],
      ),
      // Help's three rows and About's two are each one row in Swarm's look, opening a sheet of
      // them: all five are opened once in a while, and as rows they were a fifth of the page.
      if (SettingsSwarmLook.of(context)) ...[
        const SizedBox(height: AppSpace.xl),
        SettingsGroup(children: [_helpRow(context), const _AboutRow()]),
      ] else ...[
        const SettingsCaption('Help'),
        SettingsGroup(
          children: [
            SettingsRow(
              title: 'How Harness works',
              glyph: LucideIcons.circleHelp300,
              onTap: () => unawaited(openHowItWorks(context)),
            ),
            // The offline sample, from inside the real app too — to show somebody, or to try a
            // gesture without touching a real harness. Not offered inside the sample itself.
            if (_sample(context) == null)
              SettingsRow(
                title: 'Try the sample',
                glyph: LucideIcons.play300,
                onTap: () => unawaited(openSampleMode(context)),
              ),
            SettingsRow(
              title: 'Show the tips again',
              glyph: LucideIcons.lightbulb300,
              onTap: () => _showTipsAgain(context),
            ),
          ],
        ),
        const SettingsCaption('About'),
        SettingsGroup(
          children: [
            const _VersionRow(),
            const _BuildRow(),
            // The stores want the policy reachable from inside the app — see [kPrivacyPolicyUrl].
            SettingsRow(
              title: 'Privacy Policy',
              glyph: LucideIcons.fileText300,
              onTap: () => unawaited(openPrivacyPolicy(context)),
            ),
          ],
        ),
      ],
    ],
  );

  void _showTipsAgain(BuildContext context) {
    unawaited(FocusHintsSeen.shared.forget());
    ScaffoldMessenger.maybeOf(context)?.showSnackBar(
      const SnackBar(content: Text('The tips come back on the next harness.')),
    );
  }

  /// Help's rows as one, in Swarm's look: the same three, in the same words, in a sheet. Each
  /// runs after the sheet has closed ([PhoneSheetAction.onTap]), so on this page's context.
  Widget _helpRow(BuildContext context) => SettingsRow(
    key: const ValueKey('settings-help'),
    title: 'Help',
    glyph: LucideIcons.circleHelp300,
    onTap: () => showPhoneSheet(
      context,
      title: 'Help',
      actions: [
        PhoneSheetAction(
          icon: LucideIcons.circleHelp300,
          label: 'How Harness works',
          chevron: true,
          onTap: () => unawaited(openHowItWorks(context)),
        ),
        if (_sample(context) == null)
          PhoneSheetAction(
            icon: LucideIcons.play300,
            label: 'Try the sample',
            chevron: true,
            onTap: () => unawaited(openSampleMode(context)),
          ),
        PhoneSheetAction(
          icon: LucideIcons.lightbulb300,
          label: 'Show the tips again',
          onTap: () => _showTipsAgain(context),
        ),
      ],
    ),
  );

  /// The sample this page is in, or null in the real app — see `lib/demo/sample_mode.dart`.
  SampleSession? _sample(BuildContext context) =>
      SampleMode.maybeOf(context) ?? SampleMode.ofNotifier(notifier);

  /// The account's rows as Swarm splits You's, in cards with no caption (prototype A lean,
  /// 2026-11-03, `docs/design/2026-11-03-swarm-settings.md`): you and what you use; your computers;
  /// this phone. Notifications is on You, one level up (2026-11-04).
  List<Widget> _swarmAccount(BuildContext context) => [
    if (_sample(context) != null)
      const SwarmCaption('Sample', first: true)
    else
      const SizedBox(height: AppSpace.s),
    SettingsGroup(
      children: [
        _accountRow(context),
        buildUsageSettingsRow(context, notifier),
        ?_privacyRow(context),
      ],
    ),
    const SizedBox(height: AppSpace.l),
    SettingsGroup(
      children: [
        _computersRow(context),
        ?_profileRow(context),
        _connectorsRow(context),
        _signInRow(context),
        // ⚠️ Only while Computers has no list. Its Set up Intern 3 sits under the list
        // (`machines_tab.dart` `_ConnectBar`), and with no computer — none yet, still loading, or
        // not fetched — that page is an empty state whose one button is Add computer. Somebody
        // whose first Harness is an Intern 3 would have had no way to set it up from here.
        if (visibleMachines(notifier).isEmpty) _addDeviceRow(context),
      ],
    ),
    const SizedBox(height: AppSpace.l),
    SettingsGroup(
      children: [_devicesRow(context), _PhoneNameRow(notifier: notifier)],
    ),
  ];

  /// Not in the sample.
  Widget? _privacyRow(BuildContext context) => _sample(context) != null
      ? null
      : SettingsRow(
          title: 'Privacy',
          glyph: LucideIcons.shield300,
          onTap: () => Navigator.of(context).push(
            phoneRoute(
              (_) => PrivacyPage(
                request: ({bool? enabled}) async {
                  final value = await notifier.productUsageSettings(
                    enabled: enabled,
                  );
                  // Set here by the person: it also settles an opt-out made before sign-in.
                  notifier.productMeasurement.savedChoice(
                    value,
                    explicit: enabled != null,
                  );
                  await notifier.productMeasurement.setupChoiceSaved;
                  return value;
                },
                feedback: notifier.api.productUsageFeedback,
              ),
            ),
          ),
        );

  /// The computers this phone reaches — here rather than a menu of their own: linking one is a
  /// once-a-while errand, and Find already reaches every agent on them.
  /// Each computer's sheet there holds what the account can do to it — try it again, rename it,
  /// take it off the account (`machine_actions.dart`).
  Widget _computersRow(BuildContext context) => SettingsRow(
    title: 'Computers',
    glyph: LucideIcons.laptop300,
    onTap: () {
      notifier.productMeasurement.screenOpened(
        PhoneScreen.computers,
        ScreenOpening.button,
      );
      Navigator.of(context).push(
        phoneRoute(
          (_) => MachinesTab(notifier: notifier, large: false, fromSettings: true),
        ),
      );
    },
  );

  /// Which computer's tabs this phone shows — the desktop's Profiles. Beside Computers: it is a
  /// choice among them, and changes nothing on any of them. Only once there IS a choice — two
  /// computers or more — or one is already made, so it can be undone.
  Widget? _profileRow(BuildContext context) =>
      notifier.machines.length > 1 || notifier.machineProfileId != null
      ? SettingsRow(
          key: const Key('settings-profile'),
          title: 'Profile',
          glyph: LucideIcons.layers300,
          value: machineProfileLabel(notifier),
          onTap: () => unawaited(showMachineProfilePicker(context, notifier)),
        )
      : null;

  /// The services those computers' agents use (Linear, GitHub…), signed in to from here.
  Widget _connectorsRow(BuildContext context) => SettingsRow(
    key: const Key('settings-connectors'),
    title: 'Connectors',
    glyph: LucideIcons.plug300,
    onTap: () => Navigator.of(context).push(
      phoneRoute((_) => ConnectorsPage(notifier: notifier)),
    ),
  );

  /// A computer showing its sign-in QR (`harness login --qr`, or the web app's "Scan with your
  /// phone"): this phone approves it with its own account.
  Widget _signInRow(BuildContext context) => SettingsRow(
    key: const Key('settings-sign-in-computer'),
    title: 'Sign in a computer',
    glyph: LucideIcons.qrCode300,
    onTap: () => unawaited(signInAComputer(context, notifier)),
  );

  /// A Harness with no screen (a box, a mini PC): onto the person's Wi-Fi and signed in to this
  /// account through its setup hotspot.
  Widget _addDeviceRow(BuildContext context) => SettingsRow(
    key: const Key('settings-add-device'),
    title: 'Set up Intern 3',
    glyph: LucideIcons.server300,
    onTap: () => Navigator.of(context).push(
      phoneRoute((_) => AddDevicePage(notifier: notifier)),
    ),
  );

  /// Every device signed in to the account — each trusted by the others because of that, so this
  /// is where one that is not yours is seen and taken out.
  Widget _devicesRow(BuildContext context) => SettingsRow(
    title: 'Your devices',
    glyph: LucideIcons.monitorSmartphone300,
    value: notifier.newDevices.isEmpty
        ? null
        : '${notifier.newDevices.length} new',
    onTap: () => Navigator.of(context).push(
      phoneRoute((_) => DevicesPage(notifier: notifier)),
    ),
  );

  /// Not in the sample, whose notices go nowhere.
  Widget? _notificationsRow(BuildContext context) => _sample(context) == null
      ? NotificationsSettingsRow(notices: notifier.agentNotices.system)
      : null;

  /// Who is signed in — or, in sample mode, which has no account to show or sign out of, the
  /// way back out of it.
  Widget _accountRow(BuildContext context) {
    final sample = _sample(context);
    if (sample != null) {
      return SettingsRow(
        key: const ValueKey('settings-leave-sample'),
        title: 'Leave the sample',
        glyph: LucideIcons.logOut300,
        onTap: () => sample.leave(),
      );
    }
    return SettingsRow(
      leading: _Avatar(notifier: notifier),
      title: notifier.currentUser?.displayName ?? 'Signed in',
      detail: notifier.currentUser?.email,
      onTap: () => _showAccountSheet(context, notifier),
    );
  }

  void _showAccountSheet(BuildContext context, AppNotifier notifier) {
    // The Swarms read under the sheet's own context, before it opens: a Username field each (#2655).
    final swarms = accountProfileSwarms(SwarmScope.of(context));
    showPhoneSheet(
      context,
      title: notifier.currentUser?.email ?? 'Signed in',
      actions: [
        // Your name, and your @username in each Swarm: the desktop's avatar menu Profile (#2917).
        PhoneSheetAction(
          icon: LucideIcons.user300,
          label: 'Profile',
          onTap: () => unawaited(showAccountProfile(context, notifier, swarms: swarms)),
        ),
        PhoneSheetAction(
          icon: LucideIcons.logOut300,
          label: 'Sign out',
          destructive: true,
          onTap: () => unawaited(confirmSignOut(context, notifier)),
        ),
      ],
    );
  }
}

/// Sign out, asked first — from the account sheet here, and from "Not you? Sign out" on the page a
/// phone waits for its first computer on (`welcome/your_computer.dart`).
///
/// Asked first, because a sign-out is more than leaving this screen: the phone's key leaves the
/// account's devices ([AppNotifier.logout]), and signing in again makes a new one — which every
/// other device then announces as a new device. One stray tap in the sheet used to be all of it.
///
/// ⚠️ **"Signing out…" from the confirm on.** The sign-out takes up to 5 seconds before the welcome
/// screen comes up ([AppNotifier.logout]), and the page it was asked from used to stand there
/// unchanged meanwhile, its Sign out still there to press again. A page that cannot be left now
/// says what is happening; the signed-in screen, and it with it, goes when the sign-out lands.
Future<void> confirmSignOut(BuildContext context, AppNotifier notifier) async {
  if (notifier.signingOut) return;
  final confirmed = await confirmPhoneAction(
    context,
    // The sheet row's own icon — see [confirmPhoneAction].
    icon: LucideIcons.logOut300,
    title: 'Sign out?',
    detail: notifier.currentUser?.email,
    // "Your harnesses keep running" is news only to somebody who has harnesses: the account with
    // no computer is the wrong-account case "Not you? Sign out" is for.
    message: notifier.machines.isEmpty
        ? 'When you sign in again, your other devices will see this phone as a '
              'new device.'
        : 'Your harnesses keep running on your computers. When you sign in again, '
              'your other devices will see this phone as a new device.',
    confirmLabel: 'Sign out',
  );
  if (!confirmed) return;
  // The sign-out itself never waits on the page: one asked for is carried out.
  Route<void>? shown;
  if (context.mounted) {
    final route = phoneRoute(
      (_) => const _SigningOut(),
      swipeToGoBack: false,
    );
    unawaited(Navigator.of(context).push(route));
    shown = route;
  }
  try {
    await notifier.logout();
  } finally {
    // Gone with the signed-in screen when the sign-out lands; still here only if it was cut short.
    if (shown != null && shown.isActive) shown.navigator?.removeRoute(shown);
  }
}

/// The page a Sign out by hand stands on until the welcome screen comes up — see [confirmSignOut].
/// No way back from it: there is nothing left to go back to.
class _SigningOut extends StatelessWidget {
  const _SigningOut();

  @override
  Widget build(BuildContext context) {
    AppTheme.watch(context);
    return PopScope(
      canPop: false,
      child: Scaffold(
        backgroundColor: AppPalette.windowBg,
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox.square(
                dimension: 22,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  color: AppPalette.accent,
                ),
              ),
              const SizedBox(height: 14),
              Text(
                'Signing out…',
                key: const ValueKey('signing-out'),
                style: TextStyle(color: AppPalette.textSecondary, fontSize: 14),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// Settings over the current page — the page Find and a terminal's menu push, and Swarm's You
/// ([swarm], in Swarm's look).
void openPhoneSettings(
  BuildContext context,
  AppNotifier notifier, {
  bool swarm = false,
}) => unawaited(
  Navigator.of(context).push(
    phoneRoute(
      (_) => SettingsPage(notifier: notifier, large: false, swarm: swarm),
    ),
  ),
);

/// Settings, at the top right of the screens a phone stands on before it can reach any harness:
/// waiting for its first computer, unlocking the only one, the computers list while none is ready,
/// pairing by a scanned code.
///
/// ⚠️ **The only way to Settings from those screens, and so to Sign out.** Find and a terminal's
/// menu are where Settings otherwise opens, and both need a harness: a phone signed in to the wrong
/// account — one with no computer on it — had no way out short of deleting the app.
class PhoneSettingsButton extends StatelessWidget {
  const PhoneSettingsButton({super.key, required this.notifier});

  final AppNotifier notifier;

  @override
  Widget build(BuildContext context) {
    final tty = Tty.of(context);
    return Semantics(
      button: true,
      label: 'Settings',
      excludeSemantics: true,
      child: GestureDetector(
        key: const ValueKey('phone-settings'),
        behavior: HitTestBehavior.opaque,
        onTap: () {
          HapticFeedback.selectionClick();
          openPhoneSettings(context, notifier);
        },
        // The back chevron's box, mirrored: the same touch target, the glyph on the right gutter.
        child: SizedBox(
          width: 52,
          height: 44,
          child: Padding(
            padding: const EdgeInsets.only(right: Tty.origin - 2),
            child: Align(
              alignment: Alignment.centerRight,
              child: Icon(LucideIcons.settings300, size: 21, color: tty.faint),
            ),
          ),
        ),
      ),
    );
  }
}

class _Avatar extends StatelessWidget {
  const _Avatar({required this.notifier});

  final AppNotifier notifier;

  @override
  Widget build(BuildContext context) {
    AppTheme.watch(context);
    final user = notifier.currentUser;
    final source = (user?.name?.trim().isNotEmpty ?? false)
        ? user!.name!.trim()
        : (user?.email ?? '');
    // Swarm's round mark, in the colour Swarm gives this account on every screen.
    if (SettingsSwarmLook.of(context)) {
      return SwarmAvatar(id: user?.id ?? source, name: source, size: 40);
    }
    // ⚠️ The first CHARACTER, not the first code unit: a name that opens with an emoji starts on
    // half of a surrogate pair, and a lone half is a string the text engine refuses — it threw,
    // and took the whole Settings page down with it.
    final initial = source.isEmpty
        ? '?'
        : source.characters.first.toUpperCase();
    return Container(
      // 34, matching the stepper beside it two rows down: both are the tallest thing in their row,
      // and at 38 this one alone pushed its row past [kSettingsRowHeight] while the others sat on
      // it — one card with a taller first row.
      width: 34,
      height: 34,
      decoration: BoxDecoration(
        color: Tty.of(context).selected,
        shape: BoxShape.circle,
      ),
      alignment: Alignment.center,
      child: Text(
        initial,
        style: TextStyle(
          color: Tty.of(context).text,
          // Scaled with the disc: 15pt inside 34 left almost no ring around the letter, which
          // reads as a cramped badge rather than an avatar.
          fontSize: 14,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }
}

/// The language the mic under every terminal transcribes in.
///
/// ⚠️ **The mic's long press opens the same picker — but only in the build that taps to talk.**
/// Hold-to-talk gives that gesture to the recording (`voice_mic_mode.dart`), so there this row is the
/// whole of the setting: without it a phone transcribes in whatever language it guessed on first
/// launch, for ever. It is drawn either way rather than only in the build that needs it — a setting
/// that moves between releases is one nobody can be told where to find.
class _VoiceLanguageRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) => ValueListenableBuilder(
    valueListenable: voiceLanguageStore,
    builder: (context, code, _) {
      AppTheme.watch(context);
      return SettingsRow(
        // "Language", not "Voice language": the caption above the group
        // already said Voice, and a row that repeats its own section reads as
        // though there were a second kind of language further down.
        title: 'Language',
        glyph: LucideIcons.mic300,
        value: voiceLanguageName(code),
        onTap: () => unawaited(showVoiceLanguagePicker(context)),
      );
    },
  );
}

/// Whether this phone may notify — a harness finishing while the app is away, a new device on the
/// account ([noticesWhen]) — and the way to turn it on.
///
/// ⚠️ **The way back.** The OS asks once by itself, as the first terminal's tips go
/// (`terminal_page.dart`). A "Don't Allow" there had no way back from inside the app, and the device
/// notices went with it — the one warning that a key nobody recognises joined the account.
///
/// Off, a tap asks the OS: the prompt where it still has one to show, and where it does not (iOS
/// asks once; Android stops after a refusal or two) the answer is still no, so the way to the
/// phone's own switch is offered. On, a tap goes straight to that switch. Read again on the way back
/// from Settings. No value at all where the answer cannot be read (a stand-in notice centre).
///
/// In the terminal's Settings, and on Swarm's You ([SettingsSwarmLook] around it there), whose
/// Settings leaves it out.
class NotificationsSettingsRow extends StatefulWidget {
  const NotificationsSettingsRow({super.key, required this.notices});

  /// The phone's notice centre (`AgentAnnouncer.system`).
  final SystemNotices notices;

  @override
  State<NotificationsSettingsRow> createState() => _NotificationsSettingsRowState();
}

class _NotificationsSettingsRowState extends State<NotificationsSettingsRow>
    with WidgetsBindingObserver {
  bool? _on;

  SystemNotices get _notices => widget.notices;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    unawaited(_read());
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  /// Back from the phone's Settings, where the switch is — or from anywhere else it could change.
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) unawaited(_read());
  }

  Future<void> _read() async {
    final on = await noticesEnabled(_notices);
    if (mounted && on != _on) setState(() => _on = on);
  }

  Future<void> _tap() async {
    if (_on == true) {
      await openAppSettings();
      return;
    }
    await _notices.requestPermission();
    await _read();
    if (!mounted || _on != false) return;
    ScaffoldMessenger.maybeOf(context)?.showSnackBar(
      SnackBar(
        content: const Text(
          'Notifications are off for Harness. Turn them on in the phone’s Settings.',
        ),
        action: SnackBarAction(
          label: 'Open Settings',
          onPressed: () => unawaited(openAppSettings()),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    AppTheme.watch(context);
    return SettingsRow(
      key: const ValueKey('settings-notifications'),
      title: 'Notifications',
      glyph: LucideIcons.bell300,
      // On or Off says it in Swarm's look, which keeps its rows to one line.
      detail: SettingsSwarmLook.of(context) ? null : 'When $noticesWhen.',
      value: switch (_on) {
        true => 'On',
        false => 'Off',
        null => null,
      },
      onTap: () => unawaited(_tap()),
    );
  }
}

/// One [PhoneExperiment] and its switch. The whole row toggles it, as a phone's own settings do;
/// the switch only shows which way it is.
class _ExperimentRow extends StatelessWidget {
  const _ExperimentRow({required this.experiment, required this.store});

  final PhoneExperiment experiment;
  final ExperimentalFeaturesStore store;

  @override
  Widget build(BuildContext context) => ValueListenableBuilder(
    valueListenable: store,
    builder: (context, _, _) {
      AppTheme.watch(context);
      final on = store.isOn(experiment);
      void toggle(bool next) {
        HapticFeedback.selectionClick();
        // Swarm is turned on from its page, which says first what it does; off, it goes at once.
        if (next && experiment == PhoneExperiment.swarm) {
          unawaited(
            Navigator.of(context).push(phoneRoute((_) => SwarmIntroPage(features: store))),
          );
          return;
        }
        unawaited(store.set(experiment, next));
      }

      // One control to a screen reader: "Swarm, switch, off", not a button and a switch.
      return MergeSemantics(
        child: SettingsRow(
          key: ValueKey('settings-experiment-${experiment.id}'),
          title: experiment.label,
          glyph: LucideIcons.flaskConical300,
          // Swarm's look keeps its rows to one line; what Swarm is, its own intro page says as it
          // is turned on.
          detail: SettingsSwarmLook.of(context) ? null : experiment.description,
          trailing: Switch.adaptive(
            value: on,
            activeTrackColor: Tty.of(context).green,
            onChanged: toggle,
          ),
          onTap: () => toggle(!on),
        ),
      );
    },
  );
}

/// What this phone is called on another screen's "took control" banner —
/// the name the OS gives it until the person types their own here.
class _PhoneNameRow extends StatelessWidget {
  const _PhoneNameRow({required this.notifier});

  final AppNotifier notifier;

  @override
  Widget build(BuildContext context) => ValueListenableBuilder(
    valueListenable: phoneNameStore,
    builder: (context, override, _) {
      AppTheme.watch(context);
      return SettingsRow(
        key: const ValueKey('settings-phone-name'),
        // What the row sets, not what it is about: "This phone · Phone" read as a heading.
        title: 'Phone name',
        glyph: LucideIcons.smartphone300,
        value: notifier.phoneClientDescriptor().name,
        onTap: () => unawaited(
          showAppDialog<void>(
            context: context,
            builder: (_) => _PhoneNameDialog(
              current: override ?? '',
              placeholder: composePhoneName(
                device: NativeDeviceInfo.cached,
                userName: notifier.currentUser?.name,
              ),
            ),
          ),
        ),
      );
    },
  );
}

/// Owns its controller for the reason `widgets/rename_agent_dialog.dart` gives:
/// a controller disposed while the route is still animating out is a red screen.
class _PhoneNameDialog extends StatefulWidget {
  const _PhoneNameDialog({required this.current, required this.placeholder});

  /// The override on file, or empty for "the OS's name".
  final String current;

  /// What the phone is called with no override — shown as the field's hint.
  final String placeholder;

  @override
  State<_PhoneNameDialog> createState() => _PhoneNameDialogState();
}

class _PhoneNameDialogState extends State<_PhoneNameDialog> {
  late final _controller = TextEditingController(text: widget.current);

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _submit() {
    unawaited(phoneNameStore.rename(_controller.text));
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    AppTheme.watch(context);
    return AlertDialog(
      title: const Text('Phone name'),
      content: SizedBox(
        width: 360,
        child: TextField(
          key: const ValueKey('settings-phone-name-field'),
          controller: _controller,
          autofocus: true,
          maxLength: phoneNameMax,
          decoration: InputDecoration(
            hintText: widget.placeholder,
            helperText: 'Leave empty to use the name above.',
          ),
          onSubmitted: (_) => _submit(),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('Cancel'),
        ),
        FilledButton(onPressed: _submit, child: const Text('Save')),
      ],
    );
  }
}

/// One terminal line in the chosen face and size — what Font and Size change, live, above them.
class _FontPreview extends StatelessWidget {
  @override
  Widget build(BuildContext context) => ValueListenableBuilder(
    valueListenable: terminalFontStore,
    builder: (context, font, _) {
      AppTheme.watch(context);
      final tty = Tty.of(context);
      TextStyle ink(Color color) => TextStyle(
        fontFamily: font.fontFamily,
        fontFamilyFallback: font.fontFamilyFallback,
        fontSize: font.fontSize,
        height: 1.2,
        color: color,
      );
      return ExcludeSemantics(
        child: Padding(
          // In Swarm's look the line starts where the rows' titles do, after their glyphs.
          padding: EdgeInsets.fromLTRB(
            SettingsSwarmLook.of(context)
                ? AppSpace.l + SwarmRowGlyph.width + AppSpace.m
                : 13,
            14,
            13,
            14,
          ),
          child: Text.rich(
            TextSpan(
              children: [
                TextSpan(text: '~/web ', style: ink(tty.faint)),
                TextSpan(text: '❯ ', style: ink(tty.green)),
                TextSpan(text: 'claude "fix the login"', style: ink(tty.text)),
              ],
            ),
            maxLines: 1,
            softWrap: false,
            overflow: TextOverflow.clip,
          ),
        ),
      );
    },
  );
}

/// The terminal typeface. A sheet rather than a dropdown: a phone has room for the whole list.
class _FontRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) => ValueListenableBuilder(
    valueListenable: terminalFontStore,
    builder: (context, _, _) {
      AppTheme.watch(context);
      return SettingsRow(
        title: 'Font',
        glyph: LucideIcons.type300,
        value: terminalFontStore.family.label,
        onTap: () => showPhoneSheet(
          context,
          title: 'Terminal font',
          actions: [
            for (final choice in TerminalFontChoice.available)
              PhoneSheetAction(
                icon: choice == terminalFontStore.family
                    ? LucideIcons.check300
                    : LucideIcons.type300,
                label: choice.label,
                onTap: () => unawaited(terminalFontStore.setFamily(choice)),
              ),
          ],
        ),
      );
    },
  );
}

/// Terminal text size, as a stepper rather than buried a screen deeper: on a phone this is the
/// setting people actually reach for, because the same pane that reads fine indoors is unreadable
/// at arm's length on a train.
class _SizeRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) => ValueListenableBuilder(
    valueListenable: terminalFontStore,
    builder: (context, _, _) {
      AppTheme.watch(context);
      final size = terminalFontStore.size;
      return SettingsRow(
        title: 'Size',
        glyph: LucideIcons.aLargeSmall300,
        trailing: SettingsStepper(
          value: size.toStringAsFixed(0),
          // The bounds are the store's own, so a lit + that does nothing is impossible.
          onDecrease: size > TerminalFontStore.minSize
              ? () => unawaited(terminalFontStore.decreaseSize())
              : null,
          onIncrease: size < TerminalFontStore.maxSize
              ? () => unawaited(terminalFontStore.increaseSize())
              : null,
        ),
      );
    },
  );
}

/// The terminal's colour scheme. Beside the face and the size rather than under Appearance, because
/// all three describe the pane a remote program draws into — and [TerminalThemeChoice.matchApp],
/// the default, is precisely the choice to follow Appearance instead.
class _TerminalThemeRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) =>
      ValueListenableBuilder<TerminalThemeChoice>(
        valueListenable: terminalThemeStore,
        builder: (context, choice, _) {
          AppTheme.watch(context);
          // "Same as the app" names a rule; the palette it resolves to names a colour — the
          // terminal's own, which stays dark while Swarm's Theme is chosen, whatever the app wears.
          String label(TerminalThemeChoice option) =>
              option == TerminalThemeChoice.matchApp
              ? AppTheme.terminalPalette.label
              : option.label;
          return SettingsRow(
            title: 'Colors',
            glyph: LucideIcons.palette300,
            value: label(choice),
            onTap: () => showPhoneSheet(
              context,
              title: 'Terminal colors',
              actions: [
                for (final option in TerminalThemeChoice.values)
                  PhoneSheetAction(
                    icon: option == choice
                        ? LucideIcons.check300
                        : LucideIcons.palette300,
                    label: label(option),
                    onTap: () => unawaited(terminalThemeStore.set(option)),
                  ),
              ],
            ),
          );
        },
      );
}

/// The app's palette — the [HarnessPalette] choices the desktop lays out as swatch cards.
///
/// A sheet of names rather than a grid of previews, and the difference is the screen: the desktop's
/// cards each draw a miniature workspace, which needs the width of a settings pane to be legible at
/// all. Shrunk to a phone's column they would be eight indistinguishable rectangles. The app
/// repaints on the tap anyway — [AppearancePrefsStore.setPalette] moves the notifier before it
/// writes — so the preview IS the app behind the sheet, at full size, which no swatch can beat.
///
/// Under Dark and Light captions, because a light palette is the whole of light mode in the
/// terminal's Settings: Swarm asks light or dark instead, with the Theme on its You.
///
/// It names the palette on screen — which Swarm's Theme may have chosen (Paper, under Light) — and
/// a pick here hands light and dark back to the palette ([AppearancePrefsStore.setPalette]).
class _PaletteRow extends StatelessWidget {
  const _PaletteRow({required this.store});

  final AppearancePrefsStore store;

  @override
  Widget build(BuildContext context) => ValueListenableBuilder<AppearancePrefs>(
    valueListenable: store,
    builder: (context, prefs, _) {
      AppTheme.watch(context);
      final shown = AppTheme.palette.value;
      PhoneSheetAction choice(HarnessPalette palette) => PhoneSheetAction(
        icon: palette == shown
            ? LucideIcons.check300
            : LucideIcons.swatchBook300,
        label: palette.label,
        value: palette.description,
        onTap: () => unawaited(store.setPalette(palette)),
      );
      return SettingsRow(
        // "App colors", beside the terminal's own "Colors": both read Graphite by default, and
        // two rows with one value looked like the same setting twice.
        title: 'App colors',
        glyph: LucideIcons.contrast300,
        value: shown.label,
        onTap: () => showPhoneSheet(
          context,
          title: 'App colors',
          sections: [
            for (final (caption, dark) in const [
              ('Dark', true),
              ('Light', false),
            ])
              PhoneSheetSection(
                caption: caption,
                actions: [
                  for (final palette in HarnessPalette.values)
                    if (palette.isDark == dark) choice(palette),
                ],
              ),
          ],
        ),
      );
    },
  );
}

/// The app's own text size — everything that is not the terminal.
class _TextSizeRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) => ValueListenableBuilder(
    valueListenable: appearancePrefsStore,
    builder: (context, prefs, _) {
      AppTheme.watch(context);
      final size = prefs.uiSize;
      return SettingsRow(
        title: 'Text size',
        glyph: LucideIcons.aLargeSmall300,
        trailing: SettingsStepper(
          value: size.toStringAsFixed(0),
          onDecrease: size > AppearancePrefs.uiSizeMin
              ? () => unawaited(appearancePrefsStore.setUiSize(size - 1))
              : null,
          onIncrease: size < AppearancePrefs.uiSizeMax
              ? () => unawaited(appearancePrefsStore.setUiSize(size + 1))
              : null,
        ),
      );
    },
  );
}

/// The version, read from the bundle rather than from `pubspec.yaml` — see [appVersion].
class _VersionRow extends StatelessWidget {
  const _VersionRow();

  @override
  Widget build(BuildContext context) => FutureBuilder<String>(
    future: runningAppVersion(),
    builder: (context, snapshot) {
      AppTheme.watch(context);
      return SettingsRow(title: 'Version', value: snapshot.data ?? '');
    },
  );
}

/// About as one row, as Settings opened from Swarm has it: "About  1.0.12 (80)", the version and
/// the build together — short enough that the build is not lost to an ellipsis, which is why the
/// phone's own look gives it a row of its own ([_BuildRow]). A tap opens a sheet that names them
/// again over the Privacy Policy, the stores' required link (see [kPrivacyPolicyUrl]).
class _AboutRow extends StatefulWidget {
  const _AboutRow();

  @override
  State<_AboutRow> createState() => _AboutRowState();
}

class _AboutRowState extends State<_AboutRow> {
  /// Read once for the row, not once per build: the list rebuilds on every [AppNotifier]
  /// notification, and a new future each time would flash the row empty (see [_BuildRow._info]).
  /// [PackageInfo] keeps what the platform said, so a row built again asks no channel.
  late final Future<String> _label = () async {
    final version = await runningAppVersion();
    final build = (await PackageInfo.fromPlatform()).buildNumber;
    return build.isEmpty ? version : '$version ($build)';
  }();

  @override
  Widget build(BuildContext context) => FutureBuilder<String>(
    future: _label,
    builder: (context, snapshot) {
      AppTheme.watch(context);
      final label = snapshot.data ?? '';
      return SettingsRow(
        key: const ValueKey('settings-about'),
        title: 'About',
        glyph: LucideIcons.info300,
        value: label,
        onTap: () => showPhoneSheet(
          context,
          title: label.isEmpty ? 'Version' : 'Version $label',
          actions: [
            PhoneSheetAction(
              icon: LucideIcons.fileText300,
              label: 'Privacy Policy',
              chevron: true,
              onTap: () => unawaited(openPrivacyPolicy(context)),
            ),
          ],
        ),
      );
    },
  );
}

/// The build behind the version — `buildNumber` from the bundle, and the store's own identifier.
///
/// Version alone is not enough to name a phone build. Two TestFlight builds and two Play internal
/// tracks share one marketing version by design, and a bug report that says "1.0.0" names four
/// binaries. The build number is what the store shows beside a submission and what a crash report
/// is filed against, so it is the one figure support actually asks for — which is why it earns a
/// row rather than being folded into the version's text and lost to its own ellipsis.
///
/// ⚠️ Read through [PackageInfo] rather than [runningAppVersion]: that one deliberately answers only
/// the marketing version, with a Linux `version.txt` branch this platform never takes.
class _BuildRow extends StatelessWidget {
  const _BuildRow();

  /// Resolved ONCE per process, not per build of this row.
  ///
  /// [PackageInfo.fromPlatform] is a platform-channel round trip, and the settings list rebuilds on
  /// every [AppNotifier] notification — a socket frame, an agent's state change. A future created
  /// inline would fire one channel call per frame and flash the em dash back in each time while it
  /// resolved. The answer cannot change while the process lives, so caching it is exact rather than
  /// merely cheap.
  static final Future<PackageInfo> _info = PackageInfo.fromPlatform();

  @override
  Widget build(BuildContext context) => FutureBuilder<PackageInfo>(
    future: _info,
    builder: (context, snapshot) {
      AppTheme.watch(context);
      final info = snapshot.data;
      // Empty on Linux/desktop dev builds, where nothing stamps it: the row says nothing rather
      // than a dash.
      final build = info?.buildNumber ?? '';
      return SettingsRow(title: 'Build', value: build);
    },
  );
}