robius-state-management – skill Thiết kế & UI cho agent AI
CRITICAL: Dùng cho các mẫu quản lý trạng thái của Robius. Kích hoạt khi có: AppState, persistence, theme switch, 状态管理, Scope::with_data, save state, load state, serde, 状态持久化, 主题切换
Cài skill robius-state-management bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/robius-state-management-7f3b2.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /robius-state-management – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/robius-state-management-7f3b2.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $robius-state-management – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/robius-state-management-7f3b2.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /robius-state-management – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/robius-state-management-7f3b2.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /robius-state-management – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
Supporting material availability
This catalog copy contains the inline guidance below, but does not include the following supporting paths. They are external prerequisites, not bundled files:
<support-root>/references/persistence-patterns.md<support-root>/references/state-structures.md<support-root>/references/moly-state-patterns.md
Ask for the original supporting material or an existing installation before using a step that depends on these paths; this catalog does not identify a verified download source for them. Resolve each path relative to that installation, inspect its contents, and verify any applicable license and execution prerequisites. Do not run a command or claim a referenced procedure was followed until its required file exists. Do not fabricate the missing scripts or treat an unrelated file with the same name as equivalent. Independent steps fully documented here can proceed within the user’s authorized scope; report any dependent step as unavailable.
Robius State Management Skill
Best practices for state management and persistence in Makepad applications based on Robrix and Moly codebases.
Source codebases:
- Robrix: Matrix chat client - AppState, SelectedRoom, persistence via serde
- Moly: AI chat application - Central Store pattern, async initialization, Preferences
When to Use
Use this skill when:
- Designing application state structure
- Implementing state persistence
- Passing state through widget tree
- Managing UI state across sessions
- Keywords: app state, makepad state, persistence, Scope::with_data, save state, load state
Production Patterns
The upstream _base/ directory is not bundled. These pattern names are orientation only, not available production-ready implementations:
| Pattern | Description |
|---------|-------------|
| 06-global-registry | Global widget registry with Cx::set_global |
| 07-radio-navigation | Tab-style navigation with radio buttons |
| 10-state-machine | Enum-based state machine widgets |
| 11-theme-switching | Multi-theme support with apply_over |
| 12-local-persistence | Save/load user preferences |
AppState Structure
Core State Definition
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use matrix_sdk::ruma::{OwnedRoomId, RoomId, UserId, OwnedUserId};
/// App-wide state that is stored persistently across multiple app runs
/// and shared/updated across various parts of the app.
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct AppState {
/// The currently-selected room
pub selected_room: Option<SelectedRoom>,
/// Saved UI layout state for main view
pub saved_layout_state: SavedLayoutState,
/// Per-item saved states (e.g., per-space dock layouts)
pub saved_state_per_item: HashMap<OwnedRoomId, SavedLayoutState>,
/// Whether a user is currently logged in
#[serde(skip)] // Don't persist login state
pub logged_in: bool,
}
/// Represents a currently selected item
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SelectedRoom {
JoinedRoom { room_name_id: RoomNameId },
InvitedRoom { room_name_id: RoomNameId },
Space { space_name_id: RoomNameId },
}
impl SelectedRoom {
pub fn room_id(&self) -> &OwnedRoomId {
match self {
Self::JoinedRoom { room_name_id } => room_name_id.room_id(),
Self::InvitedRoom { room_name_id } => room_name_id.room_id(),
Self::Space { space_name_id } => space_name_id.room_id(),
}
}
/// Upgrade from invited to joined state
pub fn upgrade_invite_to_joined(&mut self, room_id: &RoomId) -> bool {
match self {
Self::InvitedRoom { room_name_id } if room_name_id.room_id() == room_id => {
let name = room_name_id.clone();
*self = Self::JoinedRoom { room_name_id: name };
true
}
_ => false,
}
}
}
// Equality based on room_id only
impl PartialEq for SelectedRoom {
fn eq(&self, other: &Self) -> bool {
self.room_id() == other.room_id()
}
}
impl Eq for SelectedRoom {}Layout/Dock State Persistence
/// A snapshot of UI layout state for restoration
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct SavedLayoutState {
/// All items contained in the layout, keyed by ID
pub layout_items: HashMap<LiveIdSerde, LayoutItemSerde>,
/// Items currently open, keyed by ID
pub open_items: HashMap<LiveIdSerde, SelectedRoom>,
/// Order items were opened (chronological)
pub item_order: Vec<SelectedRoom>,
/// Currently selected item when state was saved
pub selected_item: Option<SelectedRoom>,
}
/// Serializable wrapper for LiveId
#[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct LiveIdSerde(pub u64);
impl From<LiveId> for LiveIdSerde {
fn from(id: LiveId) -> Self {
Self(id.0)
}
}
impl From<LiveIdSerde> for LiveId {
fn from(s: LiveIdSerde) -> Self {
LiveId(s.0)
}
}State Propagation via Scope
Passing State Through Widget Tree
impl AppMain for App {
fn handle_event(&mut self, cx: &mut Cx, event: &Event) {
// Forward to MatchEvent
self.match_event(cx, event);
// Create Scope with AppState data
let scope = &mut Scope::with_data(&mut self.app_state);
// Pass to widget tree - all children can access AppState
self.ui.handle_event(cx, event, scope);
}
}Accessing State in Child Widgets
impl Widget for RoomScreen {
fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {
// Access AppState from scope
if let Some(app_state) = scope.data.get::<AppState>() {
if let Some(selected) = &app_state.selected_room {
self.update_for_room(cx, selected);
}
}
self.view.handle_event(cx, event, scope);
}
}Modifying State
impl Widget for RoomsList {
fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {
// Mutable access to AppState
if let Some(app_state) = scope.data.get_mut::<AppState>() {
if self.selection_changed {
app_state.selected_room = self.get_selected();
}
}
}
}The examples are fragments requiring application-defined layout types and a pinned Makepad/Matrix SDK. Keep state directories private, do not persist tokens, bound file sizes, version serialized data and serialize concurrent writers. A missing platform app-data directory now fails explicitly rather than silently writing in the working directory; adapt error handling to the application.
Persistence Layer
File Paths
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
const LATEST_APP_STATE_FILE_NAME: &str = "latest_app_state.json";
const WINDOW_GEOM_STATE_FILE_NAME: &str = "window_geom_state.json";
/// Get user-specific persistent state directory
fn persistent_state_dir(user_id: &UserId) -> PathBuf {
app_data_dir()
.join("users")
.join(user_id.as_str().as_bytes().iter().map(|b| format!("{b:02x}")).collect::<String>())
}
/// Get app-wide data directory
fn app_data_dir() -> &'static Path {
// Platform-specific app data location
static APP_DATA_DIR: OnceLock<PathBuf> = OnceLock::new();
APP_DATA_DIR.get_or_init(|| {
dirs::data_dir()
.expect("Platform app-data directory is required")
.join("myapp")
})
}Saving State
use std::io::Write;
pub fn save_app_state(
app_state: AppState,
user_id: OwnedUserId,
) -> anyhow::Result<()> {
let directory = persistent_state_dir(&user_id);
std::fs::create_dir_all(&directory)?;
// Requires the application to add the tempfile crate. Same-filesystem atomic replace.
let mut temporary = tempfile::NamedTempFile::new_in(&directory)?;
serde_json::to_writer(temporary.as_file_mut(), &app_state)?;
temporary.as_file_mut().flush()?;
temporary.as_file().sync_all()?;
temporary.persist(directory.join(LATEST_APP_STATE_FILE_NAME))?;
log!("Successfully saved app state to persistent storage.");
Ok(())
}
/// Save window geometry state (user-agnostic)
pub fn save_window_state(window_ref: WindowRef, cx: &Cx) -> anyhow::Result<()> {
let inner_size = window_ref.get_inner_size(cx);
let position = window_ref.get_position(cx);
let window_geom = WindowGeomState {
inner_size: (inner_size.x, inner_size.y),
position: (position.x, position.y),
is_fullscreen: window_ref.is_fullscreen(cx),
};
std::fs::create_dir_all(app_data_dir())?;
let mut temporary = tempfile::NamedTempFile::new_in(app_data_dir())?;
serde_json::to_writer(temporary.as_file_mut(), &window_geom)?;
temporary.as_file_mut().flush()?;
temporary.as_file().sync_all()?;
temporary.persist(app… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- robius-widget-patterns – CRITICAL: Dùng cho các mẫu widget của Robius. Kích hoạt khi có: apply_over, TextOrImage…
- saas-multi-tenant – Thiết kế và triển khai kiến trúc SaaS đa khách hàng (multi-tenant) với row-level…
- scarcity-urgency-psychologist – Thiết kế thông điệp về sự khan hiếm và tính cấp bách một cách trung thực, khi tồn kho…
- schema-markup – Thiết kế, kiểm tra và tối ưu dữ liệu có cấu trúc schema.org để đạt đủ điều kiện hiển…
- sci-fi-interface – Hướng dẫn triển khai Web và App cho thiết kế giao diện Sci-Fi. Kích hoạt khi người dùng…
- seek-and-analyze-video – Tìm kiếm và phân tích nội dung video bằng Memories.ai Large Visual Memory Model, phục vụ…
- senior-frontend – Skill phát triển frontend cho ứng dụng React, Next.js, TypeScript và Tailwind CSS. Dùng…
- shadcn – Quản lý các component và dự án shadcn/ui, cung cấp ngữ cảnh, tài liệu và mẫu sử dụng để…