[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M716ZGCX66RNDHMXJJVWQCYA":3,"skill-same:01M716ZGCX66RNDHMXJJVWQCYA":64},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":14,"repositoryHtmlUrl":47,"repositoryHomepageUrl":6,"ownerHtmlUrl":48,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":49,"install":50,"resources":63},"01M716ZGCX66RNDHMXJJVWQCYA","robius-state-management",null,"CRITICAL: Use for Robius state management patterns. Triggers on:\nAppState, persistence, theme switch, 状态管理,\nScope::with_data, save state, load state, serde,\n状态持久化, 主题切换","sapsapshen\u002Fai-memory-router","sapsapshen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F20347959?v=4","01M6XDQEF1DP50DKF37H81J3J5","shenmian","01M6XDQEJPE41Y3DT2763X8ZJN",0,"MIT","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcursor\u002Frobius-state-management\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"state","state management","management","robius state management","save","persistence","patterns","data","with","unknown","critical","load","use","triggers","for","switch","scope","theme","community","2026-11-10 10:12:30",false,"---\nname: robius-state-management\ndescription: |\n  CRITICAL: Use for Robius state management patterns. Triggers on:\n  AppState, persistence, theme switch, 状态管理,\n  Scope::with_data, save state, load state, serde,\n  状态持久化, 主题切换\nrisk: unknown\nsource: community\n---\n\n# Robius State Management Skill\n\nBest practices for state management and persistence in Makepad applications based on Robrix and Moly codebases.\n\n**Source codebases:**\n- **Robrix**: Matrix chat client - AppState, SelectedRoom, persistence via serde\n- **Moly**: AI chat application - Central Store pattern, async initialization, Preferences\n\n## Triggers\n\nUse this skill when:\n- Designing application state structure\n- Implementing state persistence\n- Passing state through widget tree\n- Managing UI state across sessions\n- Keywords: app state, makepad state, persistence, Scope::with_data, save state, load state\n\n## Production Patterns\n\nFor production-ready state management patterns, see the `_base\u002F` directory:\n\n| Pattern | Description |\n|---------|-------------|\n| 06-global-registry | Global widget registry with Cx::set_global |\n| 07-radio-navigation | Tab-style navigation with radio buttons |\n| 10-state-machine | Enum-based state machine widgets |\n| 11-theme-switching | Multi-theme support with apply_over |\n| 12-local-persistence | Save\u002Fload user preferences |\n\n## AppState Structure\n\n### Core State Definition\n\n```rust\nuse serde::{Serialize, Deserialize};\nuse std::collections::HashMap;\nuse matrix_sdk::ruma::OwnedRoomId;\n\n\u002F\u002F\u002F App-wide state that is stored persistently across multiple app runs\n\u002F\u002F\u002F and shared\u002Fupdated across various parts of the app.\n#[derive(Clone, Default, Debug, Serialize, Deserialize)]\npub struct AppState {\n    \u002F\u002F\u002F The currently-selected room\n    pub selected_room: Option\u003CSelectedRoom>,\n\n    \u002F\u002F\u002F Saved UI layout state for main view\n    pub saved_layout_state: SavedLayoutState,\n\n    \u002F\u002F\u002F Per-item saved states (e.g., per-space dock layouts)\n    pub saved_state_per_item: HashMap\u003COwnedRoomId, SavedLayoutState>,\n\n    \u002F\u002F\u002F Whether a user is currently logged in\n    #[serde(skip)]  \u002F\u002F Don't persist login state\n    pub logged_in: bool,\n}\n\n\u002F\u002F\u002F Represents a currently selected item\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub enum SelectedRoom {\n    JoinedRoom { room_name_id: RoomNameId },\n    InvitedRoom { room_name_id: RoomNameId },\n    Space { space_name_id: RoomNameId },\n}\n\nimpl SelectedRoom {\n    pub fn room_id(&self) -> &OwnedRoomId {\n        match self {\n            Self::JoinedRoom { room_name_id } => room_name_id.room_id(),\n            Self::InvitedRoom { room_name_id } => room_name_id.room_id(),\n            Self::Space { space_name_id } => space_name_id.room_id(),\n        }\n    }\n\n    \u002F\u002F\u002F Upgrade from invited to joined state\n    pub fn upgrade_invite_to_joined(&mut self, room_id: &RoomId) -> bool {\n        match self {\n            Self::InvitedRoom { room_name_id } if room_name_id.room_id() == room_id => {\n                let name = room_name_id.clone();\n                *self = Self::JoinedRoom { room_name_id: name };\n                true\n            }\n            _ => false,\n        }\n    }\n}\n\n\u002F\u002F Equality based on room_id only\nimpl PartialEq for SelectedRoom {\n    fn eq(&self, other: &Self) -> bool {\n        self.room_id() == other.room_id()\n    }\n}\nimpl Eq for SelectedRoom {}\n```\n\n### Layout\u002FDock State Persistence\n\n```rust\n\u002F\u002F\u002F A snapshot of UI layout state for restoration\n#[derive(Clone, Default, Debug, Serialize, Deserialize)]\npub struct SavedLayoutState {\n    \u002F\u002F\u002F All items contained in the layout, keyed by ID\n    pub layout_items: HashMap\u003CLiveIdSerde, LayoutItemSerde>,\n\n    \u002F\u002F\u002F Items currently open, keyed by ID\n    pub open_items: HashMap\u003CLiveIdSerde, SelectedRoom>,\n\n    \u002F\u002F\u002F Order items were opened (chronological)\n    pub item_order: Vec\u003CSelectedRoom>,\n\n    \u002F\u002F\u002F Currently selected item when state was saved\n    pub selected_item: Option\u003CSelectedRoom>,\n}\n\n\u002F\u002F\u002F Serializable wrapper for LiveId\n#[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)]\npub struct LiveIdSerde(pub u64);\n\nimpl From\u003CLiveId> for LiveIdSerde {\n    fn from(id: LiveId) -> Self {\n        Self(id.0)\n    }\n}\n\nimpl From\u003CLiveIdSerde> for LiveId {\n    fn from(s: LiveIdSerde) -> Self {\n        LiveId(s.0)\n    }\n}\n```\n\n## State Propagation via Scope\n\n### Passing State Through Widget Tree\n\n```rust\nimpl AppMain for App {\n    fn handle_event(&mut self, cx: &mut Cx, event: &Event) {\n        \u002F\u002F Forward to MatchEvent\n        self.match_event(cx, event);\n\n        \u002F\u002F Create Scope with AppState data\n        let scope = &mut Scope::with_data(&mut self.app_state);\n\n        \u002F\u002F Pass to widget tree - all children can access AppState\n        self.ui.handle_event(cx, event, scope);\n    }\n}\n```\n\n### Accessing State in Child Widgets\n\n```rust\nimpl Widget for RoomScreen {\n    fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {\n        \u002F\u002F Access AppState from scope\n        if let Some(app_state) = scope.data.get::\u003CAppState>() {\n            if let Some(selected) = &app_state.selected_room {\n                self.update_for_room(cx, selected);\n            }\n        }\n\n        self.view.handle_event(cx, event, scope);\n    }\n}\n```\n\n### Modifying State\n\n```rust\nimpl Widget for RoomsList {\n    fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {\n        \u002F\u002F Mutable access to AppState\n        if let Some(app_state) = scope.data.get_mut::\u003CAppState>() {\n            if self.selection_changed {\n                app_state.selected_room = self.get_selected();\n            }\n        }\n    }\n}\n```\n\n## Persistence Layer\n\n### File Paths\n\n```rust\nuse std::path::{Path, PathBuf};\n\nconst LATEST_APP_STATE_FILE_NAME: &str = \"latest_app_state.json\";\nconst WINDOW_GEOM_STATE_FILE_NAME: &str = \"window_geom_state.json\";\n\n\u002F\u002F\u002F Get user-specific persistent state directory\nfn persistent_state_dir(user_id: &UserId) -> PathBuf {\n    app_data_dir()\n        .join(\"users\")\n        .join(user_id.to_string().replace(':', \"_\"))\n}\n\n\u002F\u002F\u002F Get app-wide data directory\nfn app_data_dir() -> &'static Path {\n    \u002F\u002F Platform-specific app data location\n    static APP_DATA_DIR: OnceLock\u003CPathBuf> = OnceLock::new();\n    APP_DATA_DIR.get_or_init(|| {\n        dirs::data_dir()\n            .unwrap_or_else(|| PathBuf::from(\".\"))\n            .join(\"myapp\")\n    })\n}\n```\n\n### Saving State\n\n```rust\nuse std::io::Write;\n\npub fn save_app_state(\n    app_state: AppState,\n    user_id: OwnedUserId,\n) -> anyhow::Result\u003C()> {\n    let file = std::fs::File::create(\n        persistent_state_dir(&user_id).join(LATEST_APP_STATE_FILE_NAME)\n    )?;\n    let mut writer = std::io::BufWriter::new(file);\n    serde_json::to_writer(&mut writer, &app_state)?;\n    writer.flush()?;\n    log!(\"Successfully saved app state to persistent storage.\");\n    Ok(())\n}\n\n\u002F\u002F\u002F Save window geometry state (user-agnostic)\npub fn save_window_state(window_ref: WindowRef, cx: &Cx) -> anyhow::Result\u003C()> {\n    let inner_size = window_ref.get_inner_size(cx);\n    let position = window_ref.get_position(cx);\n    let window_geom = WindowGeomState {\n        inner_size: (inner_size.x, inner_size.y),\n        position: (position.x, position.y),\n        is_fullscreen: window_ref.is_fullscreen(cx),\n    };\n    std::fs::write(\n        app_data_dir().join(WINDOW_GEOM_STATE_FILE_NAME),\n        serde_json::to_string(&window_geom)?,\n    )?;\n    Ok(())\n}\n```\n\n### Loading State\n\n```rust\n\u002F\u002F\u002F Load app state with graceful fallback\npub async fn load_app_state(user_id: &UserId) -> anyhow::Result\u003CAppState> {\n    let state_path = persistent_state_dir(user_id).join(LATEST_APP_STATE_FILE_NAME);\n\n    \u002F\u002F Read file\n    let file_bytes = match tokio::fs::read(&state_path).await {\n        Ok(fb) => fb,\n        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {\n            log!(\"No saved app state found, using default.\");\n            return Ok(AppState::default());\n        }\n        Err(e) => return Err(e.into()),\n    };\n\n    \u002F\u002F Deserialize with fallback\n    match serde_json::from_slice(&file_bytes) {\n        Ok(app_state) => {\n            log!(\"Successfully loaded app state.\");\n            Ok(app_state)\n        }\n        Err(e) => {\n            error!(\"Failed to deserialize: {e}. May be incompatible format.\");\n\n            \u002F\u002F Backup old file\n            let backup_path = state_path.with_extension(\"json.bak\");\n            if let Err(backup_err) = tokio::fs::rename(&state_path, &backup_path).await {\n                error!(\"Failed to backup old state: {}\", backup_err);\n            } else {\n                log!(\"Old state backed up to: {:?}\", backup_path);\n            }\n\n            log!(\"Using default app state.\");\n            Ok(AppState::default())\n        }\n    }\n}\n\n\u002F\u002F\u002F Load window geometry (synchronous, on UI thread)\npub fn load_window_state(window_ref: WindowRef, cx: &mut Cx) -> anyhow::Result\u003C()> {\n    let file = match std::fs::File::open(app_data_dir().join(WINDOW_GEOM_STATE_FILE_NAME)) {\n        Ok(file) => file,\n        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),\n        Err(e) => return Err(e.into()),\n    };\n\n    let window_geom: WindowGeomState = serde_json::from_reader(file)?;\n    log!(\"Restoring window geometry: {window_geom:?}\");\n\n    window_ref.configure_window(\n        cx,\n        dvec2(window_geom.inner_size.0, window_geom.inner_size.1),\n        dvec2(window_geom.position.0, window_geom.position.1),\n        window_geom.is_fullscreen,\n        \"MyApp\".to_string(),\n    );\n    Ok(())\n}\n```\n\n### Startup\u002FShutdown Integration\n\n```rust\nimpl MatchEvent for App {\n    fn handle_startup(&mut self, cx: &mut Cx) {\n        \u002F\u002F Load window geometry (sync, on UI thread)\n        if let Err(e) = persistence::load_window_state(\n            self.ui.window(ids!(main_window)), cx\n        ) {\n            error!(\"Failed to load window state: {}\", e);\n        }\n\n        \u002F\u002F Trigger async app state load\n        let user_id = get_current_user_id();\n        tokio::spawn(async move {\n            match persistence::load_app_state(&user_id).await {\n                Ok(app_state) => {\n                    Cx::post_action(AppStateAction::RestoreFromPersistence(app_state));\n                    SignalToUI::set_ui_signal();\n                }\n                Err(e) => error!(\"Failed to load app state: {}\", e),\n            }\n        });\n    }\n}\n\nimpl AppMain for App {\n    fn handle_event(&mut self, cx: &mut Cx, event: &Event) {\n        if let Event::Shutdown = event {\n            \u002F\u002F Save window state (sync)\n            if let Err(e) = persistence::save_window_state(\n                self.ui.window(ids!(main_window)), cx\n            ) {\n                error!(\"Failed to save window state: {e}\");\n            }\n\n            \u002F\u002F Save app state (sync)\n            if let Some(user_id) = current_user_id() {\n                if let Err(e) = persistence::save_app_state(\n                    self.app_state.clone(), user_id\n                ) {\n                    error!(\"Failed to save app state: {e}\");\n                }\n            }\n        }\n        \u002F\u002F ...\n    }\n}\n```\n\n## Thread-Local State (UI-Only)\n\n```rust\nuse std::{cell::RefCell, rc::Rc, collections::HashMap};\n\nthread_local! {\n    \u002F\u002F\u002F UI-thread-only cache\n    static UI_CACHE: Rc\u003CRefCell\u003CHashMap\u003COwnedRoomId, CachedData>>> =\n        Rc::new(RefCell::new(HashMap::new()));\n}\n\n\u002F\u002F\u002F Get cache reference (requires Cx to ensure UI thread)\npub fn get_ui_cache(_cx: &mut Cx) -> Rc\u003CRefCell\u003CHashMap\u003COwnedRoomId, CachedData>>> {\n    UI_CACHE.with(Rc::clone)\n}\n\n\u002F\u002F\u002F Clear cache (requires Cx)\npub fn clear_ui_cache(_cx: &mut Cx) {\n    UI_CACHE.with(|cache| cache.borrow_mut().clear());\n}\n```\n\n## Best Practices\n\n1. **Separate persistent vs runtime state**: Use `#[serde(skip)]` for non-persistent fields\n2. **Use Scope::with_data() for tree propagation**: Don't pass state through widget refs\n3. **Graceful deserialization fallback**: Handle format changes between versions\n4. **Backup old state files**: Preserve user data when format changes\n5. **User-specific persistent paths**: Separate state per user account\n6. **Sync window state, async app state**: Window geometry loads sync on UI thread\n7. **Thread-local for UI-only caches**: Use `thread_local!` with Cx parameter guard\n\n## Reference Files\n\n- `references\u002Fpersistence-patterns.md` - Additional persistence patterns (Robrix)\n- `references\u002Fstate-structures.md` - State structure examples (Robrix)\n- `references\u002Fmoly-state-patterns.md` - Moly-specific patterns\n  - Central Store struct containing all state\n  - Async Store initialization with `load_into_app()`\n  - App state check pattern (early return if not loaded)\n  - Submodule state managers (Search, Downloads, Chats)\n  - Provider syncing status tracking\n  - Store action forwarding to submodules\n","# Robius State Management Skill\n\nBest practices for state management and persistence in Makepad applications based on Robrix and Moly codebases.\n\n**Source codebases:**\n- **Robrix**: Matrix chat client - AppState, SelectedRoom, persistence via serde\n- **Moly**: AI chat application - Central Store pattern, async initialization, Preferences\n\n## Triggers\n\nUse this skill when:\n- Designing application state structure\n- Implementing state persistence\n- Passing state through widget tree\n- Managing UI state across sessions\n- Keywords: app state, makepad state, persistence, Scope::with_data, save state, load state\n\n## Production Patterns\n\nFor production-ready state management patterns, see the `_base\u002F` directory:\n\n| Pattern | Description |\n|---------|-------------|\n| 06-global-registry | Global widget registry with Cx::set_global |\n| 07-radio-navigation | Tab-style navigation with radio buttons |\n| 10-state-machine | Enum-based state machine widgets |\n| 11-theme-switching | Multi-theme support with apply_over |\n| 12-local-persistence | Save\u002Fload user preferences |\n\n## AppState Structure\n\n### Core State Definition\n\n```rust\nuse serde::{Serialize, Deserialize};\nuse std::collections::HashMap;\nuse matrix_sdk::ruma::OwnedRoomId;\n\n\u002F\u002F\u002F App-wide state that is stored persistently across multiple app runs\n\u002F\u002F\u002F and shared\u002Fupdated across various parts of the app.\n#[derive(Clone, Default, Debug, Serialize, Deserialize)]\npub struct AppState {\n    \u002F\u002F\u002F The currently-selected room\n    pub selected_room: Option\u003CSelectedRoom>,\n\n    \u002F\u002F\u002F Saved UI layout state for main view\n    pub saved_layout_state: SavedLayoutState,\n\n    \u002F\u002F\u002F Per-item saved states (e.g., per-space dock layouts)\n    pub saved_state_per_item: HashMap\u003COwnedRoomId, SavedLayoutState>,\n\n    \u002F\u002F\u002F Whether a user is currently logged in\n    #[serde(skip)]  \u002F\u002F Don't persist login state\n    pub logged_in: bool,\n}\n\n\u002F\u002F\u002F Represents a currently selected item\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub enum SelectedRoom {\n    JoinedRoom { room_name_id: RoomNameId },\n    InvitedRoom { room_name_id: RoomNameId },\n    Space { space_name_id: RoomNameId },\n}\n\nimpl SelectedRoom {\n    pub fn room_id(&self) -> &OwnedRoomId {\n        match self {\n            Self::JoinedRoom { room_name_id } => room_name_id.room_id(),\n            Self::InvitedRoom { room_name_id } => room_name_id.room_id(),\n            Self::Space { space_name_id } => space_name_id.room_id(),\n        }\n    }\n\n    \u002F\u002F\u002F Upgrade from invited to joined state\n    pub fn upgrade_invite_to_joined(&mut self, room_id: &RoomId) -> bool {\n        match self {\n            Self::InvitedRoom { room_name_id } if room_name_id.room_id() == room_id => {\n                let name = room_name_id.clone();\n                *self = Self::JoinedRoom { room_name_id: name };\n                true\n            }\n            _ => false,\n        }\n    }\n}\n\n\u002F\u002F Equality based on room_id only\nimpl PartialEq for SelectedRoom {\n    fn eq(&self, other: &Self) -> bool {\n        self.room_id() == other.room_id()\n    }\n}\nimpl Eq for SelectedRoom {}\n```\n\n### Layout\u002FDock State Persistence\n\n```rust\n\u002F\u002F\u002F A snapshot of UI layout state for restoration\n#[derive(Clone, Default, Debug, Serialize, Deserialize)]\npub struct SavedLayoutState {\n    \u002F\u002F\u002F All items contained in the layout, keyed by ID\n    pub layout_items: HashMap\u003CLiveIdSerde, LayoutItemSerde>,\n\n    \u002F\u002F\u002F Items currently open, keyed by ID\n    pub open_items: HashMap\u003CLiveIdSerde, SelectedRoom>,\n\n    \u002F\u002F\u002F Order items were opened (chronological)\n    pub item_order: Vec\u003CSelectedRoom>,\n\n    \u002F\u002F\u002F Currently selected item when state was saved\n    pub selected_item: Option\u003CSelectedRoom>,\n}\n\n\u002F\u002F\u002F Serializable wrapper for LiveId\n#[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)]\npub struct LiveIdSerde(pub u64);\n\nimpl From\u003CLiveId> for LiveIdSerde {\n    fn from(id: LiveId) -> Self {\n        Self(id.0)\n    }\n}\n\nimpl From\u003CLiveIdSerde> for LiveId {\n    fn from(s: LiveIdSerde) -> Self {\n        LiveId(s.0)\n    }\n}\n```\n\n## State Propagation via Scope\n\n### Passing State Through Widget Tree\n\n```rust\nimpl AppMain for App {\n    fn handle_event(&mut self, cx: &mut Cx, event: &Event) {\n        \u002F\u002F Forward to MatchEvent\n        self.match_event(cx, event);\n\n        \u002F\u002F Create Scope with AppState data\n        let scope = &mut Scope::with_data(&mut self.app_state);\n\n        \u002F\u002F Pass to widget tree - all children can access AppState\n        self.ui.handle_event(cx, event, scope);\n    }\n}\n```\n\n### Accessing State in Child Widgets\n\n```rust\nimpl Widget for RoomScreen {\n    fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {\n        \u002F\u002F Access AppState from scope\n        if let Some(app_state) = scope.data.get::\u003CAppState>() {\n            if let Some(selected) = &app_state.selected_room {\n                self.update_for_room(cx, selected);\n            }\n        }\n\n        self.view.handle_event(cx, event, scope);\n    }\n}\n```\n\n### Modifying State\n\n```rust\nimpl Widget for RoomsList {\n    fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {\n        \u002F\u002F Mutable access to AppState\n        if let Some(app_state) = scope.data.get_mut::\u003CAppState>() {\n            if self.selection_changed {\n                app_state.selected_room = self.get_selected();\n            }\n        }\n    }\n}\n```\n\n## Persistence Layer\n\n### File Paths\n\n```rust\nuse std::path::{Path, PathBuf};\n\nconst LATEST_APP_STATE_FILE_NAME: &str = \"latest_app_state.json\";\nconst WINDOW_GEOM_STATE_FILE_NAME: &str = \"window_geom_state.json\";\n\n\u002F\u002F\u002F Get user-specific persistent state directory\nfn persistent_state_dir(user_id: &UserId) -> PathBuf {\n    app_data_dir()\n        .join(\"users\")\n        .join(user_id.to_string().replace(':', \"_\"))\n}\n\n\u002F\u002F\u002F Get app-wide data directory\nfn app_data_dir() -> &'static Path {\n    \u002F\u002F Platform-specific app data location\n    static APP_DATA_DIR: OnceLock\u003CPathBuf> = OnceLock::new();\n    APP_DATA_DIR.get_or_init(|| {\n        dirs::data_dir()\n            .unwrap_or_else(|| PathBuf::from(\".\"))\n            .join(\"myapp\")\n    })\n}\n```\n\n### Saving State\n\n```rust\nuse std::io::Write;\n\npub fn save_app_state(\n    app_state: AppState,\n    user_id: OwnedUserId,\n) -> anyhow::Result\u003C()> {\n    let file = std::fs::File::create(\n        persistent_state_dir(&user_id).join(LATEST_APP_STATE_FILE_NAME)\n    )?;\n    let mut writer = std::io::BufWriter::new(file);\n    serde_json::to_writer(&mut writer, &app_state)?;\n    writer.flush()?;\n    log!(\"Successfully saved app state to persistent storage.\");\n    Ok(())\n}\n\n\u002F\u002F\u002F Save window geometry state (user-agnostic)\npub fn save_window_state(window_ref: WindowRef, cx: &Cx) -> anyhow::Result\u003C()> {\n    let inner_size = window_ref.get_inner_size(cx);\n    let position = window_ref.get_position(cx);\n    let window_geom = WindowGeomState {\n        inner_size: (inner_size.x, inner_size.y),\n        position: (position.x, position.y),\n        is_fullscreen: window_ref.is_fullscreen(cx),\n    };\n    std::fs::write(\n        app_data_dir().join(WINDOW_GEOM_STATE_FILE_NAME),\n        serde_json::to_string(&window_geom)?,\n    )?;\n    Ok(())\n}\n```\n\n### Loading State\n\n```rust\n\u002F\u002F\u002F Load app state with graceful fallback\npub async fn load_app_state(user_id: &UserId) -> anyhow::Result\u003CAppState> {\n    let state_path = persistent_state_dir(user_id).join(LATEST_APP_STATE_FILE_NAME);\n\n    \u002F\u002F Read file\n    let file_bytes = match tokio::fs::read(&state_path).await {\n        Ok(fb) => fb,\n        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {\n            log!(\"No saved app state found, using default.\");\n            return Ok(AppState::default());\n        }\n        Err(e) => return Err(e.into()),\n    };\n\n    \u002F\u002F Deserialize with fallback\n    match serde_json::from_slice(&file_bytes) {\n        Ok(app_state) => {\n            log!(\"Successfully loaded app state.\");\n            Ok(app_state)\n        }\n        Err(e) => {\n            error!(\"Failed to deserialize: {e}. May be incompatible format.\");\n\n            \u002F\u002F Backup old file\n            let backup_path = state_path.with_extension(\"json.bak\");\n            if let Err(backup_err) = tokio::fs::rename(&state_path, &backup_path).await {\n                error!(\"Failed to backup old state: {}\", backup_err);\n            } else {\n                log!(\"Old state backed up to: {:?}\", backup_path);\n            }\n\n            log!(\"Using default app state.\");\n            Ok(AppState::default())\n        }\n    }\n}\n\n\u002F\u002F\u002F Load window geometry (synchronous, on UI thread)\npub fn load_window_state(window_ref: WindowRef, cx: &mut Cx) -> anyhow::Result\u003C()> {\n    let file = match std::fs::File::open(app_data_dir().join(WINDOW_GEOM_STATE_FILE_NAME)) {\n        Ok(file) => file,\n        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),\n        Err(e) => return Err(e.into()),\n    };\n\n    let window_geom: WindowGeomState = serde_json::from_reader(file)?;\n    log!(\"Restoring window geometry: {window_geom:?}\");\n\n    window_ref.configure_window(\n        cx,\n        dvec2(window_geom.inner_size.0, window_geom.inner_size.1),\n        dvec2(window_geom.position.0, window_geom.position.1),\n        window_geom.is_fullscreen,\n        \"MyApp\".to_string(),\n    );\n    Ok(())\n}\n```\n\n### Startup\u002FShutdown Integration\n\n```rust\nimpl MatchEvent for App {\n    fn handle_startup(&mut self, cx: &mut Cx) {\n        \u002F\u002F Load window geometry (sync, on UI thread)\n        if let Err(e) = persistence::load_window_state(\n            self.ui.window(ids!(main_window)), cx\n        ) {\n            error!(\"Failed to load window state: {}\", e);\n        }\n\n        \u002F\u002F Trigger async app state load\n        let user_id = get_current_user_id();\n        tokio::spawn(async move {\n            match persistence::load_app_state(&user_id).await {\n                Ok(app_state) => {\n                    Cx::post_action(AppStateAction::RestoreFromPersistence(app_state));\n                    SignalToUI::set_ui_signal();\n                }\n                Err(e) => error!(\"Failed to load app state: {}\", e),\n            }\n        });\n    }\n}\n\nimpl AppMain for App {\n    fn handle_event(&mut self, cx: &mut Cx, event: &Event) {\n        if let Event::Shutdown = event {\n            \u002F\u002F Save window state (sync)\n            if let Err(e) = persistence::save_window_state(\n                self.ui.window(ids!(main_window)), cx\n            ) {\n                error!(\"Failed to save window state: {e}\");\n            }\n\n            \u002F\u002F Save app state (sync)\n            if let Some(user_id) = current_user_id() {\n                if let Err(e) = persistence::save_app_state(\n                    self.app_state.clone(), user_id\n                ) {\n                    error!(\"Failed to save app state: {e}\");\n                }\n            }\n        }\n        \u002F\u002F ...\n    }\n}\n```\n\n## Thread-Local State (UI-Only)\n\n```rust\nuse std::{cell::RefCell, rc::Rc, collections::HashMap};\n\nthread_local! {\n    \u002F\u002F\u002F UI-thread-only cache\n    static UI_CACHE: Rc\u003CRefCell\u003CHashMap\u003COwnedRoomId, CachedData>>> =\n        Rc::new(RefCell::new(HashMap::new()));\n}\n\n\u002F\u002F\u002F Get cache reference (requires Cx to ensure UI thread)\npub fn get_ui_cache(_cx: &mut Cx) -> Rc\u003CRefCell\u003CHashMap\u003COwnedRoomId, CachedData>>> {\n    UI_CACHE.with(Rc::clone)\n}\n\n\u002F\u002F\u002F Clear cache (requires Cx)\npub fn clear_ui_cache(_cx: &mut Cx) {\n    UI_CACHE.with(|cache| cache.borrow_mut().clear());\n}\n```\n\n## Best Practices\n\n1. **Separate persistent vs runtime state**: Use `#[serde(skip)]` for non-persistent fields\n2. **Use Scope::with_data() for tree propagation**: Don't pass state through widget refs\n3. **Graceful deserialization fallback**: Handle format changes between versions\n4. **Backup old state files**: Preserve user data when format changes\n5. **User-specific persistent paths**: Separate state per user account\n6. **Sync window state, async app state**: Window geometry loads sync on UI thread\n7. **Thread-local for UI-only caches**: Use `thread_local!` with Cx parameter guard\n\n## Reference Files\n\n- `references\u002Fpersistence-patterns.md` - Additional persistence patterns (Robrix)\n- `references\u002Fstate-structures.md` - State structure examples (Robrix)\n- `references\u002Fmoly-state-patterns.md` - Moly-specific patterns\n  - Central Store struct containing all state\n  - Async Store initialization with `load_into_app()`\n  - App state check pattern (early return if not loaded)\n  - Submodule state managers (Search, Downloads, Chats)\n  - Provider syncing status tracking\n  - Store action forwarding to submodules\n",{"name":5,"risk":28,"source":37,"description":43},"CRITICAL: Use for Robius state management patterns. Triggers on:\nAppState, persistence, theme switch, 状态管理,\nScope::with_data, save state, load state, serde,\n状态持久化, 主题切换\n","main","7a38d8e7073e61c16eda85681cb32fb68a8657a5","skills-store\u002Fcursor\u002Frobius-state-management","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router","https:\u002F\u002Fgithub.com\u002Fsapsapshen","2026-04-14 21:12:12",{"source":8,"skillName":5,"commands":51,"prompt":61,"zipAvailable":62},[52,55,58],{"tool":53,"command":54},"npx","npx skills add sapsapshen\u002Fai-memory-router --skill robius-state-management",{"tool":56,"command":57},"bunx","bunx skills add sapsapshen\u002Fai-memory-router --skill robius-state-management",{"tool":59,"command":60},"pnpm","pnpm dlx skills add sapsapshen\u002Fai-memory-router --skill robius-state-management","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcursor\u002Frobius-state-management\u002FSKILL.md",true,[],[65,75,82,90,96,104],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":69,"licenseFileUrl":70,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":74},"01M72R8PZX1ABFHJGTYPA4CAF1","webapp-testing","To test local web applications, write native Python Playwright scripts.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fglobal\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fglobal\u002Fwebapp-testing\u002FSKILL.md",[],[],"2026-11-10 22:39:42",{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":74},"01M72QG37MMZNDY7X7GXPAK5W6","python-packaging","Comprehensive guide to creating, structuring, and distributing Python packages using modern packaging tools, pyproject.toml, and publishing to PyPI.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fglobal\u002Fpython-packaging\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":69,"licenseFileUrl":86,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":74},"01M72NXR0QMP9G46TW6A2DH59C","canvas-design","These are instructions for creating design philosophies - aesthetic movements that are then EXPRESSED VISUALLY. Output only .md files, .pdf files, and .png files.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fglobal\u002Fcanvas-design\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fglobal\u002Fcanvas-design\u002FSKILL.md",[],[],{"skillNo":91,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":69,"licenseFileUrl":92,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":74},"01M72N55TK3EEQ4QK4AWDC2KZS","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcursor\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcursor\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":69,"licenseFileUrl":100,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":74},"01M72MTWC150CFAP4Y5GSNKF80","slack-gif-creator","A toolkit providing utilities and knowledge for creating animated GIFs optimized for Slack.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcursor\u002Fslack-gif-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcursor\u002Fslack-gif-creator\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":69,"licenseFileUrl":108,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":74},"01M72KPT3VVNSP88MNAY466TZT","frontend-design","You are a frontend designer-engineer, not a layout generator.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcursor\u002Ffrontend-design\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcursor\u002Ffrontend-design\u002FSKILL.md",[],[]]