Android Multiprofile android-multiprofile

Gives guidance on multiprofile pitfalls, gotchas, and established solutions.

Use it when you are refactoring Chrome for Android to support multiple profiles, removing `getLastUsedRegularProfile()`, scoping `SharedPreferences` or `ProfileKeyedMap` / `ProfileTokenUtils`, or changing how a feature interacts with profiles.

Works in Claude, ChatGPT, Codex and more
Our test
—
not tested yet
GitHub stars
26k
chromium/chromium
Added by
0
members
Updated
Dec 6
commit 8cf236c
Content
1 file
no scripts · 13 KB
License
BSD 3-Clause
free to use

What our test found

Not tested yet. Our model tries every skill on a realistic request and scores the result, the most popular skills first. Until then, the safety checks on the right still apply.

View on GitHub ↗
name: android-multiprofile
description: >-
  Gives guidance on multiprofile pitfalls, gotchas, and established solutions.
  Use whenever you are refactoring Chrome for Android to support multiple
  profiles, removing `getLastUsedRegularProfile()`, scoping `SharedPreferences`
  or `ProfileKeyedMap` / `ProfileTokenUtils`, or changing how a feature
  interacts with profiles.

Chrome for Android Multiprofile Guide

Clank has been long assuming that only 1 global profile exists in the browser. We now aim to support multiple profiles, and expect to see significant refactoring of existing code to support this.

Desktop shared code already supports multiple profiles; prefer removing #if !BUILDFLAG(IS_ANDROID) guards over inventing Android-only paths. Clank's issues live in Android-specific Java/C++ glue built around pre-native UI startup, one regular profile (Default), one primary Incognito profile, and APK-wide OS APIs.

Use Established Solutions

  • Tab / page code: tab.getProfile() or Profile.fromWebContents(webContents).
  • Window / Activity UI: Observe a Profile supplier (TabModelSelectorProfileSupplier for active regular/OTR switches, or a MonotonicObservableSupplier<Profile> / NullableObservableSupplier<Profile>); store a direct Profile field only when post-native and destroyed before the profile. ActivityProfileProvider (OneshotSupplier<ProfileProvider>) resolves the activity's profile from its intent token (failing closed if invalid; falling back to getLastUsedRegularProfile() only when no token is present), without tracking regular/OTR switches — mark any still-missing upstream routing with TODO(crbug.com/40254448).
  • Java-owned per-profile state (`ProfileKeyedMap`): Use static final ProfileKeyedMap<T> (createMapOfDestroyables()). Set ProfileSelection.REDIRECTED_TO_ORIGINAL (shared with OTR) vs. default OWN_INSTANCE on the map instead of manually calling getOriginalProfile(). Use ProfileKeyedMap<Boolean> to replace static boolean sInitialized.
  • C++ `KeyedService` & JNI bridges: Pass @JniType("Profile*") Profile across JNI (FooFactory.getForProfile(profile)) and delete C++ ambient calls (GetLastUsedProfile*, GetActiveUserProfile, GetPrimaryUserProfile, GetLastUsedRegularProfileKey). Do not wrap stateless shims in ProfileKeyedMap; for stateful wrappers around a C++ KeyedService, prefer C++ owning a ScopedJavaGlobalRef and destroying it in Shutdown().
  • Internal Intents: Use ProfileTokenUtils (addProfileToIntent, resolveProfileToken, retrieveProfileFromIntent, getNotificationTag) to encode which profile to use.
  • Preferences: Prefer UserPrefs.get(profile) (PrefService) for per-profile prefs (sync, policy, OTR, and deletion work automatically) unless accessed off the UI thread or before native; otherwise use ProfileSharedPreferences.get(profile) / getSideStore(profile, baseFileName). Keep ChromeSharedPreferences.getInstance() and ChromeSharedPreferences.getSideStore(fileName) strictly for device/app-wide state. Never bypass via ContextUtils.getAppSharedPreferences(), direct context.getSharedPreferences(name, ...), or //base's SharedPreferencesManager directly.
  • Disk / cache paths: Key by profile.getBaseName() ("Default", "Profile 1"). Note chrome::GetUserCacheDirectory() maps "Default" to bare Context.getCacheDir() and secondary profiles to getCacheDir()/<baseName>.
  • Before native is initialized:
  • Defer via supplier (preferred): Hold the Activity's OneshotSupplier<ProfileProvider> and run work once populated post-native.
  • Java state: PreNativeProfileKeyedMap<T> (pass factory and Destroyable::destroy cleanup to the constructor; acts as a single factory.apply(null) instance when AndroidMultiprofile is disabled. When enabled, getForProfile(null) keys one instance to getLastUsedProfileBaseName() and throws IllegalStateException once ProfileManager.isInitialized() — re-fetch with a non-null Profile post-native since it is destroyed if the base name was null or mismatched).
  • Preferences: ProfileSharedPreferences.forProfileDir(profileDirName) (or getSideStoreForProfileDir(profileDirName, baseFileName) for side stores; pass "Default" if getLastUsedProfileBaseName() is null).
  • Tokens & notifications: ProfileTokenUtils.parseProfileToken() and getNotificationTagFromIntent() work pre-native (e.g. to inspect tokens or dismiss a notification from a cold BroadcastReceiver).
  • Enumerating profiles: C++ ProfileAttributesStorage covers unloaded profiles (ProfileManager.getLoadedProfiles() returns only loaded regular profiles; Java ProfileAttributesStorage.get() currently exposes public primary-account lookups and observers, skipping signed-out/omitted profiles).

