Files
buzz/mobile/test/features/onboarding/hosted_communities_test.dart
klopez4212 a82d596fc2 mobile: show account communities in the switcher and sync saved destinations (#9262)
## Summary

Switch Community currently shows only device-saved communities, leaving
account destinations behind a separate Find step. It now merges saved
communities with supported account destinations directly, keeps Add
Community, and removes the redundant Find action from that Add route.
Initial onboarding and identity recovery keep their discovery entry.
Find lists supported account addresses before hosted identity setup;
hosted selection still performs binding, backup, and admission, while
external selection opens the existing identity flow.

Mobile also saves QR/address additions and explicit removals through
Builder Lab's existing known-communities account APIs. A per-account
local journal retries transient failures, survives restarts, pauses in
the background, and fences requests against account changes. External
secure addresses use the existing self-hosted entry flow; account
destinations never imply membership or bypass admission. Remote list
omissions do not delete local identities.

Explicit additions store an account owner and revision atomically with
local credentials. Legacy/unclaimed destinations remain local-only until
explicitly added while signed in; signing into another account never
claims retained destinations. Restart reconciliation lets a committed
re-add supersede an older removal even if the retry-journal write
failed. Local deletion and its credential-free account-removal intent
commit in one storage write, independent of the account-only retry
journal. Removing one of several local identities owned by the same
account at an address retains its account destination until that
account’s last identity is removed. Another account’s saved identity
does not block removal or lose its credentials during recovery. Offline
edits retain the stored account subject without treating it as network
authorization. Discovery-only intent survives browser callbacks, app
restart, and retry. Onboarding recovery controls have a Material
ancestor in the actual route. Pending status is fenced to the current
subject; interrupted older removals offer explicit local completion, and
denied requests offer browser reauthentication. Same-host ports have
distinct labels and confirmations, and unsupported hosted ports are
excluded.

This changes the mobile client and its public-build CI test list only:
no relay endpoints, events, migrations, or backend deployment.

### Related issue

No duplicate found among open known-communities/switcher issues and PRs.
Related picker editing work: #6632 (renaming communities).

### Testing

Validated after merging main (`02535e1b53`) at
`c4ee037f7e710962f176540abf88d26e98c2823c`. Wes’s follow-up fixes cover
push-revocation commit ordering, same-account removal confirmation, and
recovery after completed hosted admission. The merge also preserves
main’s toolbar and session protections; a test override now accepts the
updated relay subscription parameter.

- Formatting, static analysis, and differential file-size checks pass.
- Prior full CI and security review passed on `3adb117aae`; security
checks also passed on `cf3836ecb`. Fresh CI and security review are
required for this head.
- Mutation checks fail when either the initiating-account removal guard
or the rendered-status subject fence is removed; both guards were
restored before final validation.
- CI explicitly runs the public-only account discovery and
synchronization journeys.
- Added journeys cover paused removal across A→B, offline restart,
journal read/write failures, duplicate local identities in either
removal order, delayed status reads across accounts, real browser
handoff after denial, unbound external discovery, and local same-host
port removal.
- Earlier journeys cover pairing acknowledgement and restart after
journal-write failure, same-subject setup completion, offline/rejected
removal with reopen/retry, and fresh external-only/mixed account entry.
- Regression coverage includes discovery deduplication and retry, hosted
and external selection, Add without Find, account-only removal, shared
authentication/removal persistence, restart recovery, latest-intent
ordering, account changes, and retry pause/resume.
- `just mobile-check`, `just file-size-check`, and `just mobile-test`:
4,954 default-build tests passed (71 skipped), plus 27 crypto-package
tests.
- Full public-account suite: 5,012 passed, 12 skipped, one pre-existing
failure in `fullscreen_onboarding_test.dart` ("Home stays hidden until
community choice and admission"). The same assertion was reproduced on
clean base `8cce12f591`: expected both communities imported, actual only
the selected community.
- Follow-up regression journeys cover both A/B same-address removal
orderings, recovery preserving B’s saved key, the production onboarding
widget composition, and retained discovery intent with callback/retry
plus normal-sign-in controls.
- Native/live-account and human testing remain outstanding. The tests
use fake network/storage boundaries; live account API behavior,
cross-device synchronization, native accessibility, and
timeout/late-server-commit ordering still require integration
verification.

- The three expanded recovery/removal journeys pass and each fails when
the corresponding fix is removed. A durably journaled revocation now
finishes the confirmed removal even if the account changes during
journaling; pre-journal account mismatches still abort. Confirmation
copy counts only same-account identities. Explicit account recovery
retires a completed join target while preserving in-progress targets.

### Preview

Sample-data Flutter widget renders: saved-only and combined lists. These
illustrate the picker layout, not a device session or live account sync.

| Saved-only | Combined |
| --- | --- |
| ![Saved-only
picker](https://github.com/user-attachments/assets/eeadbd28-5ef0-4bc1-a381-8fdf71563144)
| ![Combined
picker](https://github.com/user-attachments/assets/58080884-82c2-4538-8d9d-54eb95218d81)
|

### Manual verification

1. Sign into a public account with a community saved on another device.
Open Switch Community; verify it appears alongside local choices and
Add.
2. Select a hosted and an external community; verify the existing
identity/admission flow opens. Add should not offer Find again.
3. Add a community by QR/address, then check the account list on
desktop. Remove it on mobile and verify the account entry disappears
while other devices retain their local credentials.
4. Repeat removal offline, restart, then reconnect/resume. Verify the
queued removal reaches the account service without switching identities.
5. On a fresh device, verify external-only and mixed account lists offer
external entry. Check two ports on the same host remain distinguishable.
6. Sign out of account A and into B; retained A destinations must not
upload to B. Explicitly add a B destination and verify it syncs.
7. Reject or interrupt account removal; verify visible pending/failure
status. A denied session must open browser sign-in through “Sign in
again” and retry after exchange; setup-required accounts retain their
setup action.
8. Keep two local identities owned by the same account at one address;
removing the first must keep the account entry, and removing the last
must queue account removal. Repeat with A and B at that address;
removing A must preserve B’s saved credentials and still sync A’s
removal.
9. Restart offline with a stored account, add/remove an external
community, then reconnect as the same account and verify convergence.
Explicit sign-out must not claim new local-only entries.


10. Start Find my communities, restart during browser authentication,
then return or retry. External destinations must appear before hosted
identity setup; normal sign-in must retain its identity checks.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-15 15:07:56 -08:00

410 lines
17 KiB
Dart

import 'package:buzz/shared/community/community_grid_option.dart';
import 'dart:ui' as ui;
import 'package:buzz/shared/hosted/hosted_community_creation.dart';
import 'package:buzz/shared/hosted/hosted_environment.dart';
import 'package:buzz/features/onboarding/hosted_connect_page.dart';
import 'package:buzz/hosted_app_gate.dart';
import 'package:buzz/shared/hosted/hosted_flow_provider.dart';
import 'package:buzz/onboarding_app_entry.dart';
import 'package:buzz/shared/deeplink/pending_deep_link_provider.dart';
import 'package:buzz/shared/hosted/hosted_flow.dart';
import 'package:buzz/shared/hosted/builderlab_account.dart';
import 'package:buzz/shared/hosted/hosted_community_connection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../helpers/hosted_communities_fixture.dart';
import '../../helpers/widget_helpers.dart';
void main() {
testWidgets(
'cancel sign-in and resolve batch conflicts without replacing saved identities',
(tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
// Keep secure-storage operations in the same test zone.
for (final reduced in [false, true]) {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(320, 640);
FlutterSecureStorage.setMockInitialValues({});
PendingDeepLinkNotifier.debugUriStreamOverride =
const Stream<Uri>.empty();
final f = HostedCommunitiesFixture();
await f.initialize(widget: true);
f.expired = true;
await tester.pumpWidget(
WidgetHelpers.testable(
disableAnimations: reduced,
child: const HostedAppGate(
authenticated: false,
child: OnboardingAppEntry(),
),
overrides: [hostedFlowProvider.overrideWithValue(f.flow)],
),
);
await pumpUntilVisible(tester, find.bySemanticsLabel('Buzz'));
await revealOptionsWithSemantics(tester);
await tester.pump();
tester.view.physicalSize = const Size(420, 900);
await tester.pump();
final linkCard = find.ancestor(
of: find.text('Enter a community link').hitTestable(),
matching: find.byType(InkWell),
);
expect(tester.getBottomRight(linkCard).dy, closeTo(876, 1));
final scanCard = find.ancestor(
of: find.text('Use a pairing code').hitTestable(),
matching: find.byType(InkWell),
);
final subtitle = find
.text('Enter a community link or use a pairing code to continue.')
.hitTestable();
expect(
tester.getTopLeft(scanCard).dy - tester.getBottomLeft(subtitle).dy,
// The transitioning heading reserves the taller of both text blocks.
greaterThanOrEqualTo(24),
);
tester.view.physicalSize = const Size(320, 640);
await tester.pump();
final optionTop = tester
.getTopLeft(find.text('Enter a community link').hitTestable())
.dy;
final scanTop = tester.getTopLeft(scanCard).dy;
await tester.tap(find.text('Enter a community link').hitTestable());
await tester.pump();
await tester.pump(const Duration(milliseconds: 30));
if (!reduced) {
// Keyboard setup must finish before any heading/surface movement.
expect(
tester
.getTopLeft(find.byKey(const Key('connection-options-motion')))
.dy,
scanTop,
);
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
'buzz/community_keyboard',
const StandardMethodCodec().encodeMethodCall(
const MethodCall('willShow'),
),
(_) {},
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 30));
final scanLayer = find.byKey(const Key('connection-options-motion'));
expect(tester.getTopLeft(scanLayer).dy, greaterThan(scanTop));
final formOpacity = tester.widget<Opacity>(
find
.descendant(
of: find.byKey(const Key('community-form-motion')),
matching: find.byType(Opacity),
)
.first,
);
expect(formOpacity.opacity, greaterThan(0));
final surface = find.byWidgetPredicate(
(widget) => widget is LayoutId && widget.id == 'surface',
);
final action = find.byWidgetPredicate(
(widget) => widget is LayoutId && widget.id == 'action',
);
expect(tester.getRect(surface), tester.getRect(action));
}
await tester.pump(const Duration(milliseconds: 50));
await tester.binding.handlePopRoute();
await pumpUntilVisible(tester, find.text('Use a pairing code'));
expect(tester.testTextInput.isVisible, isFalse);
expect(find.text('Use a pairing code').hitTestable(), findsOneWidget);
await tester.tap(find.text('Enter a community link').hitTestable());
await tester.pump();
// A hardware keyboard produces no software-keyboard notification.
await tester.pump(const Duration(milliseconds: 350));
await tester.pumpAndSettle();
expect(
tester
.getTopLeft(find.text('Enter a community link').hitTestable())
.dy,
lessThan(optionTop - 100),
);
expect(tester.testTextInput.isVisible, isTrue);
tester.view.viewInsets = const FakeViewPadding(bottom: 300);
await tester.pumpAndSettle();
final field = find.byKey(const Key('community-link-input'));
await tester.ensureVisible(field);
expect(field.hitTestable(), findsOneWidget);
expect(
tester
.widget<EditableText>(
find.descendant(of: field, matching: find.byType(EditableText)),
)
.focusNode
.hasFocus,
isTrue,
);
expect(tester.takeException(), isNull);
tester.view.viewInsets = const FakeViewPadding();
await tester.binding.handlePopRoute();
await pumpUntilVisible(tester, find.text('Use a pairing code'));
expect(tester.testTextInput.isVisible, isFalse);
expect(find.text('Use pairing code'), findsNothing);
await tester.tap(find.text('Use a pairing code').hitTestable());
await tester.pumpAndSettle();
expect(
find
.text('Paste the pairing code from your desktop app.')
.hitTestable(),
findsOneWidget,
);
await tester.tap(find.text('Back').hitTestable());
await pumpUntilVisible(tester, find.text('or sign in with email'));
expect(
find.text('or sign in with email').hitTestable(),
findsOneWidget,
);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpAndSettle();
await f.dispose();
tester.view.reset();
}
debugDefaultTargetPlatformOverride = null;
await tester.binding.setSurfaceSize(const Size(440, 956));
addTearDown(() => tester.binding.setSurfaceSize(null));
// Keep the process-wide secure-store queue in one widget-test zone.
{
FlutterSecureStorage.setMockInitialValues({});
PendingDeepLinkNotifier.debugUriStreamOverride =
const Stream<Uri>.empty();
final f = HostedCommunitiesFixture();
await f.initialize(widget: true);
f.rows = [f.row('one'), f.row('two')];
f.expired = true;
addTearDown(() async {
PendingDeepLinkNotifier.debugUriStreamOverride = null;
await f.dispose();
});
await tester.pumpWidget(
WidgetHelpers.testable(
disableAnimations: true,
child: const HostedAppGate(
authenticated: false,
child: OnboardingAppEntry(),
),
overrides: [hostedFlowProvider.overrideWithValue(f.flow)],
),
);
await tester.pumpAndSettle();
expect(find.text('Scan a QR code').hitTestable(), findsOneWidget);
expect(find.text('Enter a community link').hitTestable(), findsNothing);
expect(find.text('Sign in with email').hitTestable(), findsNothing);
expect(find.text('Use pairing code'), findsNothing);
await revealOptions(tester);
await tester.pumpAndSettle();
expect(
find.text('Enter a community link').hitTestable(),
findsOneWidget,
);
expect(find.text('Use a pairing code').hitTestable(), findsOneWidget);
expect(find.text('Use pairing code').hitTestable(), findsNothing);
await tester.tap(find.byType(BackButton));
await tester.pumpAndSettle();
expect(find.text('Enter a community link').hitTestable(), findsNothing);
await revealOptions(tester);
await tester.pumpAndSettle();
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(
find.text('or sign in with email').hitTestable(),
findsOneWidget,
);
expect(find.text('Enter a community link').hitTestable(), findsNothing);
await tester.tap(find.text('or sign in with email').hitTestable());
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(f.browser.startedIntent, {'type': 'account'});
expect(
find.bySemanticsLabel('Cancel sign-in').hitTestable(),
findsOneWidget,
);
await tester.tap(find.bySemanticsLabel('Cancel sign-in').hitTestable());
await tester.pumpAndSettle();
expect(find.text('Scan a QR code').hitTestable(), findsOneWidget);
// Target sign-in remains pending when an Android Custom Tab closes.
await f.flow.start(HostedCreateCommunity('new-community'));
await tester.pumpAndSettle();
expect(f.flow.accountOnly, isFalse);
expect(f.flow.stage, HostedFlowStage.signIn);
expect(find.text('Cancel sign-in').hitTestable(), findsOneWidget);
expect(find.text('Scan a QR code').hitTestable(), findsNothing);
await tester.tap(find.text('Cancel sign-in').hitTestable());
await tester.pumpAndSettle();
expect(f.flow.stage, HostedFlowStage.idle);
expect(find.text('Scan a QR code').hitTestable(), findsOneWidget);
f.expired = false;
await f.flow.signInAccount(openBrowser: false);
await tester.pumpAndSettle();
f.expired = true;
await tester.tap(find.text('Find my communities'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(f.flow.stage, HostedFlowStage.signIn);
expect(f.browser.startedIntent, {
'type': 'account',
'discover_only': 'true',
});
expect(find.byType(HostedConnectPage), findsNothing);
expect(
find.bySemanticsLabel('Cancel sign-in').hitTestable(),
findsOneWidget,
);
expect(find.text('Enter a community link').hitTestable(), findsNothing);
f.expired = false;
await tester.tap(find.bySemanticsLabel('Cancel sign-in').hitTestable());
await tester.pumpAndSettle();
expect(f.flow.stage, HostedFlowStage.idle);
await tester.pumpAndSettle();
expect(find.text('Find my communities'), findsOneWidget);
expect(find.byType(HostedConnectPage), findsNothing);
await tester.tap(find.text('Find my communities'));
await tester.pumpAndSettle();
expect(f.flow.stage, HostedFlowStage.chooseCommunities);
expect(find.byType(CommunityGridOption), findsWidgets);
await tester.tap(find.byType(CommunityGridOption).first);
await tester.pumpAndSettle();
expect(find.byType(CommunityGridOption), findsNothing);
expect(f.admitted, ['one.communities.buzz.xyz']);
expect(find.byType(HostedConnectPage), findsNothing);
f.admitted.clear();
f.beforeAdmission = (name) async {
if (name == 'two.communities.buzz.xyz') {
throw const SavedCommunityIdentityConflict();
}
};
await tester.tap(find.text('Find my communities'));
await tester.pumpAndSettle();
expect(f.flow.stage, HostedFlowStage.chooseCommunities);
expect(find.byType(CommunityGridOption), findsWidgets);
await tester.tap(find.byType(CommunityGridOption).last);
await tester.pumpAndSettle();
expect(find.text('Keep saved identity and skip'), findsOneWidget);
expect(find.text('1 community added and kept.'), findsNothing);
await tester.tap(find.text('Keep saved identity and skip'));
await tester.pumpAndSettle();
expect(f.admitted, isEmpty);
expect(find.byType(HostedConnectPage), findsNothing);
f.admitted.clear();
f.beforeAdmission = (name) async {
if (name == 'two.communities.buzz.xyz') throw AccountFailure.rejected;
};
await tester.tap(find.text('Find my communities'));
await tester.pumpAndSettle();
expect(f.flow.stage, HostedFlowStage.chooseCommunities);
expect(find.byType(CommunityGridOption), findsWidgets);
await tester.tap(find.byType(CommunityGridOption).last);
await tester.pumpAndSettle();
expect(find.text('1 community added and kept.'), findsNothing);
expect(find.text('Try again').hitTestable(), findsNothing);
expect(find.text('Skip this community').hitTestable(), findsOneWidget);
await tester.tap(find.text('Back to choices'));
await tester.pumpAndSettle();
expect(find.byType(CommunityGridOption), findsNWidgets(2));
expect(
find.descendant(
of: find.byType(CommunityGridOption),
matching: find.text('two'),
),
findsWidgets,
);
await tester.tap(find.byType(CommunityGridOption).last);
await tester.pumpAndSettle();
await tester.tap(find.text('Skip this community'));
await tester.pumpAndSettle();
expect(f.admitted, isEmpty);
expect(f.openedCommunity, 'wss://one.communities.buzz.xyz');
expect(find.byType(HostedConnectPage), findsNothing);
}
},
skip: HostedEnvironment.authDomains.isEmpty,
);
}
Future<void> revealOptions(WidgetTester tester) async {
// Ordinary double taps must not expose the hidden connection options.
await tester.tapAt(const Offset(24, 120));
await tester.pump(const Duration(milliseconds: 50));
await tester.tapAt(const Offset(24, 120));
await tester.pumpAndSettle();
expect(find.text('Use a pairing code').hitTestable(), findsNothing);
for (var tap = 0; tap < 2; tap++) {
final first = await tester.createGesture(pointer: 11);
final second = await tester.createGesture(pointer: 12);
await first.down(
const Offset(24, 120),
timeStamp: Duration(milliseconds: tap * 70),
);
await second.down(
const Offset(70, 120),
timeStamp: Duration(milliseconds: tap * 70),
);
await tester.pump(const Duration(milliseconds: 20));
await first.up(timeStamp: Duration(milliseconds: tap * 70 + 20));
await second.up(timeStamp: Duration(milliseconds: tap * 70 + 20));
await tester.pump(const Duration(milliseconds: 50));
}
}
Future<void> revealOptionsWithSemantics(WidgetTester tester) async {
final handle = tester.ensureSemantics();
try {
await tester.pump();
final wordmark = tester.getSemantics(find.bySemanticsLabel('Buzz'));
final data = wordmark.getSemanticsData();
final actionIds = data.customSemanticsActionIds!;
expect(actionIds, hasLength(1));
expect(
CustomSemanticsAction.getAction(actionIds.single)!.label,
'More connection options',
);
// The action belongs to the wordmark, never an unlabelled page-sized stop.
expect(data.label, 'Buzz');
expect(wordmark.rect.height, lessThan(200));
wordmark.owner!.performAction(
wordmark.id,
ui.SemanticsAction.customAction,
actionIds.single,
);
await pumpUntilVisible(tester, find.text('Use a pairing code'));
expect(find.text('Enter a community link').hitTestable(), findsOneWidget);
expect(find.text('Use a pairing code').hitTestable(), findsOneWidget);
} finally {
handle.dispose();
}
}
// The welcome bees intentionally never settle. Wait for the requested control
// and its ancestor fades to finish instead of waiting for every app animation.
Future<void> pumpUntilVisible(WidgetTester tester, Finder target) async {
bool visible() {
final hit = target.hitTestable();
if (hit.evaluate().length != 1) return false;
return tester
.widgetList<Opacity>(
find.ancestor(of: hit, matching: find.byType(Opacity)),
)
.every((opacity) => opacity.opacity == 1);
}
for (var frame = 0; frame < 120; frame++) {
await tester.pump(const Duration(milliseconds: 16));
if (visible()) return;
}
expect(target.hitTestable(), findsOneWidget);
expect(visible(), isTrue, reason: 'The control must finish fading in');
}