⚠ This page is served via a proxy. Original site: https://github.com
This service does not collect credentials or authentication data.
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
/packages/eip-5792-middleware @MetaMask/wallet-integrations

## Core Platform Team
/packages/ui-state-controller @MetaMask/core-platform
Copy link
Contributor

@mcmire mcmire Feb 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are your thoughts on putting this controller under the ownership of Extension Platform and Mobile Platform? Our team already own a lot of things we shouldn't, and it doesn't fit with the goals of our team, it seems like something that's more feature-oriented. This controller also feels like something these teams need to be in the loop on, as the logic for tracking the state of the UI is dependent on the platform.

Suggested change
/packages/ui-state-controller @MetaMask/core-platform
/packages/ui-state-controller @MetaMask/extension-platform @MetaMask/mobile-platform

/packages/base-controller @MetaMask/core-platform
/packages/build-utils @MetaMask/core-platform
/packages/composable-controller @MetaMask/core-platform
Expand Down
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ Each package in this repository has its own README where you can find installati
- [`@metamask/subscription-controller`](packages/subscription-controller)
- [`@metamask/transaction-controller`](packages/transaction-controller)
- [`@metamask/transaction-pay-controller`](packages/transaction-pay-controller)
- [`@metamask/ui-state-controller`](packages/ui-state-controller)
- [`@metamask/user-operation-controller`](packages/user-operation-controller)