Non-Obvious Pitfalls

  • Startup, recreation, and Activity reuse:
  • AsyncInitializationActivity gates onStartWithNative, onResumeWithNative, and finishNativeInitialization on ProfileProvider.
  • In SynchronousInitializationActivity, async profile load runs after super.onCreate() (including restored Fragments/DialogFragments), onStart(), and onResume().
  • Note when Intents are rewritten/replaced, preserve their token with ProfileTokenUtils.copyProfileToken(from, to). Recents/process-death/config-change recreation can strip or rewrite launch intent extras (IntentHandler.rewriteFromHistoryIntent, sClearIntentWhenRecreated, Settings-in-tab recreation); do not assume launch extras survive.
  • singleTop/singleTask/singleInstance/singleInstancePerTask activities receive onNewIntent() — route to the profile's window, recreate, or reject (don't rebind a live window to a different profile).
  • Profile teardown & UAF:
  • ProfileManager.Observer.onProfileAdded fires only for regular profiles, while onProfileDestroyed fires for both regular and OTR profiles.
  • Teardown runs: onProfileWillBeDestroyed (shutdownStarted() == true, onProfileDestroyed + ProfileKeyedMap cleanup while native Profile* is live) → OTR teardown → KeyedService shutdown → onNativeDestroyed.
  • Never call sProfileMap.destroy() from a per-window destroy(). Supply a cleanup action to unregister global observers and clear ObserverLists, and null-check optional services before getForProfile (factories must return non-null).
  • Java-owned C++ bridges holding raw_ptr<KeyedService> or ScopedObservation must tear down via ProfileKeyedMap or ProfileObserver::OnProfileWillBeDestroyed, not GC or Activity.onDestroy (see send_tab_to_self_android_bridge.cc).
  • Do not oneshot-read observable Profile suppliers; re-check active profile, shutdownStarted(), and isFinishing() in async callbacks.
  • Implicit contamination in "already per-profile" features:
  • Features reading UserPrefs or TrackerFactory.getTrackerForProfile() still leak when they cache values in static fields/maps, gate on a global pref (e.g. first-launch timestamps) or counter (skewing UMA/Finch), or write cached SharedPreferences back into synced UserPrefs.
  • Scoping files does not scope static in-memory caches over them, nor startup GC tasks that purge unopened windows belonging to unloaded profiles.
  • AndroidX Preference widgets auto-persist their android:key into default global SharedPreferences unless persistence is disabled or backed by a PreferenceDataStore.
  • `ProfileTokenUtils` subtleties:
  • addProfileToIntent is post-native only, requires an explicit self component/package already set on the Intent (for addTrustedIntentExtras), and sets intent.setIdentifier(token) so PendingIntents don't overwrite across profiles. It asserts getIdentifier() == null — don't pre-set one or call twice; use requestCode for within-profile uniqueness.
  • retrieveProfileFromIntent runs its callback with `null` if a failure occurs - never fall back to getLastUsedRegularProfile().
  • Encoded tokens persist in OS PendingIntents and notification tags; keep ProfileToken wire-compatible. When migrating to getNotificationTag, cancel legacy untagged notifications only for !profile.isOffTheRecord() && profile.isInitialProfile().
  • Multiple Incognito profiles exist: Each regular Profile has its own primary OTR profile (and custom OTRs can also exist). Use IncognitoTabHostUtils.doIncognitoTabsExistForProfile(otrProfile) / isIncognitoTabModelActive(otrProfile) for profile-scoped queries.
  • OtrProfileId is only unique within its owning regular Profile (every regular profile shares OtrProfileId.getPrimaryOtrProfileId()); compare Profile instances, not OtrProfileId or isOffTheRecord().
  • Do not conflate isOffTheRecord() with isIncognitoBranded() (Ephemeral CCT and enterprise isolated profiles are OTR without Incognito UI).