<!-- end package list -->
Expand Down Expand Up @@ -166,6 +167,7 @@ linkStyle default opacity:0.5
subscription_controller(["@metamask/subscription-controller"]);
transaction_controller(["@metamask/transaction-controller"]);
transaction_pay_controller(["@metamask/transaction-pay-controller"]);
ui_state_controller(["@metamask/ui-state-controller"]);
user_operation_controller(["@metamask/user-operation-controller"]);
account_tree_controller --> accounts_controller;
account_tree_controller --> base_controller;
Expand All @@ -181,16 +183,29 @@ linkStyle default opacity:0.5
address_book_controller --> base_controller;
address_book_controller --> controller_utils;
address_book_controller --> messenger;
ai_controllers --> base_controller;
ai_controllers --> messenger;
analytics_controller --> base_controller;
analytics_controller --> messenger;
analytics_data_regulation_controller --> base_controller;
analytics_data_regulation_controller --> controller_utils;
analytics_data_regulation_controller --> messenger;
announcement_controller --> base_controller;
announcement_controller --> messenger;
app_metadata_controller --> base_controller;
app_metadata_controller --> messenger;
approval_controller --> base_controller;
approval_controller --> messenger;
assets_controller --> account_tree_controller;
assets_controller --> base_controller;
assets_controller --> controller_utils;
assets_controller --> core_backend;
assets_controller --> keyring_controller;
assets_controller --> messenger;
assets_controller --> network_controller;
assets_controller --> network_enablement_controller;
assets_controller --> permission_controller;
assets_controller --> polling_controller;
assets_controllers --> account_tree_controller;
assets_controllers --> accounts_controller;
assets_controllers --> approval_controller;
Expand All @@ -201,11 +216,13 @@ linkStyle default opacity:0.5
assets_controllers --> messenger;
assets_controllers --> multichain_account_service;
assets_controllers --> network_controller;
assets_controllers --> network_enablement_controller;
assets_controllers --> permission_controller;
assets_controllers --> phishing_controller;
assets_controllers --> polling_controller;
assets_controllers --> preferences_controller;
assets_controllers --> profile_sync_controller;
assets_controllers --> storage_service;
assets_controllers --> transaction_controller;
base_controller --> messenger;
base_controller --> json_rpc_engine;
Expand Down Expand Up @@ -412,12 +429,11 @@ linkStyle default opacity:0.5
subscription_controller --> polling_controller;
subscription_controller --> profile_sync_controller;
subscription_controller --> transaction_controller;
token_search_discovery_controller --> base_controller;
token_search_discovery_controller --> messenger;
transaction_controller --> accounts_controller;
transaction_controller --> approval_controller;
transaction_controller --> base_controller;
transaction_controller --> controller_utils;
transaction_controller --> core_backend;
transaction_controller --> gas_fee_controller;
transaction_controller --> messenger;
transaction_controller --> network_controller;
Expand All @@ -434,6 +450,8 @@ linkStyle default opacity:0.5
transaction_pay_controller --> network_controller;
transaction_pay_controller --> remote_feature_flag_controller;
transaction_pay_controller --> transaction_controller;
ui_state_controller --> base_controller;
ui_state_controller --> messenger;
user_operation_controller --> approval_controller;
user_operation_controller --> base_controller;
user_operation_controller --> controller_utils;
Expand Down
20 changes: 20 additions & 0 deletions packages/ui-state-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Initial release of `@metamask/ui-state-controller` ([#7808](https://github.com/MetaMask/core/pull/7808))
- `UiStateController` for managing client (UI) open/closed state (formerly `ClientStateController`)
- `UiStateController:setClientOpen` messenger action for platform code to call
- `UiStateController:stateChange` event for controllers to subscribe to lifecycle changes
- `isUiOpen` state property (not persisted - always starts as `false`)
- `uiStateControllerSelectors.selectIsUiOpen` selector for derived state access
- Full TypeScript support with exported types

[Unreleased]: https://github.com/MetaMask/core/
21 changes: 21 additions & 0 deletions packages/ui-state-controller/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 MetaMask

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
151 changes: 151 additions & 0 deletions packages/ui-state-controller/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# `@metamask/ui-state-controller`

Provides a centralized way for controllers to respond to application lifecycle changes.

## Installation

`yarn add @metamask/ui-state-controller`

or

`npm install @metamask/ui-state-controller`

## Usage

### Basic Setup

```typescript
import { Messenger } from '@metamask/messenger';
import {
UiStateController,
UiStateControllerActions,
UiStateControllerEvents,
} from '@metamask/ui-state-controller';

const rootMessenger = new Messenger<
'Root',
UiStateControllerActions,
UiStateControllerEvents
>({ namespace: 'Root' });

const controllerMessenger = new Messenger({
namespace: 'UiStateController',
parent: rootMessenger,
});

const uiStateController = new UiStateController({
messenger: controllerMessenger,
});
```

### Platform Integration

Platform code calls `UiStateController:setUiOpen` when the UI is opened or closed:

```text
onUiOpened() {
controllerMessenger.call('UiStateController:setUiOpen', true);
}

onUiClosed() {
controllerMessenger.call('UiStateController:setUiOpen', false);
}
```

### Consumer controller and using with other lifecycle state (e.g. Keyring unlock/lock)

Use `UiStateController:stateChange` only for behavior that **must** run when the UI is open or closed (e.g., pausing/resuming a critical background task). **Use the selector** when subscribing so the handler receives a single derived value (e.g. `isUiOpen`), and **prefer pause/resume** over stop/start for polling.

UI open/close alone is usually not enough to decide when to start or stop work. Combine `UiStateController:stateChange` with other lifecycle events, such as **KeyringController:unlock** / **KeyringController:lock** (or any controller that expresses "ready for background work"). Only start subscriptions, polling, or network requests when **both** the UI is open and the keyring (or equivalent) is unlocked; stop or pause when the UI closes **or** the keyring locks.

#### Important: Usage guidelines and warnings

**Do not subscribe to updates for all kinds of data as soon as the client opens.** When MetaMask opens, the current screen may not need every type of data. Starting subscriptions, polling, or network requests for everything when `isUiOpen` becomes true can lead to unnecessary network traffic and battery use, requests before onboarding is complete (a recurring source of issues), and poor performance as more features are added.

**Use this controller responsibly:**

- Start only the subscriptions, polling, or requests that are **needed for the current screen or flow**
- Do **not** start network-dependent or heavy behavior solely because `UiStateController:stateChange` reported `isUiOpen: true`
- Consider **deferring** non-critical updates until the user has completed onboarding or reached a screen that needs that data
- Prefer starting and stopping per feature or per screen (e.g., when a component mounts that needs the data) rather than globally when the client opens
- **Combine with Keyring unlock/lock:** Only start work when it is appropriate for both UI open state and wallet state (e.g. client open **and** keyring unlocked)
- **Prefer pause/resume over stop/start for polling** so you can resume without full re-initialization. Use the selector when subscribing (see example below).

```typescript
import { uiStateControllerSelectors } from '@metamask/ui-state-controller';

class SomeDataController extends BaseController {
#uiOpen = false;
#keyringUnlocked = false;

constructor({ messenger }) {
super({ messenger, ... });

messenger.subscribe(
'UiStateController:stateChange',
(isUiOpen) => {
this.#uiOpen = isUiOpen;
this.updateActive();
},
uiStateControllerSelectors.selectIsUiOpen,
);

messenger.subscribe('KeyringController:unlock', () => {
this.#keyringUnlocked = true;
this.updateActive();
});

messenger.subscribe('KeyringController:lock', () => {
this.#keyringUnlocked = false;
this.updateActive();
});
}

updateActive() {
const shouldRun = this.#uiOpen && this.#keyringUnlocked;
if (shouldRun) {
this.resume();
} else {
this.pause();
}
}
}
```

Note: `stateChange` emits `[state, patches]`; the selector receives the full payload and returns the value passed to the handler (here, `isUiOpen`).

## API Reference

### State

| Property | Type | Description |
| ---------- | --------- | ------------------------------------------ |
| `isUiOpen` | `boolean` | Whether the client (UI) is currently open. |

Note: State is not persisted. It always starts as `false`.

### Actions

| Action | Parameters | Description |
| ----------------------------- | --------------- | ---------------------------- |
| `UiStateController:getState` | none | Returns current state. |
| `UiStateController:setUiOpen` | `open: boolean` | Sets whether the UI is open. |

### Events

| Event | Payload | Description |
| ------------------------------- | ------------------ | ---------------------------- |
| `UiStateController:stateChange` | `[state, patches]` | Standard state change event. |

### Selectors

```typescript
import { uiStateControllerSelectors } from '@metamask/ui-state-controller';

const state = messenger.call('UiStateController:getState');
const isOpen = uiStateControllerSelectors.selectIsUiOpen(state);
```

## Contributing

This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
24 changes: 24 additions & 0 deletions packages/ui-state-controller/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/

const merge = require('deepmerge');
const path = require('path');

const baseConfig = require('../../jest.config.packages');

const displayName = path.basename(__dirname);

module.exports = merge(baseConfig, {
displayName,
coveragePathIgnorePatterns: [],
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
});
72 changes: 72 additions & 0 deletions packages/ui-state-controller/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{
"name": "@metamask/ui-state-controller",
"version": "0.0.0",
"description": "Tracks and manages the lifecycle state of MetaMask as an application",
"keywords": [
"MetaMask",
"Ethereum"
],
"homepage": "https://github.com/MetaMask/core/tree/main/packages/ui-state-controller#readme",
"bugs": {
"url": "https://github.com/MetaMask/core/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/MetaMask/core.git"
},
"license": "MIT",
"sideEffects": false,
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./package.json": "./package.json"
},
"main": "./dist/index.cjs",
"types": "./dist/index.d.cts",
"files": [
"dist/"
],
"scripts": {
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
"build:all": "ts-bridge --project tsconfig.build.json --verbose --clean",
"build:docs": "typedoc",
"changelog:update": "../../scripts/update-changelog.sh @metamask/ui-state-controller",
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/ui-state-controller",
"publish:preview": "yarn npm publish --tag preview",
"since-latest-release": "../../scripts/since-latest-release.sh",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
"test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
"test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
},
"dependencies": {
"@metamask/base-controller": "^9.0.0",
"@metamask/messenger": "^0.3.0"
},
"devDependencies": {
"@metamask/auto-changelog": "^3.4.4",
"@ts-bridge/cli": "^0.6.4",
"@types/jest": "^27.5.2",
"deepmerge": "^4.2.2",
"jest": "^27.5.1",
"ts-jest": "^27.1.5",
"typedoc": "^0.24.8",
"typedoc-plugin-missing-exports": "^2.0.0",
"typescript": "~5.3.3"
},
"engines": {
"node": "^18.18 || >=20"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}
Loading
Loading