Easily Missed Android Surfaces

  • Activity / window / tab lookups: ApplicationStatus.getLastTrackedFocusedActivity() / getRunningActivities(), MultiWindowUtils.getLastAccessedWindowId(), and TabWindowManager iterators span all profiles (plus CCT/Incognito/PiP); use TabWindowManagerSingleton.getForProfile(profile) (ProfileTabWindowLookup) for profile-scoped tab/window queries.
  • `BackgroundTaskScheduler` / `JobScheduler`: Static TaskIds map 1:1 to APK-global job IDs — scheduling or canceling for Profile B overwrites/cancels Profile A even with PersistableBundle extras. Prefer a single dispatcher job that fans out across profiles or schedules the earliest deadline from per-profile state.
  • `Service`s, `BroadcastReceiver`s, `ContentProvider`s: One instance per APK UID, often cold/pre-native (foreground services, DownloadManagerService, 3P autofill ContentProvider).
  • OS, AndroidX & GMSCore APK-wide state: Notification channels, PackageManager component toggles (watch cleanup wiping shared state), AppCompatDelegate global night mode, OS donors (AppSearch, Assist, Digital Wellbeing, Backup), OS Settings endpoints, and app-scoped AndroidX/GMSCore APIs (Cast, GCMDriver / InstanceID subtypes, CredMan/UPM/WebAuthn).
  • Identity, enterprise & consents: AccountManagerFacade exposes all OS-user accounts and Android uses kMirror cookie reconciliation. Do not auto-delete profile dirs on OS account removal or equate a managed Chrome profile with an Android Work Profile. Confirm install-wide vs. per-profile scope for consents and ambiguous UX with product/owners.

Flags & Testing

We plan to define critical multiprofile behavior in Public Transit tests that are landed disabled, with the goal to re-enable these tests when we fix the underlying issue. Never forget to remove the @DisabledTest(message = "https://crbug.com/40254448") when you expect to fix the underlying issue. If adding new critical behavior, codify it in a new test, but not all bug fixes or tiny changes need this level of coverage.

  • Feature flag (off by default, including in tests): ChromeFeatureList.sAndroidMultiprofile / ChromeFeatureList.ANDROID_MULTIPROFILE / chrome::android::kAndroidMultiprofile (prefer profiles::IsMultipleProfilesEnabled() in C++) gates multi-profile creation, startup, and account filtering.
  • Avoid single `@Mock Profile` false confidence: ProfileManager.setLastUsedProfileForTesting(), Profile.setProfileFromWebContentsForTesting(), and single-slot UserPrefs.setPrefServiceForTesting() / FooFactory.setInstanceForTesting() hide wrong-profile bugs, while mock getOriginalProfile() and getBaseName() return null.
  • Test types
  • Manual testing: Launch with --enable-features=AndroidMultiprofile --profile-directory=<name> to start in (or create) a profile, and check chrome://version (Profile Path) to verify which profile a window is using.
  • Preferred: Java instrumentation tests (Public Transit): Follow MultiProfileWindowTest under chrome/android/javatests/.../profiles/ (@DoNotBatch, @MinAndroidSdkLevel(VERSION_CODES.S), @Restriction(DeviceRestriction.RESTRICTION_TYPE_NON_AUTO), ANDROID_MULTIPROFILE, station.getOriginalProfile(), openNewWindowInNewProfileFast(name), and BasePageStation.Builder#inNewWindow(profile)). Beware legacy helpers (SigninTestRule, SigninTestUtil, SyncTestUtil, BookmarkTestUtil) that call getLastUsedRegularProfile().
  • Robolectric (Java unit tests): Use two real profiles — TestProfile.createRegular("Default") and TestProfile.createRegular("Profile 1") (plus TestProfile.createIncognito(testProfile)), TestProfileProvider, and FakeProfileAttributesStorage.
  • C++ `unit_tests`: Call TestingProfileManager::SetUp() and CreateTestingProfile(...) to test with multiple TestingProfile instances.
  • C++ `android_browsertests`: Enable chrome::android::kAndroidMultiprofile and use profiles::testing::CreateProfileSync() (or GenerateNextProfileDirectoryPath() / CreateMultiProfileAsync()).