diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index 057402e813..2d7cc72c60 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -1,9 +1,9 @@ # OpenBitFun 功能与设置目录 / OpenBitFun Features & Settings -OpenBitFun Playbook 当前包含 **22 个功能**和 **22 个设置页**,共 **44 个**用户可理解的条目、**338 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 +OpenBitFun Playbook 当前包含 **22 个功能**和 **22 个设置页**,共 **44 个**用户可理解的条目、**339 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 -OpenBitFun Playbook currently contains **22 features**, **22 settings pages**, and **338** source-backed sub-capabilities across **44** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. +OpenBitFun Playbook currently contains **22 features**, **22 settings pages**, and **339** source-backed sub-capabilities across **44** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. ## 唯一事实源 / Single source of truth @@ -33,14 +33,14 @@ Docs, website, search, and agents see only features, settings, and documented su ## 控制边界 / Control boundary -- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **62**、委托 **72**、需交互 **204**、不支持 **0**。 +- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **62**、委托 **72**、需交互 **205**、不支持 **0**。 - 稳定行为声明为带 JSON 输入契约的 `operations` 或 `options`,并绑定原生产品控制 Provider;智能体不接触原始 Tauri Command。 -- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 338 项子能力都不会写入 system prompt。 +- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 339 项子能力都不会写入 system prompt。 - 目录发现与契约读取不依赖 React 或可见窗口。普通配置型 option 统一由 Product Assembly 的共享 ConfigService 执行器读、写并回读,因此 Desktop、CLI 与 Headless 表面走同一份实现;只有宿主原生 operation/provider option 和界面导航按表面注册适配器,缺失时必须明确返回不可用,禁止静默回退本机。只读智能体只能发现和读取目录。 -- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **62 direct**, **72 delegated**, **204 interactive**, and **0 unsupported**. +- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **62 direct**, **72 delegated**, **205 interactive**, and **0 unsupported**. - Stable behavior becomes a typed `operation` or `option` with a JSON input contract and a native product-control provider. Agents never receive raw Tauri commands. -- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 338 documented items enters the system prompt. +- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 339 documented items enters the system prompt. - Discovery and contract lookup do not depend on React or a visible window. Ordinary config-backed options are read, written, and read back by one Product Assembly ConfigService executor shared by Desktop, CLI, and headless surfaces. Only host-native operations/provider options and presentation routes install surface adapters; missing adapters return explicit unavailability without local fallback. Read-only agents may only discover and inspect entries. ## 防腐化门禁 / Anti-drift gates diff --git a/docs/interactive-capabilities/capabilities.json b/docs/interactive-capabilities/capabilities.json index 43d5d0b9e3..3c7bfee1b3 100644 --- a/docs/interactive-capabilities/capabilities.json +++ b/docs/interactive-capabilities/capabilities.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "513e184cc2d93f183cdea258516f532caf58ac6400ef76dce9b54f6de0752627", + "digest": "6ae2eeaa19e6342f9dcf7ff33b7c0fa94547ee1c02fc1835f6f4471caab6fbb3", "ownerDigest": "3cc6d7d869b2c90c2161494a854b5ff7eb72ea69a1a28e40ccd42065fb3382e2", "searchAcceptance": [ { @@ -175,11 +175,11 @@ "features": 22, "settings": 22, "userFacing": 44, - "documentedItems": 338, + "documentedItems": 339, "controlCoverage": { "direct": 62, "delegated": 72, - "interactive": 204, + "interactive": 205, "unsupported": 0 } }, @@ -11565,6 +11565,7 @@ "agent-cards", "home-management", "card-actions", + "desktop-pinning", "drag-restore" ], "kind": "query", @@ -11745,6 +11746,53 @@ "sectionId": "desktop-cards" } }, + { + "id": "feature.desktop-cards:open:desktop-pinning", + "capabilityId": "feature.desktop-cards", + "itemIds": [ + "desktop-pinning" + ], + "kind": "open", + "risk": "ui", + "executionHost": "presentationSurface", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "product_control_presentation_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "openReason": "unstructuredInteraction", + "presentationTarget": { + "kind": "settings", + "pageId": "application.pet", + "sectionId": "desktop-cards" + } + }, { "id": "feature.desktop-cards:open:drag-restore", "capabilityId": "feature.desktop-cards", @@ -26958,11 +27006,13 @@ "highlightsZh": [ "智能体按需创建并更新卡片", "在首页查看、显示、隐藏或删除卡片", + "把卡片固定到 Windows 桌面图标之上", "拖动卡片,位置在重启后恢复" ], "highlightsEn": [ "Agents create and update cards when useful", "View, show, hide, or delete cards from Home", + "Pin cards to the Windows desktop above the icons", "Drag cards; positions are restored after restart" ], "items": [ @@ -27029,6 +27079,17 @@ ] } }, + { + "id": "desktop-pinning", + "titleZh": "在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态", + "titleEn": "Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态”会让卡片进入 Explorer 桌面层,位于桌面图标之上、其他应用之下,并且需要 Explorer 可用且 DPI 上下文一致才能成立;DesktopCard 工具的配置里没有这项显示偏好,因此由用户在卡片菜单或管理列表里切换,智能体只打开精确入口。", + "reasonEn": "“Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards” moves the card into the Explorer desktop layer, above the icons and behind other apps, and only holds while Explorer is available with a matching DPI context; the DesktopCard tool configuration deliberately does not carry this display preference, so the user toggles it from the card menu or a management list and the Agent only opens the exact entry." + } + }, { "id": "drag-restore", "titleZh": "拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复", @@ -27044,11 +27105,13 @@ "stepsZh": [ "让智能体创建一张卡片,或在任务中由智能体主动创建", "拖动卡片到合适位置", + "在卡片菜单、首页列表或设置里把卡片固定到桌面(Windows)", "在首页“小卡片”区或卡片菜单中隐藏或删除" ], "stepsEn": [ "Ask an agent for a card, or let it create one during a task", "Drag the card where you want it", + "Pin it to the desktop from the card menu, the Home card list, or Settings (Windows)", "Hide or delete it from the Home Desktop cards section or the card menu" ], "agentControl": { @@ -27097,9 +27160,11 @@ "countdown reminder", "智能体按需创建并更新卡片", "在首页查看、显示、隐藏或删除卡片", + "把卡片固定到 Windows 桌面图标之上", "拖动卡片,位置在重启后恢复", "Agents create and update cards when useful", "View, show, hide, or delete cards from Home", + "Pin cards to the Windows desktop above the icons", "Drag cards; positions are restored after restart", "按需求或在任务过程中创建倒计时、清单、便签、进度、指标、图表、定时任务和自定义卡片,可定时从 HTTP 接口或本机命令刷新数据", "Create countdown, checklist, note, progress, metrics, chart, scheduled-job, and custom cards on request or during a task, optionally refreshed from an HTTP endpoint or a local command", @@ -27107,6 +27172,8 @@ "See every card in the Home Desktop cards section, and show, hide, or delete individual cards", "在卡片上刷新数据、勾选清单项、切换置顶、打开链接或回到来源会话", "Refresh data, check off list items, toggle always-on-top, open the link, or return to the source session from a card", + "在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态", + "Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards", "拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复", "Drag cards anywhere on the desktop and resize them from their edges or corners; they disappear when OpenBitFun closes and return with the same position and size when it reopens", "20 分钟后提醒我开会", diff --git a/docs/interactive-capabilities/capabilities/feature.desktop-cards.md b/docs/interactive-capabilities/capabilities/feature.desktop-cards.md index 49ee99840b..633159b0dd 100644 --- a/docs/interactive-capabilities/capabilities/feature.desktop-cards.md +++ b/docs/interactive-capabilities/capabilities/feature.desktop-cards.md @@ -23,6 +23,8 @@ Let agents place draggable cards outside the main window for glanceable informat - See every card in the Home Desktop cards section, and show, hide, or delete individual cards - **由专用智能体工具控制 / Delegated Agent tool** · `DesktopCard` · 在卡片上刷新数据、勾选清单项、切换置顶、打开链接或回到来源会话 - Refresh data, check off list items, toggle always-on-top, open the link, or return to the source session from a card +- **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态 + - Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards - **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复 - Drag cards anywhere on the desktop and resize them from their edges or corners; they disappear when OpenBitFun closes and return with the same position and size when it reopens @@ -32,7 +34,9 @@ Let agents place draggable cards outside the main window for glanceable informat Ask an agent for a card, or let it create one during a task 2. 拖动卡片到合适位置 Drag the card where you want it -3. 在首页“小卡片”区或卡片菜单中隐藏或删除 +3. 在卡片菜单、首页列表或设置里把卡片固定到桌面(Windows) + Pin it to the desktop from the card menu, the Home card list, or Settings (Windows) +4. 在首页“小卡片”区或卡片菜单中隐藏或删除 Hide or delete it from the Home Desktop cards section or the card menu 入口 / Entry: OpenBitFun 设置 diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index e552bc1c6a..cd61df7f2a 100644 --- a/docs/interactive-capabilities/technical/product-control-open-audit.json +++ b/docs/interactive-capabilities/technical/product-control-open-audit.json @@ -1,12 +1,12 @@ { "schemaVersion": 1, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "513e184cc2d93f183cdea258516f532caf58ac6400ef76dce9b54f6de0752627", - "count": 204, + "catalogDigest": "6ae2eeaa19e6342f9dcf7ff33b7c0fa94547ee1c02fc1835f6f4471caab6fbb3", + "count": 205, "reasonCounts": { "externalAuth": 4, "secretEntry": 5, - "unstructuredInteraction": 169, + "unstructuredInteraction": 170, "visualSelection": 26 }, "entries": [ @@ -2358,6 +2358,26 @@ "command:show_main_window" ] }, + { + "capabilityId": "feature.desktop-cards", + "itemId": "desktop-pinning", + "titleZh": "在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态", + "titleEn": "Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态”会让卡片进入 Explorer 桌面层,位于桌面图标之上、其他应用之下,并且需要 Explorer 可用且 DPI 上下文一致才能成立;DesktopCard 工具的配置里没有这项显示偏好,因此由用户在卡片菜单或管理列表里切换,智能体只打开精确入口。", + "reasonEn": "“Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards” moves the card into the Explorer desktop layer, above the icons and behind other apps, and only holds while Explorer is available with a matching DPI context; the DesktopCard tool configuration deliberately does not carry this display preference, so the user toggles it from the card menu or a management list and the Agent only opens the exact entry.", + "presentationTarget": { + "kind": "settings", + "pageId": "application.pet", + "sectionId": "desktop-cards" + }, + "evidence": [ + "command:desktop_card_set_always_on_top", + "source:src/apps/desktop/src/desktop_cards/desktop_layer.rs#SHELLDLL_DefView", + "source:src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx#desktopCards.pin", + "source:src/web-ui/src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.tsx#desktop-card-pin-row" + ] + }, { "capabilityId": "feature.desktop-cards", "itemId": "drag-restore", diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index d5916091ca..a4470bd75b 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -1,7 +1,7 @@ { "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "513e184cc2d93f183cdea258516f532caf58ac6400ef76dce9b54f6de0752627", + "catalogDigest": "6ae2eeaa19e6342f9dcf7ff33b7c0fa94547ee1c02fc1835f6f4471caab6fbb3", "commandCount": 709, "coverage": { "commandCount": 709, @@ -2198,7 +2198,8 @@ "feature.desktop-cards" ], "documentedItemIds": [ - "feature.desktop-cards:card-actions" + "feature.desktop-cards:card-actions", + "feature.desktop-cards:desktop-pinning" ], "visibility": "documented", "rustPath": "desktop_cards::commands::desktop_card_set_always_on_top", diff --git a/src/apps/desktop/AGENTS.md b/src/apps/desktop/AGENTS.md index 5fea987bc5..6a790a45c1 100644 --- a/src/apps/desktop/AGENTS.md +++ b/src/apps/desktop/AGENTS.md @@ -142,6 +142,18 @@ may add the CA from `OPENBITFUN_E2E_SUBSCRIPTION_CA_FILE` under that same guard; it does not turn off certificate verification. The native application fixture is `node tests/e2e/scripts/run-subscription-pool.mjs` (see its E2E guide). +For desktop card stacking, native parenting rollback, and legacy record/request compatibility, +run `cargo test --locked -p openbitfun-desktop --no-default-features --lib desktop_cards`. +On a graphical Windows session with Explorer running, also run +`cargo test --locked -p openbitfun-desktop --no-default-features --lib live_explorer_attachment_round_trip -- --ignored`. +The native fixtures use hidden disposable windows; they do not establish WebView rendering, +Win+D behavior, Explorer restart recovery, mixed-DPI monitor dragging, or remote behavior. +After rebuilding, manually verify those native interactions and switching between desktop pinning, +global always-on-top, and hide/show. For Explorer restart (`taskkill /f /im explorer.exe`, then +start it again) a pinned card must reattach within about 30 s, or come back unpinned with the +pin-failure notice; it must never stay "Shown" without a window. UI, hidden-card pinning, and old-host negotiation coverage: +`pnpm --dir src/web-ui run test:run src/app/components/DesktopCard/DesktopCardWindow.test.tsx src/infrastructure/api/service-api/DesktopCardAPI.test.ts src/app/scenes/personal-overview/OverviewDesktopCardsSection.test.tsx src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.test.tsx`. + For session storage directory access, run `cargo test -p openbitfun-desktop --lib api::session_storage_directory::tests` for session storage directory resolution (these tests do not launch a file manager), diff --git a/src/apps/desktop/Cargo.toml b/src/apps/desktop/Cargo.toml index e1169d50bd..59a1478c8e 100644 --- a/src/apps/desktop/Cargo.toml +++ b/src/apps/desktop/Cargo.toml @@ -122,6 +122,7 @@ windows = { workspace = true, features = [ "Win32_System_Com_StructuredStorage", "Win32_System_Ole", "Win32_System_Variant", + "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_Shell_PropertiesSystem", diff --git a/src/apps/desktop/src/desktop_cards/commands.rs b/src/apps/desktop/src/desktop_cards/commands.rs index 9aa742d7a4..17983edbbc 100644 --- a/src/apps/desktop/src/desktop_cards/commands.rs +++ b/src/apps/desktop/src/desktop_cards/commands.rs @@ -39,6 +39,28 @@ pub struct DesktopCardChecklistItemRequest { pub struct DesktopCardAlwaysOnTopRequest { pub card_id: String, pub always_on_top: bool, + /// Omitted by older clients: retain the original always-on-top operation. + #[serde(default)] + pub desktop_pinned: Option, +} + +/// Runtime capability of this host, never a persisted card field. Clients +/// negotiate with it before extending the legacy stacking request, so an +/// older host keeps receiving the original always-on-top payload. +fn desktop_pinning_supported() -> bool { + cfg!(windows) +} + +/// Host capabilities live beside the card list so management surfaces can +/// offer desktop pinning for hidden cards without loading every card. +fn with_host_capabilities(mut payload: Value) -> Value { + if let Some(object) = payload.as_object_mut() { + object.insert( + "desktopPinningSupported".to_string(), + serde_json::json!(desktop_pinning_supported()), + ); + } + payload } #[tauri::command] @@ -47,7 +69,7 @@ pub async fn desktop_card_list( request: DesktopCardListRequest, ) -> Result { let DesktopCardListRequest {} = request; - Ok(cards.list().await) + Ok(with_host_capabilities(cards.list().await)) } #[tauri::command] @@ -55,7 +77,14 @@ pub async fn desktop_card_get( cards: State<'_, Arc>, request: DesktopCardIdRequest, ) -> Result { - cards.get(&request.card_id).await + let mut card = cards.get(&request.card_id).await?; + // Runtime capability only, never persisted. New clients must negotiate + // before extending the legacy stacking request sent to an older host. + card.extra.insert( + "desktopPinningSupported".to_string(), + serde_json::json!(desktop_pinning_supported()), + ); + Ok(card) } #[tauri::command] @@ -101,6 +130,52 @@ pub async fn desktop_card_set_always_on_top( request: DesktopCardAlwaysOnTopRequest, ) -> Result { cards - .set_always_on_top(&request.card_id, request.always_on_top) + .set_stacking( + &request.card_id, + request.always_on_top, + request.desktop_pinned, + ) .await } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn legacy_stacking_requests_do_not_require_desktop_pinning() { + let request: DesktopCardAlwaysOnTopRequest = serde_json::from_value(json!({ + "cardId": "card-1", "alwaysOnTop": true + })) + .unwrap(); + assert!(request.always_on_top); + assert_eq!(request.desktop_pinned, None); + let request: DesktopCardAlwaysOnTopRequest = serde_json::from_value(json!({ + "cardId": "card-1", "alwaysOnTop": false, "desktopPinned": true + })) + .unwrap(); + assert!(!request.always_on_top); + assert_eq!(request.desktop_pinned, Some(true)); + } + + #[test] + fn list_advertises_pinning_as_an_additive_capability() { + let payload = with_host_capabilities(json!({ + "enabled": true, + "cards": [{ "id": "card-1", "desktopPinned": true }] + })); + assert_eq!( + payload["desktopPinningSupported"], + json!(desktop_pinning_supported()) + ); + // Older readers keep working: the original keys are untouched. + assert_eq!(payload["enabled"], json!(true)); + assert_eq!( + payload["cards"], + json!([{ "id": "card-1", "desktopPinned": true }]) + ); + // A non-object payload is returned unchanged instead of patched. + assert_eq!(with_host_capabilities(json!(null)), json!(null)); + } +} diff --git a/src/apps/desktop/src/desktop_cards/desktop_layer.rs b/src/apps/desktop/src/desktop_cards/desktop_layer.rs new file mode 100644 index 0000000000..a0d82093cd --- /dev/null +++ b/src/apps/desktop/src/desktop_cards/desktop_layer.rs @@ -0,0 +1,381 @@ +//! Windows desktop-layer integration. All mutations run on the window's UI thread. +//! +//! Parent cards to the existing Explorer window containing SHELLDLL_DefView, +//! above its icon view, rather than the wallpaper WorkerW behind the icons. +//! No undocumented Shell message (such as Progman's 0x052C WorkerW spawn), +//! Explorer injection, or global topmost window is needed, and nothing here +//! sends a synchronous message to Explorer. If Explorer does not expose that +//! desktop, or it is not responding, fail explicitly. +//! +//! Remaining risk: a cross-process parent/child relationship attaches the +//! input queues of OpenBitFun's UI thread and Explorer's desktop thread, so a +//! long stall on our UI thread can also stall desktop input while a card is +//! pinned. Cards set `WS_EX_NOPARENTNOTIFY` so destroying a card never sends +//! `WM_PARENTNOTIFY` into Explorer, and a hung desktop is refused up front. +//! +//! When Explorer exits, its desktop window destroys the attached card window. +//! The service recreates it from the card record (window `Destroyed` event), +//! and [`install_shell_restart_hook`] reconciles pinned cards again on the +//! `TaskbarCreated` broadcast that Explorer sends after it restarts. + +use std::sync::OnceLock; + +use windows::core::{w, BOOL}; +use windows::Win32::Foundation::{ + GetLastError, SetLastError, HANDLE, HWND, LPARAM, LRESULT, POINT, RECT, WIN32_ERROR, WPARAM, +}; +use windows::Win32::Graphics::Gdi::ScreenToClient; +use windows::Win32::UI::HiDpi::{AreDpiAwarenessContextsEqual, GetWindowDpiAwarenessContext}; +use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass}; +use windows::Win32::UI::WindowsAndMessaging::{ + EnumWindows, FindWindowExW, GetParent, GetPropW, GetWindowLongW, GetWindowRect, + IsHungAppWindow, RegisterWindowMessageW, RemovePropW, SetParent, SetPropW, SetWindowLongW, + SetWindowPos, GWL_EXSTYLE, GWL_STYLE, HWND_NOTOPMOST, HWND_TOP, SWP_FRAMECHANGED, + SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, WS_CHILD, WS_EX_NOPARENTNOTIFY, WS_POPUP, +}; + +const ORIGINAL_STYLE: windows::core::PCWSTR = w!("OpenBitFun.DesktopCard.OriginalStyle"); +/// Subclass id for the `TaskbarCreated` hook on the main window. +const SHELL_RESTART_SUBCLASS_ID: usize = 0x0B17_C4D0; + +static TASKBAR_CREATED: OnceLock = OnceLock::new(); +static SHELL_RESTARTED: OnceLock> = OnceLock::new(); + +unsafe extern "system" fn shell_restart_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + _id: usize, + _data: usize, +) -> LRESULT { + if TASKBAR_CREATED + .get() + .is_some_and(|id| *id != 0 && *id == message) + { + if let Some(callback) = SHELL_RESTARTED.get() { + // The callback only schedules async work; it never blocks here. + callback(); + } + } + unsafe { DefSubclassProc(hwnd, message, wparam, lparam) } +} + +/// Subclasses a top-level window (it must run on that window's UI thread) so +/// Explorer's `TaskbarCreated` broadcast after a shell restart reaches +/// `on_restart`. Only top-level windows receive the broadcast; attached cards +/// are child windows, so the main window carries the hook. +pub(super) fn install_shell_restart_hook( + hwnd: HWND, + on_restart: Box, +) -> Result<(), String> { + let message = + *TASKBAR_CREATED.get_or_init(|| unsafe { RegisterWindowMessageW(w!("TaskbarCreated")) }); + if message == 0 { + return Err(format!( + "Failed to register the TaskbarCreated message: {}", + windows::core::Error::from_win32() + )); + } + if SHELL_RESTARTED.set(on_restart).is_err() { + return Ok(()); // Already installed. + } + if !unsafe { SetWindowSubclass(hwnd, Some(shell_restart_proc), SHELL_RESTART_SUBCLASS_ID, 0) } + .as_bool() + { + return Err("Failed to watch for Windows Explorer restarts.".to_string()); + } + Ok(()) +} + +/// Whether Explorer currently exposes a desktop that a card can attach to. +/// Safe to call from any thread: it only enumerates windows. +pub(super) fn desktop_available() -> Result<(), String> { + desktop_host().map(|_| ()) +} + +unsafe extern "system" fn find_desktop(hwnd: HWND, data: LPARAM) -> BOOL { + // SAFETY: EnumWindows is synchronous and data points to its caller's HWND. + if unsafe { FindWindowExW(Some(hwnd), None, w!("SHELLDLL_DefView"), None) }.is_ok() { + unsafe { *(data.0 as *mut HWND) = hwnd }; + } + BOOL(1) +} + +fn desktop_host() -> Result { + let mut host = HWND::default(); + unsafe { EnumWindows(Some(find_desktop), LPARAM(&mut host as *mut HWND as isize)) } + .map_err(|error| error.to_string())?; + if host.is_invalid() { + Err("Windows desktop is unavailable. Start Windows Explorer and try again.".to_string()) + } else if unsafe { IsHungAppWindow(host) }.as_bool() { + // Attaching joins our UI thread's input queue with Explorer's; never + // do that while the desktop is already unresponsive. + Err("Windows desktop is not responding. Try again in a moment.".to_string()) + } else { + Ok(host) + } +} + +pub(super) fn screen_position(hwnd: HWND) -> Result { + let mut rect = RECT::default(); + unsafe { GetWindowRect(hwnd, &mut rect) }.map_err(|error| error.to_string())?; + Ok(POINT { + x: rect.left, + y: rect.top, + }) +} + +fn set_style(hwnd: HWND, style: i32) -> Result<(), String> { + unsafe { + SetLastError(WIN32_ERROR(0)); + let previous = SetWindowLongW(hwnd, GWL_STYLE, style); + if previous == 0 && GetLastError().0 != 0 { + return Err(windows::core::Error::from_win32().to_string()); + } + } + Ok(()) +} + +fn reparent(hwnd: HWND, parent: Option, style: i32, position: POINT) -> Result<(), String> { + // SetParent legitimately returns NULL on success for a former top-level + // window. The windows-rs Result wrapper alone cannot distinguish that case. + unsafe { + SetLastError(WIN32_ERROR(0)); + let result = SetParent(hwnd, parent); + if result.is_err() && GetLastError().0 != 0 { + return Err(windows::core::Error::from_win32().to_string()); + } + } + set_style(hwnd, style)?; + let mut point = position; + if let Some(parent) = parent { + if !unsafe { ScreenToClient(parent, &mut point) }.as_bool() { + return Err("Failed to map desktop card screen coordinates.".to_string()); + } + } + unsafe { + SetWindowPos( + hwnd, + Some(HWND_TOP), + point.x, + point.y, + 0, + 0, + SWP_NOSIZE | SWP_NOACTIVATE | SWP_FRAMECHANGED, + ) + } + .map_err(|error| error.to_string()) +} + +fn attach_to(hwnd: HWND, parent: HWND) -> Result<(), String> { + // Cross-process SetParent with mismatched DPI contexts can forcibly reset + // the child process's DPI awareness, affecting EVERY OpenBitFun window. + // Refuse rather than silently breaking scaling or saved geometry. + if !unsafe { + AreDpiAwarenessContextsEqual( + GetWindowDpiAwarenessContext(hwnd), + GetWindowDpiAwarenessContext(parent), + ) + } + .as_bool() + { + return Err("Windows desktop and card DPI modes differ; desktop pinning is unavailable in this display configuration.".to_string()); + } + let position = screen_position(hwnd)?; + let style = unsafe { GetWindowLongW(hwnd, GWL_STYLE) }; + let previous_parent = unsafe { GetParent(hwnd) }.ok(); + let saved = unsafe { GetPropW(hwnd, ORIGINAL_STYLE) }; + if !saved.is_invalid() && previous_parent == Some(parent) { + return Ok(()); + } + // Keep only the parenting flags; visibility and resizing may change while + // attached. +1 makes a zero original flag set distinguishable from absent. + if saved.is_invalid() { + let flags = (style as u32 & (WS_CHILD.0 | WS_POPUP.0)) as usize + 1; + unsafe { SetPropW(hwnd, ORIGINAL_STYLE, Some(HANDLE(flags as *mut _))) } + .map_err(|error| error.to_string())?; + } + let result = (|| { + // Destroying a child normally sends WM_PARENTNOTIFY to its parent + // synchronously; with Explorer as the parent that call could block on + // a hung shell. The flag is harmless once the card is top-level again. + let ex_style = unsafe { GetWindowLongW(hwnd, GWL_EXSTYLE) } as u32; + if ex_style & WS_EX_NOPARENTNOTIFY.0 == 0 { + unsafe { + SetLastError(WIN32_ERROR(0)); + let previous = SetWindowLongW( + hwnd, + GWL_EXSTYLE, + (ex_style | WS_EX_NOPARENTNOTIFY.0) as i32, + ); + if previous == 0 && GetLastError().0 != 0 { + return Err(windows::core::Error::from_win32().to_string()); + } + } + } + unsafe { + SetWindowPos( + hwnd, + Some(HWND_NOTOPMOST), + 0, + 0, + 0, + 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE, + ) + } + .map_err(|error| error.to_string())?; + let child_style = (style as u32 & !WS_POPUP.0) | WS_CHILD.0; + // WS_CHILD must be set before parenting a former top-level window. + set_style(hwnd, child_style as i32)?; + reparent(hwnd, Some(parent), child_style as i32, position) + })(); + if let Err(error) = result { + let rollback = reparent(hwnd, previous_parent, style, position); + if saved.is_invalid() { + let _ = unsafe { RemovePropW(hwnd, ORIGINAL_STYLE) }; + } + return Err(format!( + "Failed to attach card to Windows desktop: {error}; rollback: {rollback:?}" + )); + } + Ok(()) +} + +pub(super) fn set_pinned(hwnd: HWND, pinned: bool) -> Result<(), String> { + if pinned { + return attach_to(hwnd, desktop_host()?); + } + let saved = unsafe { GetPropW(hwnd, ORIGINAL_STYLE) }; + if saved.is_invalid() { + return Ok(()); + } + let position = screen_position(hwnd)?; + let style = unsafe { GetWindowLongW(hwnd, GWL_STYLE) }; + let original_flags = (saved.0 as usize - 1) as u32; + let restored = (style as u32 & !(WS_CHILD.0 | WS_POPUP.0)) | original_flags; + let parent = unsafe { GetParent(hwnd) }.ok(); + if let Err(error) = reparent(hwnd, None, restored as i32, position) { + let rollback = reparent(hwnd, parent, style, position); + return Err(format!( + "Failed to detach desktop card: {error}; rollback: {rollback:?}" + )); + } + unsafe { RemovePropW(hwnd, ORIGINAL_STYLE) }.map_err(|error| error.to_string())?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, DestroyWindow, WINDOW_EX_STYLE, WS_OVERLAPPEDWINDOW, + }; + + struct TestWindow(HWND); + impl TestWindow { + fn new(x: i32, y: i32) -> Self { + Self( + unsafe { + CreateWindowExW( + WINDOW_EX_STYLE::default(), + w!("STATIC"), + w!("Desktop card test"), + WS_OVERLAPPEDWINDOW, + x, + y, + 280, + 180, + None, + None, + None, + None, + ) + } + .unwrap(), + ) + } + } + impl Drop for TestWindow { + fn drop(&mut self) { + let _ = unsafe { DestroyWindow(self.0) }; + } + } + + #[test] + fn desktop_parenting_round_trip_preserves_screen_position_and_style() { + let parent = TestWindow::new(-300, 120); + let card = TestWindow::new(45, 60); + let style = unsafe { GetWindowLongW(card.0, GWL_STYLE) }; + let before = screen_position(card.0).unwrap(); + attach_to(card.0, parent.0).unwrap(); + attach_to(card.0, parent.0).unwrap(); // Idempotent restore. + assert_eq!(unsafe { GetParent(card.0) }.unwrap(), parent.0); + assert_ne!( + unsafe { GetWindowLongW(card.0, GWL_STYLE) } as u32 & WS_CHILD.0, + 0 + ); + let attached = screen_position(card.0).unwrap(); + assert_eq!((attached.x, attached.y), (before.x, before.y)); + set_pinned(card.0, false).unwrap(); + set_pinned(card.0, false).unwrap(); + assert!(unsafe { GetParent(card.0) }.is_err()); + assert_eq!(unsafe { GetWindowLongW(card.0, GWL_STYLE) }, style); + let after = screen_position(card.0).unwrap(); + assert_eq!((after.x, after.y), (before.x, before.y)); + } + + #[test] + #[ignore = "requires a graphical Windows session with Explorer running"] + fn live_explorer_attachment_round_trip() { + // Hidden disposable window; never change Explorer's own styles or state. + // Create it in the Shell's DPI context, as required by SetParent. + use windows::Win32::UI::HiDpi::SetThreadDpiAwarenessContext; + let context = unsafe { GetWindowDpiAwarenessContext(desktop_host().unwrap()) }; + let previous_context = unsafe { SetThreadDpiAwarenessContext(context) }; + let card = TestWindow::new(80, 90); + let before = screen_position(card.0).unwrap(); + set_pinned(card.0, true).unwrap(); + assert_eq!( + unsafe { GetParent(card.0) }.unwrap(), + desktop_host().unwrap() + ); + set_pinned(card.0, false).unwrap(); + assert!(unsafe { GetParent(card.0) }.is_err()); + let after = screen_position(card.0).unwrap(); + assert_eq!((after.x, after.y), (before.x, before.y)); + drop(card); + unsafe { SetThreadDpiAwarenessContext(previous_context) }; + } + + #[test] + fn mismatched_dpi_is_rejected_before_mutating_the_window() { + use windows::Win32::UI::HiDpi::{ + SetThreadDpiAwarenessContext, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, + DPI_AWARENESS_CONTEXT_UNAWARE, + }; + let previous = unsafe { SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_UNAWARE) }; + let parent = TestWindow::new(0, 0); + unsafe { SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) }; + let card = TestWindow::new(80, 90); + unsafe { SetThreadDpiAwarenessContext(previous) }; + let style = unsafe { GetWindowLongW(card.0, GWL_STYLE) }; + assert!(attach_to(card.0, parent.0) + .unwrap_err() + .contains("DPI modes differ")); + assert!(unsafe { GetParent(card.0) }.is_err()); + assert_eq!(unsafe { GetWindowLongW(card.0, GWL_STYLE) }, style); + assert!(unsafe { GetPropW(card.0, ORIGINAL_STYLE) }.is_invalid()); + } + + #[test] + fn invalid_parent_is_rejected_without_leaving_attachment_marker() { + let card = TestWindow::new(80, 90); + let style = unsafe { GetWindowLongW(card.0, GWL_STYLE) }; + assert!(attach_to(card.0, HWND(1 as *mut _)).is_err()); + assert!(unsafe { GetParent(card.0) }.is_err()); + assert_eq!(unsafe { GetWindowLongW(card.0, GWL_STYLE) }, style); + assert!(unsafe { GetPropW(card.0, ORIGINAL_STYLE) }.is_invalid()); + } +} diff --git a/src/apps/desktop/src/desktop_cards/mod.rs b/src/apps/desktop/src/desktop_cards/mod.rs index e5c1af939f..fb50c7721c 100644 --- a/src/apps/desktop/src/desktop_cards/mod.rs +++ b/src/apps/desktop/src/desktop_cards/mod.rs @@ -5,12 +5,14 @@ //! notifications, and the `app.ai_experience.enable_desktop_cards` gate. pub mod commands; +#[cfg(windows)] +mod desktop_layer; mod fetch_gate; mod refresh; mod store; mod windows; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::future::Future; use std::pin::Pin; use std::sync::atomic::{AtomicBool, Ordering}; @@ -41,6 +43,24 @@ const GEOMETRY_SAVE_DELAY: Duration = Duration::from_millis(600); /// How long create/update wait for the first fetch so the tool result can /// report real data; slower sources keep loading in the background. const FIRST_FETCH_WAIT: Duration = Duration::from_secs(30); +/// Pinned-card recovery backoff (about 31 s in total). Covers startup before +/// Explorer has created its desktop and an Explorer restart. +const PIN_RETRY_DELAYS: [Duration; 7] = [ + Duration::from_millis(500), + Duration::from_secs(1), + Duration::from_secs(2), + Duration::from_secs(4), + Duration::from_secs(8), + Duration::from_secs(8), + Duration::from_secs(8), +]; +/// Extension-map keys owned by this host (additive; older hosts keep them). +const DESKTOP_PINNED_KEY: &str = "desktopPinned"; +/// Always-on-top mode in effect before pinning, restored on unpin. +const PIN_RESTORE_ON_TOP_KEY: &str = "desktopPinRestoreAlwaysOnTop"; +/// Set when the host had to unpin a card it could not reattach; cleared by the +/// next explicit stacking change. +const PIN_FAILURE_KEY: &str = "desktopPinFailure"; #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] @@ -80,6 +100,8 @@ pub struct DesktopCards { timers: Mutex>, fetch_gate: FetchGate, geometry_save_pending: AtomicBool, + /// Cards with a pinned-window recovery loop in flight. + pin_recovery: Mutex>, self_ref: Weak, } @@ -148,6 +170,7 @@ impl DesktopCards { timers: Mutex::new(HashMap::new()), fetch_gate: FetchGate::default(), geometry_save_pending: AtomicBool::new(false), + pin_recovery: Mutex::new(HashSet::new()), self_ref: self_ref.clone(), }) } @@ -298,6 +321,9 @@ impl DesktopCards { card_id: &str, patch: DesktopCardPatch, ) -> Result { + if let Some(always_on_top) = patch.always_on_top { + self.set_stacking(card_id, always_on_top, None).await?; + } let card = { let mut store = self.store.lock().await; let card = store.get_mut(card_id).ok_or_else(|| not_found(card_id))?; @@ -313,9 +339,6 @@ impl DesktopCards { if let Some(size) = patch.size { windows::apply_window_size(&self.app, card_id, clamp_size(size)); } - if let Some(always_on_top) = patch.always_on_top { - windows::apply_always_on_top(&self.app, card_id, always_on_top); - } let card = self.sync_card_runtime(card).await; self.emit_changed(card_id, Some(&card), false); Ok(self.await_first_fetch(card).await) @@ -329,6 +352,14 @@ impl DesktopCards { let card = { let mut store = self.store.lock().await; let card = store.get_mut(card_id).ok_or_else(|| not_found(card_id))?; + if visible && self.is_enabled() && windows::desktop_pinned(card) { + let position = windows::resolve_position( + &self.app, + card, + windows::open_card_labels(&self.app).len(), + ); + windows::open_window(&self.app, card, position).await?; + } card.visible = visible; let card = card.clone(); Self::save_locked(&mut store)?; @@ -398,20 +429,60 @@ impl DesktopCards { Ok(card) } - pub async fn set_always_on_top( + pub async fn set_stacking( &self, card_id: &str, always_on_top: bool, + desktop_pinned: Option, ) -> Result { - let card = { - let mut store = self.store.lock().await; - let card = store.get_mut(card_id).ok_or_else(|| not_found(card_id))?; - card.always_on_top = always_on_top; - let card = card.clone(); - Self::save_locked(&mut store)?; - card - }; - windows::apply_always_on_top(&self.app, card_id, always_on_top); + if desktop_pinned == Some(true) && !cfg!(windows) { + return Err("Pinning cards to the desktop is supported only on Windows.".to_string()); + } + if desktop_pinned == Some(true) && always_on_top { + return Err( + "Desktop pinning and global always-on-top are mutually exclusive.".to_string(), + ); + } + // Serialize presentation changes with persistence. Do not announce or + // persist success when Windows refuses to attach/detach the window. + let mut store = self.store.lock().await; + let previous = store + .get(card_id) + .ok_or_else(|| not_found(card_id))? + .clone(); + let mut card = previous.clone(); + apply_stacking_record(&mut card, always_on_top, desktop_pinned); + let always_on_top = card.always_on_top; + let apply = windows::apply_stacking( + &self.app, + card_id, + always_on_top, + windows::desktop_pinned(&card), + ) + .await; + if let Err(error) = apply { + let rollback = windows::apply_stacking( + &self.app, + card_id, + previous.always_on_top, + windows::desktop_pinned(&previous), + ) + .await; + return Err(format!("{error}; rollback: {rollback:?}")); + } + *store.get_mut(card_id).ok_or_else(|| not_found(card_id))? = card.clone(); + if let Err(error) = Self::save_locked(&mut store) { + *store.get_mut(card_id).ok_or_else(|| not_found(card_id))? = previous.clone(); + let rollback = windows::apply_stacking( + &self.app, + card_id, + previous.always_on_top, + windows::desktop_pinned(&previous), + ) + .await; + return Err(format!("{error}; rollback: {rollback:?}")); + } + drop(store); self.emit_changed(card_id, Some(&card), false); Ok(card) } @@ -450,7 +521,7 @@ impl DesktopCards { if active { let cascade_index = windows::open_card_labels(&self.app).len(); let position = windows::resolve_position(&self.app, &card, cascade_index); - match windows::open_window(&self.app, &card, position) { + match windows::open_window(&self.app, &card, position).await { Ok(()) => { if position.is_some() && position != card.position { card.position = position; @@ -467,6 +538,10 @@ impl DesktopCards { card.id, error ); + if windows::desktop_pinned(&card) { + // Typically startup before Explorer's desktop exists. + self.schedule_pin_recovery(&card.id, "open_failed"); + } } } } else { @@ -543,6 +618,144 @@ impl DesktopCards { card } + /// Recreates or reattaches a visible pinned card whose window could not be + /// placed on the desktop or was destroyed with Explorer's desktop window. + /// Retries with bounded backoff, then unpins the card and records an + /// explicit failure instead of leaving a "shown" card with no window. + fn schedule_pin_recovery(&self, card_id: &str, reason: &'static str) { + { + let mut recovering = match self.pin_recovery.lock() { + Ok(recovering) => recovering, + Err(poisoned) => poisoned.into_inner(), + }; + if !recovering.insert(card_id.to_string()) { + return; + } + } + let Some(service) = self.arc() else { + return; + }; + let card_id = card_id.to_string(); + tauri::async_runtime::spawn(async move { + service.recover_pin(&card_id, reason).await; + let mut recovering = match service.pin_recovery.lock() { + Ok(recovering) => recovering, + Err(poisoned) => poisoned.into_inner(), + }; + recovering.remove(&card_id); + }); + } + + /// Reattaches every visible pinned card, e.g. after Explorer restarted. + /// Cards that are still attached to the current desktop are left as is. + #[cfg(windows)] + fn reconcile_pinned_cards(&self, reason: &'static str) { + let Some(service) = self.arc() else { + return; + }; + tauri::async_runtime::spawn(async move { + if !service.is_enabled() { + return; + } + let cards = service.store.lock().await.snapshot(); + for card in cards { + if card.visible && windows::desktop_pinned(&card) { + service.schedule_pin_recovery(&card.id, reason); + } + } + }); + } + + async fn recover_pin(&self, card_id: &str, reason: &'static str) { + let mut last_error = String::from("Windows desktop is unavailable."); + for delay in PIN_RETRY_DELAYS { + tokio::time::sleep(delay).await; + if crate::desktop_exit_in_progress() { + return; + } + let store = self.store.lock().await; + // Re-read each attempt: the user may hide, unpin, or delete the + // card, or turn cards off, while recovery waits. + let Some(card) = store.get(card_id).cloned() else { + return; + }; + if !self.is_enabled() || !card.visible || !windows::desktop_pinned(&card) { + return; + } + if let Err(error) = windows::desktop_available() { + last_error = error; + continue; + } + let position = windows::resolve_position( + &self.app, + &card, + windows::open_card_labels(&self.app).len(), + ); + match windows::open_window(&self.app, &card, position).await { + Ok(()) => { + drop(store); + log::info!( + "Desktop card pinned window restored: card_id={}, reason={}", + card_id, + reason + ); + return; + } + Err(error) => last_error = error, + } + } + log::warn!( + "Desktop card pin recovery exhausted retries: card_id={}, reason={}", + card_id, + reason + ); + self.fall_back_from_pin(card_id, &last_error).await; + } + + /// Unpins a card the desktop could not take back and shows it as a normal + /// window, recording the failure so every surface can report it. + async fn fall_back_from_pin(&self, card_id: &str, error: &str) { + log::warn!( + "Desktop card pin recovery failed, unpinning: card_id={}, error={}", + card_id, + error + ); + let card = { + let mut store = self.store.lock().await; + let Some(card) = store.get_mut(card_id) else { + return; + }; + if !card.visible || !windows::desktop_pinned(card) { + return; + } + apply_stacking_record(card, false, Some(false)); + card.extra.insert(PIN_FAILURE_KEY.to_string(), json!(error)); + let mut snapshot = card.clone(); + if self.is_enabled() { + let position = windows::resolve_position( + &self.app, + &snapshot, + windows::open_card_labels(&self.app).len(), + ); + if let Err(open_error) = windows::open_window(&self.app, &snapshot, position).await + { + log::warn!( + "Failed to reopen unpinned desktop card, hiding it: card_id={}, error={}", + card_id, + open_error + ); + snapshot.visible = false; + } + } + if let Some(stored) = store.get_mut(card_id) { + *stored = snapshot.clone(); + } + let _ = Self::save_locked(&mut store); + snapshot + }; + self.emit_changed(card_id, Some(&card), false); + } + fn stop_card_runtime(&self, card_id: &str) { let mut timers = match self.timers.lock() { Ok(timers) => timers, @@ -672,7 +885,7 @@ impl DesktopCards { ); } let card = self.sync_card_runtime(card).await; - if self.is_enabled() { + if self.is_enabled() && !windows::desktop_pinned(&card) { windows::bring_to_front(&self.app, card_id); } self.emit_changed(card_id, Some(&card), false); @@ -763,6 +976,40 @@ impl DesktopCards { } } +/// Applies a stacking request to the record. Pinning remembers the card's +/// always-on-top mode, and an explicit unpin (`desktop_pinned == Some(false)`, +/// which clients send with `always_on_top: false`) restores it. Any explicit +/// change clears a previous pin-failure notice. +fn apply_stacking_record( + card: &mut DesktopCardRecord, + always_on_top: bool, + desktop_pinned: Option, +) { + let was_pinned = windows::desktop_pinned(card); + let previous_on_top = card.always_on_top; + let pinned = desktop_pinned.unwrap_or(false); + let restore_on_top = card + .extra + .get(PIN_RESTORE_ON_TOP_KEY) + .and_then(Value::as_bool); + card.always_on_top = if was_pinned && desktop_pinned == Some(false) && !always_on_top { + restore_on_top.unwrap_or(false) + } else { + always_on_top + }; + if pinned { + if !was_pinned { + card.extra + .insert(PIN_RESTORE_ON_TOP_KEY.to_string(), json!(previous_on_top)); + } + } else { + card.extra.remove(PIN_RESTORE_ON_TOP_KEY); + } + card.extra.remove(PIN_FAILURE_KEY); + card.extra + .insert(DESKTOP_PINNED_KEY.to_string(), json!(pinned)); +} + fn fetches_source(card: &DesktopCardRecord, source: &DesktopCardDataSourceKind) -> bool { card.data_source .as_ref() @@ -901,6 +1148,26 @@ pub fn install(app: &AppHandle) -> Result<(), String> { Box::pin(async move { service.handle_tool_request(request).await }) })); + #[cfg(windows)] + { + let restart_service = Arc::downgrade(&service); + if let Err(error) = windows::watch_shell_restarts( + app, + Box::new(move || { + if let Some(service) = restart_service.upgrade() { + log::info!("Windows Explorer restarted, reattaching pinned desktop cards"); + service.reconcile_pinned_cards("shell_restarted"); + } + }), + ) { + // Destroyed-window recovery still covers pinned cards. + log::warn!( + "Failed to watch for Windows Explorer restarts: error={}", + error + ); + } + } + spawn_config_listener(service); Ok(()) } @@ -916,6 +1183,18 @@ pub fn handle_window_event(window: &tauri::Window, event: &tauri::WindowEvent) { let service = Arc::clone(service.inner()); match event { tauri::WindowEvent::Moved(position) => { + // WM_MOVE reports parent-client coordinates for attached windows. + // Persist screen coordinates so detach and multi-monitor restore do + // not jump by Explorer's desktop origin or non-client offset. + #[cfg(windows)] + let position = match window + .hwnd() + .ok() + .and_then(|hwnd| desktop_layer::screen_position(hwnd).ok()) + { + Some(point) => tauri::PhysicalPosition::new(point.x, point.y), + None => *position, + }; let scale = window.scale_factor().unwrap_or(1.0); let position = position.to_logical::(scale); service.record_geometry( @@ -945,6 +1224,16 @@ pub fn handle_window_event(window: &tauri::Window, event: &tauri::WindowEvent) { }), ); } + // A pinned card is a child of Explorer's desktop window, so it is + // destroyed when Explorer exits. Hide/delete/disable update the record + // before closing, so recovery only proceeds for a card that is still + // meant to be shown and pinned. + #[cfg(windows)] + tauri::WindowEvent::Destroyed => { + if !crate::desktop_exit_in_progress() { + service.schedule_pin_recovery(card_id, "window_destroyed"); + } + } tauri::WindowEvent::CloseRequested { api, .. } => { api.prevent_close(); let card_id = card_id.to_string(); @@ -984,6 +1273,73 @@ mod tests { .unwrap() } + fn stacking_card(always_on_top: bool) -> DesktopCardRecord { + serde_json::from_value(json!({ + "id": "a", "title": "Note", "template": { "kind": "note", "text": "x" }, + "alwaysOnTop": always_on_top + })) + .unwrap() + } + + #[test] + fn unpinning_restores_the_always_on_top_mode_from_before_pinning() { + for before in [true, false] { + let mut card = stacking_card(before); + apply_stacking_record(&mut card, false, Some(true)); + assert!(windows::desktop_pinned(&card)); + assert_eq!(card.extra[PIN_RESTORE_ON_TOP_KEY], json!(before)); + // Re-pinning an already pinned card keeps the original mode. + apply_stacking_record(&mut card, false, Some(true)); + assert_eq!(card.extra[PIN_RESTORE_ON_TOP_KEY], json!(before)); + apply_stacking_record(&mut card, false, Some(false)); + assert!(!windows::desktop_pinned(&card)); + assert_eq!(card.always_on_top, before); + assert!(!card.extra.contains_key(PIN_RESTORE_ON_TOP_KEY)); + } + } + + #[test] + fn legacy_stacking_requests_and_old_pinned_records_stay_compatible() { + // A pinned record written before the restore key existed unpins to + // the previous behavior (always-on-top off). + let mut card = stacking_card(false); + card.extra + .insert(DESKTOP_PINNED_KEY.to_string(), json!(true)); + apply_stacking_record(&mut card, false, Some(false)); + assert!(!card.always_on_top); + // A legacy always-on-top request (no desktopPinned) is applied as is + // and clears pinning. + let mut card = stacking_card(false); + apply_stacking_record(&mut card, false, Some(true)); + apply_stacking_record(&mut card, true, None); + assert!(card.always_on_top); + assert!(!windows::desktop_pinned(&card)); + assert!(!card.extra.contains_key(PIN_RESTORE_ON_TOP_KEY)); + } + + #[test] + fn explicit_stacking_changes_clear_a_pin_failure_notice() { + let mut card = stacking_card(false); + card.extra.insert( + PIN_FAILURE_KEY.to_string(), + json!("Windows desktop is unavailable."), + ); + let restored: DesktopCardRecord = + serde_json::from_value(serde_json::to_value(&card).unwrap()).unwrap(); + assert_eq!( + restored.extra[PIN_FAILURE_KEY], + json!("Windows desktop is unavailable.") + ); + apply_stacking_record(&mut card, false, Some(true)); + assert!(!card.extra.contains_key(PIN_FAILURE_KEY)); + } + + #[test] + fn pin_recovery_backoff_is_bounded() { + let total: Duration = PIN_RETRY_DELAYS.iter().sum(); + assert!(total >= Duration::from_secs(25) && total <= Duration::from_secs(40)); + } + #[test] fn fetches_are_reused_only_when_started_since_the_request_for_the_same_source() { let card = command_card("gh api", json!({"fetchedAtMs": 1_000, "value": {"n": 1}})); diff --git a/src/apps/desktop/src/desktop_cards/store.rs b/src/apps/desktop/src/desktop_cards/store.rs index 2ed0582788..faa1a35e24 100644 --- a/src/apps/desktop/src/desktop_cards/store.rs +++ b/src/apps/desktop/src/desktop_cards/store.rs @@ -152,6 +152,31 @@ mod tests { dir.join("cards.json") } + #[test] + fn desktop_pinning_is_additive_and_survives_legacy_record_rewrites() { + let legacy = json!({ + "id": "a", "title": "Note", "template": { "kind": "note", "text": "x" } + }); + let record: DesktopCardRecord = serde_json::from_value(legacy.clone()).unwrap(); + assert!(record.always_on_top); + assert!(!super::super::windows::desktop_pinned(&record)); + let rewritten = serde_json::to_value(record).unwrap(); + for (key, value) in legacy.as_object().unwrap() { + assert_eq!(&rewritten[key], value); + } + + let mut pinned = legacy; + pinned["alwaysOnTop"] = json!(false); + pinned["desktopPinned"] = json!(true); + let mut record: DesktopCardRecord = serde_json::from_value(pinned).unwrap(); + assert!(super::super::windows::desktop_pinned(&record)); + record.title = "Renamed by an older client".to_string(); + let restored: DesktopCardRecord = + serde_json::from_value(serde_json::to_value(record).unwrap()).unwrap(); + assert!(super::super::windows::desktop_pinned(&restored)); + assert_eq!(restored.extra["desktopPinned"], json!(true)); + } + #[test] fn unparseable_cards_and_unknown_fields_survive_a_rewrite() { let path = temp_path("roundtrip"); diff --git a/src/apps/desktop/src/desktop_cards/windows.rs b/src/apps/desktop/src/desktop_cards/windows.rs index e029d038a5..73d0f9cc7d 100644 --- a/src/apps/desktop/src/desktop_cards/windows.rs +++ b/src/apps/desktop/src/desktop_cards/windows.rs @@ -130,7 +130,18 @@ pub(crate) fn resolve_position( } } -pub(crate) fn open_window( +/// Desktop-only presentation metadata lives in the record's forward-compatible +/// extension map, not in the portable Agent tool's configuration contract. +pub(crate) fn desktop_pinned(card: &DesktopCardRecord) -> bool { + !card.always_on_top + && card + .extra + .get("desktopPinned") + .and_then(serde_json::Value::as_bool) + == Some(true) +} + +pub(crate) async fn open_window( app: &tauri::AppHandle, card: &DesktopCardRecord, position: Option, @@ -140,13 +151,7 @@ pub(crate) fn open_window( } let label = window_label(&card.id); if let Some(window) = app.get_webview_window(&label) { - if let Err(error) = window.set_always_on_top(card.always_on_top) { - log::warn!( - "Failed to update desktop card stacking: card_id={}, error={}", - card.id, - error - ); - } + apply_stacking(app, &card.id, card.always_on_top, desktop_pinned(card)).await?; if let Err(error) = window.unminimize() { log::debug!( "Failed to unminimize desktop card window: card_id={}, error={}", @@ -186,6 +191,12 @@ pub(crate) fn open_window( let window = builder .build() .map_err(|error| format!("Failed to create desktop card window: {error}"))?; + if let Err(error) = + apply_stacking(app, &card.id, card.always_on_top, desktop_pinned(card)).await + { + let _ = window.destroy(); + return Err(error); + } window .show() .map_err(|error| format!("Failed to show desktop card window: {error}")) @@ -215,16 +226,84 @@ pub(crate) fn apply_window_size(app: &tauri::AppHandle, card_id: &str, size: Des } } -pub(crate) fn apply_always_on_top(app: &tauri::AppHandle, card_id: &str, always_on_top: bool) { - if let Some(window) = app.get_webview_window(&window_label(card_id)) { - if let Err(error) = window.set_always_on_top(always_on_top) { - log::warn!( - "Failed to update desktop card stacking: card_id={}, error={}", - card_id, - error - ); - } +/// Whether a desktop for pinned cards exists right now. Checked before +/// recreating a pinned card's window so recovery retries do not churn +/// WebViews while Explorer is still starting. +pub(crate) fn desktop_available() -> Result<(), String> { + #[cfg(windows)] + { + super::desktop_layer::desktop_available() + } + #[cfg(not(windows))] + { + Err("Pinning cards to the desktop is supported only on Windows.".to_string()) + } +} + +/// Calls `on_restart` when Windows Explorer restarts (`TaskbarCreated`), so +/// pinned cards can be reattached to the new desktop. +#[cfg(windows)] +pub(crate) fn watch_shell_restarts( + app: &tauri::AppHandle, + on_restart: Box, +) -> Result<(), String> { + let window = app + .get_webview_window("main") + .ok_or_else(|| "Main window is unavailable.".to_string())?; + let native_window = window.clone(); + window + .run_on_main_thread(move || { + let result = native_window + .hwnd() + .map_err(|error| error.to_string()) + .and_then(|hwnd| { + super::desktop_layer::install_shell_restart_hook(hwnd, on_restart) + }); + if let Err(error) = result { + log::warn!( + "Failed to watch for Windows Explorer restarts: error={}", + error + ); + } + }) + .map_err(|error| error.to_string()) +} + +pub(crate) async fn apply_stacking( + app: &tauri::AppHandle, + card_id: &str, + always_on_top: bool, + desktop_pinned: bool, +) -> Result<(), String> { + if desktop_pinned && !cfg!(windows) { + return Err("Pinning cards to the desktop is supported only on Windows.".to_string()); + } + let Some(window) = app.get_webview_window(&window_label(card_id)) else { + return Ok(()); // Hidden cards apply the saved mode when shown. + }; + #[cfg(windows)] + { + let native_window = window.clone(); + let (send, receive) = tokio::sync::oneshot::channel(); + window + .run_on_main_thread(move || { + let result = native_window + .hwnd() + .map_err(|error| error.to_string()) + .and_then(|hwnd| super::desktop_layer::set_pinned(hwnd, desktop_pinned)); + let _ = send.send(result); + }) + .map_err(|error| error.to_string())?; + receive.await.map_err(|error| error.to_string())??; + } + // Parenting removes topmost before attaching; never promote a child window + // back into the global topmost band through Tauri's top-level setter. + if !desktop_pinned { + window + .set_always_on_top(always_on_top) + .map_err(|error| error.to_string())?; } + Ok(()) } pub(crate) fn bring_to_front(app: &tauri::AppHandle, card_id: &str) { diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index 86a13573a8..9c9886246c 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -2397,6 +2397,13 @@ static PROCESS_EXIT_CLEANUP_COMPLETE: AtomicBool = AtomicBool::new(false); static DESKTOP_EXIT_REQUESTED: AtomicBool = AtomicBool::new(false); static PROCESS_EXIT_CLEANUP_NOTIFY: OnceLock = OnceLock::new(); +/// Whether a graceful desktop exit has started; background recovery must not +/// recreate windows while the app is shutting down. +pub(crate) fn desktop_exit_in_progress() -> bool { + DESKTOP_EXIT_REQUESTED.load(Ordering::Acquire) + || PROCESS_EXIT_CLEANUP_STARTED.load(Ordering::Acquire) +} + pub(crate) async fn perform_process_exit_cleanup() -> bool { let notify = PROCESS_EXIT_CLEANUP_NOTIFY.get_or_init(tokio::sync::Notify::new); if PROCESS_EXIT_CLEANUP_STARTED.swap(true, Ordering::AcqRel) { diff --git a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json index 9a392b9ef5..e4e34d37ca 100644 --- a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json +++ b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "513e184cc2d93f183cdea258516f532caf58ac6400ef76dce9b54f6de0752627", + "digest": "6ae2eeaa19e6342f9dcf7ff33b7c0fa94547ee1c02fc1835f6f4471caab6fbb3", "ownerDigest": "3cc6d7d869b2c90c2161494a854b5ff7eb72ea69a1a28e40ccd42065fb3382e2", "searchAcceptance": [ { @@ -175,11 +175,11 @@ "features": 22, "settings": 22, "userFacing": 44, - "documentedItems": 338, + "documentedItems": 339, "controlCoverage": { "direct": 62, "delegated": 72, - "interactive": 204, + "interactive": 205, "unsupported": 0 } }, @@ -11565,6 +11565,7 @@ "agent-cards", "home-management", "card-actions", + "desktop-pinning", "drag-restore" ], "kind": "query", @@ -11745,6 +11746,53 @@ "sectionId": "desktop-cards" } }, + { + "id": "feature.desktop-cards:open:desktop-pinning", + "capabilityId": "feature.desktop-cards", + "itemIds": [ + "desktop-pinning" + ], + "kind": "open", + "risk": "ui", + "executionHost": "presentationSurface", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "product_control_presentation_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "openReason": "unstructuredInteraction", + "presentationTarget": { + "kind": "settings", + "pageId": "application.pet", + "sectionId": "desktop-cards" + } + }, { "id": "feature.desktop-cards:open:drag-restore", "capabilityId": "feature.desktop-cards", @@ -27059,11 +27107,13 @@ "highlightsZh": [ "智能体按需创建并更新卡片", "在首页查看、显示、隐藏或删除卡片", + "把卡片固定到 Windows 桌面图标之上", "拖动卡片,位置在重启后恢复" ], "highlightsEn": [ "Agents create and update cards when useful", "View, show, hide, or delete cards from Home", + "Pin cards to the Windows desktop above the icons", "Drag cards; positions are restored after restart" ], "items": [ @@ -27130,6 +27180,17 @@ ] } }, + { + "id": "desktop-pinning", + "titleZh": "在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态", + "titleEn": "Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态”会让卡片进入 Explorer 桌面层,位于桌面图标之上、其他应用之下,并且需要 Explorer 可用且 DPI 上下文一致才能成立;DesktopCard 工具的配置里没有这项显示偏好,因此由用户在卡片菜单或管理列表里切换,智能体只打开精确入口。", + "reasonEn": "“Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards” moves the card into the Explorer desktop layer, above the icons and behind other apps, and only holds while Explorer is available with a matching DPI context; the DesktopCard tool configuration deliberately does not carry this display preference, so the user toggles it from the card menu or a management list and the Agent only opens the exact entry." + } + }, { "id": "drag-restore", "titleZh": "拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复", @@ -27145,11 +27206,13 @@ "stepsZh": [ "让智能体创建一张卡片,或在任务中由智能体主动创建", "拖动卡片到合适位置", + "在卡片菜单、首页列表或设置里把卡片固定到桌面(Windows)", "在首页“小卡片”区或卡片菜单中隐藏或删除" ], "stepsEn": [ "Ask an agent for a card, or let it create one during a task", "Drag the card where you want it", + "Pin it to the desktop from the card menu, the Home card list, or Settings (Windows)", "Hide or delete it from the Home Desktop cards section or the card menu" ], "agentControl": { @@ -27198,9 +27261,11 @@ "countdown reminder", "智能体按需创建并更新卡片", "在首页查看、显示、隐藏或删除卡片", + "把卡片固定到 Windows 桌面图标之上", "拖动卡片,位置在重启后恢复", "Agents create and update cards when useful", "View, show, hide, or delete cards from Home", + "Pin cards to the Windows desktop above the icons", "Drag cards; positions are restored after restart", "按需求或在任务过程中创建倒计时、清单、便签、进度、指标、图表、定时任务和自定义卡片,可定时从 HTTP 接口或本机命令刷新数据", "Create countdown, checklist, note, progress, metrics, chart, scheduled-job, and custom cards on request or during a task, optionally refreshed from an HTTP endpoint or a local command", @@ -27208,6 +27273,8 @@ "See every card in the Home Desktop cards section, and show, hide, or delete individual cards", "在卡片上刷新数据、勾选清单项、切换置顶、打开链接或回到来源会话", "Refresh data, check off list items, toggle always-on-top, open the link, or return to the source session from a card", + "在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态", + "Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards", "拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复", "Drag cards anywhere on the desktop and resize them from their edges or corners; they disappear when OpenBitFun closes and return with the same position and size when it reopens", "20 分钟后提醒我开会", diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index 20677faf1e..85a33b42c2 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -5565,11 +5565,13 @@ "highlightsZh": [ "智能体按需创建并更新卡片", "在首页查看、显示、隐藏或删除卡片", + "把卡片固定到 Windows 桌面图标之上", "拖动卡片,位置在重启后恢复" ], "highlightsEn": [ "Agents create and update cards when useful", "View, show, hide, or delete cards from Home", + "Pin cards to the Windows desktop above the icons", "Drag cards; positions are restored after restart" ], "items": [ @@ -5613,6 +5615,23 @@ "command:desktop_card_set_always_on_top" ] }, + { + "id": "desktop-pinning", + "titleZh": "在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态", + "titleEn": "Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态”会让卡片进入 Explorer 桌面层,位于桌面图标之上、其他应用之下,并且需要 Explorer 可用且 DPI 上下文一致才能成立;DesktopCard 工具的配置里没有这项显示偏好,因此由用户在卡片菜单或管理列表里切换,智能体只打开精确入口。", + "reasonEn": "“Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards” moves the card into the Explorer desktop layer, above the icons and behind other apps, and only holds while Explorer is available with a matching DPI context; the DesktopCard tool configuration deliberately does not carry this display preference, so the user toggles it from the card menu or a management list and the Agent only opens the exact entry." + }, + "evidence": [ + "command:desktop_card_set_always_on_top", + "source:src/apps/desktop/src/desktop_cards/desktop_layer.rs#SHELLDLL_DefView", + "source:src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx#desktopCards.pin", + "source:src/web-ui/src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.tsx#desktop-card-pin-row" + ] + }, { "id": "drag-restore", "titleZh": "拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复", @@ -5632,11 +5651,13 @@ "stepsZh": [ "让智能体创建一张卡片,或在任务中由智能体主动创建", "拖动卡片到合适位置", + "在卡片菜单、首页列表或设置里把卡片固定到桌面(Windows)", "在首页“小卡片”区或卡片菜单中隐藏或删除" ], "stepsEn": [ "Ask an agent for a card, or let it create one during a task", "Drag the card where you want it", + "Pin it to the desktop from the card menu, the Home card list, or Settings (Windows)", "Hide or delete it from the Home Desktop cards section or the card menu" ], "agentControl": { diff --git a/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.test.tsx b/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.test.tsx index 7d04f419ac..619718d9fc 100644 --- a/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.test.tsx +++ b/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.test.tsx @@ -9,6 +9,9 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true; const mocks = vi.hoisted(() => ({ isMac: false, + isWindows: true, + setDesktopPinned: vi.fn(), + setAlwaysOnTop: vi.fn(), nativeWindow: true, card: null as unknown, startResize: vi.fn(async (_direction: string) => {}), @@ -39,14 +42,18 @@ vi.mock('@openbitfun/ui', () => ({ IconButton: React.forwardRef void }>( ({ 'aria-label': label, onClick }, ref) => + ))} + ) : null, OverflowText: ({ children, ...props }: { children: React.ReactNode }) => {children}, Spinner: () => , })); vi.mock('@/infrastructure/i18n/hooks/useI18n', () => ({ useI18n: () => ({ - t: (key: string) => key, + t: (key: string, values?: { error?: string }) => values?.error ? `${key}: ${values.error}` : key, formatNumber: (value: number) => String(value), formatDate: (value: number) => String(value), formatRelativeTime: () => 'just now', @@ -58,6 +65,11 @@ vi.mock('@/shared/utils/logger', () => ({ })); vi.mock('@/infrastructure/api/service-api/DesktopCardAPI', () => ({ + // Mirrors the host rule: desktop pinning and global always-on-top are exclusive. + isDesktopPinned: (card: { desktopPinned?: boolean; alwaysOnTop?: boolean }) => + card.desktopPinned === true && !card.alwaysOnTop, + hasDesktopPinFailure: (card: { desktopPinned?: boolean; alwaysOnTop?: boolean; desktopPinFailure?: string }) => + typeof card.desktopPinFailure === 'string' && !(card.desktopPinned === true && !card.alwaysOnTop), desktopCardAPI: { get: vi.fn(async () => mocks.card), onChanged: vi.fn(() => () => {}), @@ -65,7 +77,8 @@ vi.mock('@/infrastructure/api/service-api/DesktopCardAPI', () => ({ setVisible: vi.fn(async () => mocks.card), delete: vi.fn(async () => {}), refresh: vi.fn(async () => mocks.card), - setAlwaysOnTop: vi.fn(async () => mocks.card), + setAlwaysOnTop: mocks.setAlwaysOnTop, + setDesktopPinned: mocks.setDesktopPinned, }, })); @@ -84,6 +97,7 @@ vi.mock('@/infrastructure/desktop-cards/desktopCardWindow', () => ({ vi.mock('@/infrastructure/runtime/environment', () => ({ supportsNativeWindowControls: () => mocks.nativeWindow, isMacOSDesktopRuntime: () => mocks.isMac, + isWindowsDesktopRuntime: () => mocks.isWindows, })); function noteCard(lastData?: Record) { @@ -118,6 +132,9 @@ describe('DesktopCardWindow', () => { mocks.isMac = false; mocks.nativeWindow = true; mocks.card = noteCard(); + mocks.isWindows = true; + mocks.setDesktopPinned.mockReset().mockImplementation(async (_id: string, pinned: boolean) => ({ ...noteCard(), alwaysOnTop: false, desktopPinned: pinned })); + mocks.setAlwaysOnTop.mockReset().mockImplementation(async (_id: string, top: boolean) => ({ ...noteCard(), alwaysOnTop: top, desktopPinned: false })); mocks.startResize.mockClear(); mocks.startDrag.mockClear(); }); @@ -136,6 +153,63 @@ describe('DesktopCardWindow', () => { }); } + async function click(selector: string) { + await act(async () => { + container.querySelector(selector)!.click(); + await Promise.resolve(); + }); + } + + it('switches between desktop pinning and global topmost without hiding the card', async () => { + mocks.card = { ...noteCard(), desktopPinningSupported: true }; + await render(); + await click('[aria-label="desktopCard.menu.more"]'); + await click('[data-menu-id="desktop-pinned"]'); + expect(mocks.setDesktopPinned).toHaveBeenCalledWith('card-1', true); + expect(container.querySelector('[data-menu-id="desktop-pinned"]')?.getAttribute('aria-checked')).toBe('true'); + expect(container.querySelector('[data-menu-id="always-on-top"]')?.getAttribute('aria-checked')).toBe('false'); + await click('[data-menu-id="always-on-top"]'); + expect(mocks.setAlwaysOnTop).toHaveBeenCalledWith('card-1', true); + expect(container.querySelector('[data-menu-id="desktop-pinned"]')?.getAttribute('aria-checked')).toBe('false'); + expect(container.textContent).toContain('hello'); + }); + + it('tells the user when the host had to unpin the card and clears it after re-pinning', async () => { + mocks.card = { ...noteCard(), desktopPinningSupported: true, desktopPinned: false, desktopPinFailure: 'Windows desktop is unavailable.' }; + await render(); + expect(container.querySelector('[role="alert"]')?.textContent).toBe('desktopCard.pinRecoveryFailed'); + await click('[aria-label="desktopCard.menu.more"]'); + await click('[data-menu-id="desktop-pinned"]'); + expect(mocks.setDesktopPinned).toHaveBeenCalledWith('card-1', true); + expect(container.querySelector('[role="alert"]')).toBeNull(); + }); + + it.each([false, undefined])('hides desktop pinning when the host does not advertise it (%s)', async supported => { + mocks.card = { ...noteCard(), desktopPinningSupported: supported }; + await render(); + await click('[aria-label="desktopCard.menu.more"]'); + expect(container.querySelector('[data-menu-id="desktop-pinned"]')).toBeNull(); + }); + + it('hides desktop pinning outside Windows even if the capability was advertised', async () => { + mocks.isWindows = false; + mocks.card = { ...noteCard(), desktopPinningSupported: true }; + await render(); + await click('[aria-label="desktopCard.menu.more"]'); + expect(container.querySelector('[data-menu-id="desktop-pinned"]')).toBeNull(); + }); + + it('reports a rejected native mode change without changing the selected mode', async () => { + mocks.card = { ...noteCard(), desktopPinningSupported: true }; + mocks.setDesktopPinned.mockRejectedValueOnce(new Error('Explorer unavailable')); + await render(); + await click('[aria-label="desktopCard.menu.more"]'); + await click('[data-menu-id="desktop-pinned"]'); + expect(container.querySelector('[role="alert"]')?.textContent).toBe('desktopCard.stackingFailed: Explorer unavailable'); + expect(container.querySelector('[data-menu-id="always-on-top"]')?.getAttribute('aria-checked')).toBe('true'); + expect(container.querySelector('[data-menu-id="desktop-pinned"]')?.getAttribute('aria-checked')).toBe('false'); + }); + function regions() { return Array.from(container.querySelectorAll('[data-openbitfun-part="resizeHandle"]')); } diff --git a/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.tsx b/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.tsx index 7200591161..563b8f82db 100644 --- a/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.tsx +++ b/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.tsx @@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { Ellipsis, RefreshCw, X } from 'lucide-react'; import { Button, Icon, IconButton, MenuPopover, OverflowText, Spinner, type MenuEntry } from '@openbitfun/ui'; import { useI18n } from '@/infrastructure/i18n/hooks/useI18n'; -import { desktopCardAPI, type DesktopCardRecord } from '@/infrastructure/api/service-api/DesktopCardAPI'; +import { desktopCardAPI, hasDesktopPinFailure, isDesktopPinned, type DesktopCardRecord } from '@/infrastructure/api/service-api/DesktopCardAPI'; import { systemAPI } from '@/infrastructure/api/service-api/SystemAPI'; import { DESKTOP_CARD_RESIZE_DIRECTIONS, @@ -11,7 +11,7 @@ import { startDesktopCardWindowDrag, startDesktopCardWindowResize, } from '@/infrastructure/desktop-cards/desktopCardWindow'; -import { isMacOSDesktopRuntime, supportsNativeWindowControls } from '@/infrastructure/runtime/environment'; +import { isMacOSDesktopRuntime, isWindowsDesktopRuntime, supportsNativeWindowControls } from '@/infrastructure/runtime/environment'; import { createLogger } from '@/shared/utils/logger'; import { ChartTemplate, @@ -135,6 +135,9 @@ export default function DesktopCardWindow() { const [menuOpen, setMenuOpen] = useState(false); const [confirmingDelete, setConfirmingDelete] = useState(false); const [refreshing, setRefreshing] = useState(false); + const [desktopPinningSupported, setDesktopPinningSupported] = useState(false); + const [stackingBusy, setStackingBusy] = useState(false); + const [stackingError, setStackingError] = useState(null); const menuButtonRef = useRef(null); const formatters = useMemo(() => ({ formatNumber, @@ -162,7 +165,11 @@ export default function DesktopCardWindow() { if (payload.card) setCard(payload.card); }); void desktopCardAPI.get(cardId) - .then(record => { if (!disposed) setCard(record); }) + .then(record => { + if (disposed) return; + setCard(record); + setDesktopPinningSupported(isWindowsDesktopRuntime() && record.desktopPinningSupported === true); + }) .catch(error => { log.warn('Failed to load desktop card', { cardId, error }); if (!disposed) setLoadFailed(true); @@ -203,6 +210,16 @@ export default function DesktopCardWindow() { .finally(() => setRefreshing(false)); }, [cardId, refreshing]); + const changeStacking = (change: () => Promise) => { + if (stackingBusy) return; + setStackingBusy(true); + setStackingError(null); + void change().then(setCard).catch(error => { + log.warn('Failed to change desktop card stacking', { cardId, error }); + setStackingError(error instanceof Error ? error.message : String(error)); + }).finally(() => setStackingBusy(false)); + }; + const onHeaderMouseDown = (event: React.MouseEvent) => { if (event.button !== 0 || event.detail > 1 || isInteractiveTarget(event.target)) return; event.preventDefault(); @@ -243,12 +260,17 @@ export default function DesktopCardWindow() { label: t('desktopCard.menu.alwaysOnTop'), role: 'menuitemcheckbox', checked: card.alwaysOnTop, - onSelect: () => { - void desktopCardAPI.setAlwaysOnTop(card.id, !card.alwaysOnTop).catch(error => { - log.warn('Failed to toggle desktop card always-on-top', { cardId: card.id, error }); - }); - }, + disabled: stackingBusy, + onSelect: () => changeStacking(() => desktopCardAPI.setAlwaysOnTop(card.id, !card.alwaysOnTop)), }, + ...(desktopPinningSupported ? [{ + id: 'desktop-pinned', + label: t('desktopCard.menu.desktopPinned'), + role: 'menuitemcheckbox' as const, + checked: isDesktopPinned(card), + disabled: stackingBusy, + onSelect: () => changeStacking(() => desktopCardAPI.setDesktopPinned(card.id, !isDesktopPinned(card))), + }] : []), { id: 'separator', label: '', separator: true }, { id: 'hide', label: t('desktopCard.menu.hide'), onSelect: hide }, { id: 'delete', label: t('desktopCard.menu.delete'), tone: 'danger', onSelect: () => setConfirmingDelete(true) }, @@ -282,6 +304,8 @@ export default function DesktopCardWindow() {
+ {stackingError === null && hasDesktopPinFailure(card) &&

{t('desktopCard.pinRecoveryFailed')}

} + {stackingError !== null &&

{t('desktopCard.stackingFailed', { error: stackingError })}

} {confirmingDelete ? (

{t('desktopCard.deleteConfirm.message')}

diff --git a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json index 43d5d0b9e3..3c7bfee1b3 100644 --- a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json +++ b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "513e184cc2d93f183cdea258516f532caf58ac6400ef76dce9b54f6de0752627", + "digest": "6ae2eeaa19e6342f9dcf7ff33b7c0fa94547ee1c02fc1835f6f4471caab6fbb3", "ownerDigest": "3cc6d7d869b2c90c2161494a854b5ff7eb72ea69a1a28e40ccd42065fb3382e2", "searchAcceptance": [ { @@ -175,11 +175,11 @@ "features": 22, "settings": 22, "userFacing": 44, - "documentedItems": 338, + "documentedItems": 339, "controlCoverage": { "direct": 62, "delegated": 72, - "interactive": 204, + "interactive": 205, "unsupported": 0 } }, @@ -11565,6 +11565,7 @@ "agent-cards", "home-management", "card-actions", + "desktop-pinning", "drag-restore" ], "kind": "query", @@ -11745,6 +11746,53 @@ "sectionId": "desktop-cards" } }, + { + "id": "feature.desktop-cards:open:desktop-pinning", + "capabilityId": "feature.desktop-cards", + "itemIds": [ + "desktop-pinning" + ], + "kind": "open", + "risk": "ui", + "executionHost": "presentationSurface", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "product_control_presentation_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "openReason": "unstructuredInteraction", + "presentationTarget": { + "kind": "settings", + "pageId": "application.pet", + "sectionId": "desktop-cards" + } + }, { "id": "feature.desktop-cards:open:drag-restore", "capabilityId": "feature.desktop-cards", @@ -26958,11 +27006,13 @@ "highlightsZh": [ "智能体按需创建并更新卡片", "在首页查看、显示、隐藏或删除卡片", + "把卡片固定到 Windows 桌面图标之上", "拖动卡片,位置在重启后恢复" ], "highlightsEn": [ "Agents create and update cards when useful", "View, show, hide, or delete cards from Home", + "Pin cards to the Windows desktop above the icons", "Drag cards; positions are restored after restart" ], "items": [ @@ -27029,6 +27079,17 @@ ] } }, + { + "id": "desktop-pinning", + "titleZh": "在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态", + "titleEn": "Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态”会让卡片进入 Explorer 桌面层,位于桌面图标之上、其他应用之下,并且需要 Explorer 可用且 DPI 上下文一致才能成立;DesktopCard 工具的配置里没有这项显示偏好,因此由用户在卡片菜单或管理列表里切换,智能体只打开精确入口。", + "reasonEn": "“Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards” moves the card into the Explorer desktop layer, above the icons and behind other apps, and only holds while Explorer is available with a matching DPI context; the DesktopCard tool configuration deliberately does not carry this display preference, so the user toggles it from the card menu or a management list and the Agent only opens the exact entry." + } + }, { "id": "drag-restore", "titleZh": "拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复", @@ -27044,11 +27105,13 @@ "stepsZh": [ "让智能体创建一张卡片,或在任务中由智能体主动创建", "拖动卡片到合适位置", + "在卡片菜单、首页列表或设置里把卡片固定到桌面(Windows)", "在首页“小卡片”区或卡片菜单中隐藏或删除" ], "stepsEn": [ "Ask an agent for a card, or let it create one during a task", "Drag the card where you want it", + "Pin it to the desktop from the card menu, the Home card list, or Settings (Windows)", "Hide or delete it from the Home Desktop cards section or the card menu" ], "agentControl": { @@ -27097,9 +27160,11 @@ "countdown reminder", "智能体按需创建并更新卡片", "在首页查看、显示、隐藏或删除卡片", + "把卡片固定到 Windows 桌面图标之上", "拖动卡片,位置在重启后恢复", "Agents create and update cards when useful", "View, show, hide, or delete cards from Home", + "Pin cards to the Windows desktop above the icons", "Drag cards; positions are restored after restart", "按需求或在任务过程中创建倒计时、清单、便签、进度、指标、图表、定时任务和自定义卡片,可定时从 HTTP 接口或本机命令刷新数据", "Create countdown, checklist, note, progress, metrics, chart, scheduled-job, and custom cards on request or during a task, optionally refreshed from an HTTP endpoint or a local command", @@ -27107,6 +27172,8 @@ "See every card in the Home Desktop cards section, and show, hide, or delete individual cards", "在卡片上刷新数据、勾选清单项、切换置顶、打开链接或回到来源会话", "Refresh data, check off list items, toggle always-on-top, open the link, or return to the source session from a card", + "在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态", + "Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards", "拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复", "Drag cards anywhere on the desktop and resize them from their edges or corners; they disappear when OpenBitFun closes and return with the same position and size when it reopens", "20 分钟后提醒我开会", diff --git a/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.test.tsx b/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.test.tsx index b0889891ba..598b419c1d 100644 --- a/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.test.tsx +++ b/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.test.tsx @@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({ tauri: true, list: vi.fn(), setVisible: vi.fn(), + setDesktopPinned: vi.fn(), remove: vi.fn(), confirm: vi.fn(), notifyError: vi.fn(), @@ -24,9 +25,15 @@ const mocks = vi.hoisted(() => ({ vi.mock('@/infrastructure/runtime', () => ({ isTauriRuntime: () => mocks.tauri })); vi.mock('@/infrastructure/api/service-api/DesktopCardAPI', () => ({ + // Mirrors the host rule: desktop pinning and global always-on-top are exclusive. + isDesktopPinned: (card: { desktopPinned?: boolean; alwaysOnTop?: boolean }) => + card.desktopPinned === true && !card.alwaysOnTop, + hasDesktopPinFailure: (card: { desktopPinned?: boolean; alwaysOnTop?: boolean; desktopPinFailure?: string }) => + typeof card.desktopPinFailure === 'string' && !(card.desktopPinned === true && !card.alwaysOnTop), desktopCardAPI: { list: mocks.list, setVisible: mocks.setVisible, + setDesktopPinned: mocks.setDesktopPinned, delete: mocks.remove, onChanged: (listener: (payload: DesktopCardChangedPayload) => void) => { mocks.changed.push(listener); @@ -80,6 +87,7 @@ beforeEach(() => { mocks.state = []; mocks.list.mockReset(); mocks.setVisible.mockReset().mockResolvedValue(undefined); + mocks.setDesktopPinned.mockReset().mockResolvedValue(undefined); mocks.remove.mockReset().mockResolvedValue(undefined); mocks.confirm.mockReset().mockResolvedValue(true); mocks.notifyError.mockReset(); @@ -142,6 +150,70 @@ it('keeps a card when deletion is not confirmed and reports host failures', asyn expect(mocks.notifyError).toHaveBeenCalledWith('desktopCards.actionFailed'); }); +it('pins and unpins a hidden card from the list when the host advertises pinning', async () => { + mocks.list.mockResolvedValue({ + enabled: true, + desktopPinningSupported: true, + cards: [card('a', { visible: false })], + }); + await render(); + await act(async () => button(rows()[0], 'desktopCards.pin').click()); + expect(mocks.setDesktopPinned).toHaveBeenCalledWith('a', true); + + await act(async () => mocks.changed.forEach(listener => listener({ + cardId: 'a', + card: card('a', { visible: false, alwaysOnTop: false, desktopPinned: true, updatedAtMs: 9 }), + deleted: false, + }))); + expect(rows()[0].dataset.pinned).toBe('true'); + expect(rows()[0].textContent).toContain('desktopCards.pinned'); + expect(rows()[0].textContent).toContain('desktopCards.hidden'); + + await act(async () => button(rows()[0], 'desktopCards.unpin').click()); + expect(mocks.setDesktopPinned).toHaveBeenCalledWith('a', false); +}); + +it('treats a globally topmost card as not pinned when pinning it from the list', async () => { + mocks.list.mockResolvedValue({ + enabled: true, + desktopPinningSupported: true, + cards: [card('a', { desktopPinned: true, alwaysOnTop: true })], + }); + await render(); + expect(rows()[0].dataset.pinned).toBe('false'); + await act(async () => button(rows()[0], 'desktopCards.pin').click()); + expect(mocks.setDesktopPinned).toHaveBeenCalledWith('a', true); +}); + +it('reports a card the host had to unpin instead of showing it as pinned', async () => { + mocks.list.mockResolvedValue({ + enabled: true, + desktopPinningSupported: true, + cards: [card('a', { desktopPinned: false, desktopPinFailure: 'Windows desktop is unavailable.' })], + }); + await render(); + expect(rows()[0].dataset.pinned).toBe('false'); + expect(rows()[0].textContent).toContain('desktopCards.pinLost'); + expect(rows()[0].textContent).toContain('desktopCards.shown'); +}); + +it('hides the pin action on hosts without the capability', async () => { + mocks.list.mockResolvedValue({ enabled: true, cards: [card('a')] }); + await render(); + expect(rows()[0].querySelector('button[aria-label="desktopCards.pin"]')).toBeNull(); + expect(rows()[0].querySelector('button[aria-label="desktopCards.unpin"]')).toBeNull(); +}); + +it('reports a rejected pin change without claiming the card is pinned', async () => { + mocks.list.mockResolvedValue({ enabled: true, desktopPinningSupported: true, cards: [card('a')] }); + mocks.setDesktopPinned.mockRejectedValue(new Error('Explorer unavailable')); + await render(); + await act(async () => button(rows()[0], 'desktopCards.pin').click()); + expect(mocks.notifyError).toHaveBeenCalledWith('desktopCards.actionFailed'); + expect(rows()[0].dataset.pinned).toBe('false'); + expect(mocks.setVisible).not.toHaveBeenCalled(); +}); + it('keeps cards listed but blocks showing hidden ones while the feature is turned off', async () => { mocks.list.mockResolvedValue({ enabled: false, cards: [card('a', { visible: false })] }); await render(); diff --git a/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx b/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx index dcaabb796e..9d23d2e87e 100644 --- a/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx +++ b/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx @@ -1,7 +1,12 @@ import { useCallback, useEffect, useState } from 'react'; -import { Eye, EyeOff, Settings, Trash2 } from 'lucide-react'; +import { Eye, EyeOff, Pin, PinOff, Settings, Trash2 } from 'lucide-react'; import { Button, Icon, IconButton, OverflowText } from '@openbitfun/ui'; -import { desktopCardAPI, type DesktopCardRecord } from '@/infrastructure/api/service-api/DesktopCardAPI'; +import { + desktopCardAPI, + hasDesktopPinFailure, + isDesktopPinned, + type DesktopCardRecord, +} from '@/infrastructure/api/service-api/DesktopCardAPI'; import { confirmDanger } from '@/infrastructure/confirm-dialog'; import { useI18n } from '@/infrastructure/i18n/hooks/useI18n'; import { isTauriRuntime } from '@/infrastructure/runtime'; @@ -18,7 +23,7 @@ const log = createLogger('OverviewDesktopCardsSection'); type CardsState = | { status: 'loading' } | { status: 'failed' } - | { status: 'ready'; enabled: boolean; cards: DesktopCardRecord[] }; + | { status: 'ready'; enabled: boolean; cards: DesktopCardRecord[]; pinningSupported: boolean }; function sortCards(cards: DesktopCardRecord[]): DesktopCardRecord[] { return [...cards].sort((a, b) => b.updatedAtMs - a.updatedAtMs); @@ -40,7 +45,12 @@ export function OverviewDesktopCardsSection({ isActive }: { isActive: boolean }) const load = useCallback(async () => { try { const list = await desktopCardAPI.list(); - setState({ status: 'ready', enabled: list.enabled, cards: sortCards(list.cards) }); + setState({ + status: 'ready', + enabled: list.enabled, + cards: sortCards(list.cards), + pinningSupported: list.desktopPinningSupported === true, + }); } catch (error) { log.warn('Failed to load desktop cards', error); setState(current => current.status === 'ready' ? current : { status: 'failed' }); @@ -80,6 +90,20 @@ export function OverviewDesktopCardsSection({ isActive }: { isActive: boolean }) } }; + const togglePinned = async (card: DesktopCardRecord) => { + setBusyCardId(card.id); + try { + // Works for hidden cards too: the host keeps the preference and applies + // it when the card is shown again. + await desktopCardAPI.setDesktopPinned(card.id, !isDesktopPinned(card)); + } catch (error) { + log.warn('Failed to change desktop card pinning', { cardId: card.id, error }); + notification.error(t('desktopCards.actionFailed')); + } finally { + setBusyCardId(null); + } + }; + const deleteCard = async (card: DesktopCardRecord) => { const confirmed = await confirmDanger( t('desktopCards.deleteConfirmTitle'), @@ -100,6 +124,7 @@ export function OverviewDesktopCardsSection({ isActive }: { isActive: boolean }) const cards = state.status === 'ready' ? state.cards : []; const enabled = state.status === 'ready' && state.enabled; + const pinningSupported = state.status === 'ready' && state.pinningSupported; const visibleCount = cards.filter(card => card.visible).length; const summaryValue = state.status === 'ready' ? formatNumber(cards.length) : t(state.status === 'loading' ? 'loadingValue' : 'unavailableValue'); const summaryDescription = state.status !== 'ready' @@ -138,16 +163,28 @@ export function OverviewDesktopCardsSection({ isActive }: { isActive: boolean }) {cards.map(card => { const CardIcon = desktopCardIcon(card); const busy = busyCardId === card.id; + const pinned = isDesktopPinned(card); return ( -
  • +
  • {card.title} {card.visible ? t('desktopCards.shown') : t('desktopCards.hidden')} + {pinned ? ` · ${t('desktopCards.pinned')}` : ''} + {hasDesktopPinFailure(card) ? ` · ${t('desktopCards.pinLost')}` : ''} {card.subtitle ? ` · ${card.subtitle}` : ''}
    + {pinningSupported && ( + } + onClick={() => void togglePinned(card)} /> + )} } diff --git a/src/web-ui/src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.test.tsx b/src/web-ui/src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.test.tsx new file mode 100644 index 0000000000..fe6d3fa14f --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.test.tsx @@ -0,0 +1,205 @@ +// @vitest-environment jsdom +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import type { + DesktopCardChangedPayload, + DesktopCardRecord, +} from '@/infrastructure/api/service-api/DesktopCardAPI'; +import DesktopCardsSettingsSection from './DesktopCardsSettingsSection'; + +const mocks = vi.hoisted(() => ({ + tauri: true, + cached: { enable_desktop_cards: true } as { enable_desktop_cards?: boolean } | undefined, + getSettings: vi.fn(), + saveSettings: vi.fn(), + list: vi.fn(), + setDesktopPinned: vi.fn(), + changed: [] as Array<(payload: DesktopCardChangedPayload) => void>, + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +vi.mock('@openbitfun/ui', () => ({ + Switch: ({ checked, disabled, onChange, 'aria-label': label }: { + checked: boolean; + disabled?: boolean; + onChange?: (event: { currentTarget: { checked: boolean } }) => void; + 'aria-label': string; + }) => ( + onChange?.({ currentTarget: { checked: event.currentTarget.checked } })} + /> + ), +})); + +vi.mock('@/infrastructure/config/components/common', () => ({ + ConfigPageSection: ({ title, children }: { title: string; children?: React.ReactNode }) => ( +

    {title}

    {children}
    + ), + ConfigPageRow: ({ label, description, children, ...rest }: { + label: React.ReactNode; + description?: React.ReactNode; + children?: React.ReactNode; + }) => ( +
    + {label} + {description} + {children} +
    + ), + ConfigLoadingState: () =>
    loading
    , + ConfigRetryState: () =>
    retry
    , +})); + +vi.mock('@/infrastructure/config/services/AIExperienceConfigService', () => ({ + aiExperienceConfigService: { + getCachedSettings: () => mocks.cached, + getSettingsAsync: mocks.getSettings, + saveSettings: mocks.saveSettings, + addChangeListener: () => () => {}, + }, +})); + +vi.mock('@/infrastructure/api/service-api/DesktopCardAPI', () => ({ + // Mirrors the host rule: desktop pinning and global always-on-top are exclusive. + isDesktopPinned: (card: { desktopPinned?: boolean; alwaysOnTop?: boolean }) => + card.desktopPinned === true && !card.alwaysOnTop, + hasDesktopPinFailure: (card: { desktopPinned?: boolean; alwaysOnTop?: boolean; desktopPinFailure?: string }) => + typeof card.desktopPinFailure === 'string' && !(card.desktopPinned === true && !card.alwaysOnTop), + desktopCardAPI: { + list: mocks.list, + setDesktopPinned: mocks.setDesktopPinned, + onChanged: (listener: (payload: DesktopCardChangedPayload) => void) => { + mocks.changed.push(listener); + return () => { mocks.changed = mocks.changed.filter(entry => entry !== listener); }; + }, + }, +})); + +vi.mock('@/infrastructure/i18n', () => ({ + useI18n: () => ({ + t: (key: string, values?: { title?: string }) => values?.title ? `${key}:${values.title}` : key, + }), +})); + +vi.mock('@/infrastructure/peer-device/deviceSurface', () => ({ + getActiveSurfaceScope: () => ({ isCurrent: () => true }), +})); + +vi.mock('@/infrastructure/runtime', () => ({ isTauriRuntime: () => mocks.tauri })); + +vi.mock('@/shared/notification-system', () => ({ + useNotification: () => ({ error: mocks.notifyError, success: mocks.notifySuccess }), +})); + +vi.mock('../shared/useSettingsSectionAnchor', () => ({ + useSettingsSectionAnchor: (id: string) => id, +})); + +const card = (id: string, extra: Partial = {}): DesktopCardRecord => ({ + id, + title: `Card ${id}`, + template: { kind: 'note', text: 'hello' }, + visible: false, + alwaysOnTop: true, + createdAtMs: 1, + updatedAtMs: 1, + ...extra, +} as DesktopCardRecord); + +let root: Root; +let container: HTMLDivElement; + +const render = () => act(async () => { + root.render(); +}); +const pinRows = () => [...container.querySelectorAll('[data-testid="desktop-card-pin-row"]')]; +const pinSwitch = (row: Element) => row.querySelector('input[type="checkbox"]')!; + +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + mocks.tauri = true; + mocks.cached = { enable_desktop_cards: true }; + mocks.changed = []; + mocks.getSettings.mockReset(); + mocks.saveSettings.mockReset(); + mocks.list.mockReset(); + mocks.setDesktopPinned.mockReset().mockResolvedValue(undefined); + mocks.notifyError.mockReset(); + mocks.notifySuccess.mockReset(); + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); +}); + +it('offers a pin switch per card, including hidden ones, and pins them through the host', async () => { + mocks.list.mockResolvedValue({ + enabled: true, + desktopPinningSupported: true, + cards: [ + card('a', { updatedAtMs: 2 }), + card('b', { updatedAtMs: 1, alwaysOnTop: false, desktopPinned: true }), + ], + }); + await render(); + expect(pinRows()).toHaveLength(2); + expect(pinSwitch(pinRows()[0]).checked).toBe(false); + expect(pinSwitch(pinRows()[1]).checked).toBe(true); + expect(pinRows()[1].textContent).toContain('features.desktopCards.pinnedOn'); + + await act(async () => pinSwitch(pinRows()[0]).click()); + expect(mocks.setDesktopPinned).toHaveBeenCalledWith('a', true); +}); + +it('follows host change events so the switch reflects the applied mode', async () => { + mocks.list.mockResolvedValue({ + enabled: true, + desktopPinningSupported: true, + cards: [card('a', { updatedAtMs: 2 })], + }); + await render(); + await act(async () => mocks.changed.forEach(listener => listener({ + cardId: 'a', + card: card('a', { updatedAtMs: 3, alwaysOnTop: false, desktopPinned: true }), + deleted: false, + }))); + expect(pinSwitch(pinRows()[0]).checked).toBe(true); + expect(pinRows()[0].textContent).toContain('features.desktopCards.pinnedOn'); +}); + +it('keeps the pin rows hidden when the host cannot pin', async () => { + mocks.list.mockResolvedValue({ enabled: true, cards: [card('a')] }); + await render(); + expect(pinRows()).toHaveLength(0); +}); + +it('renders nothing to pin and never reads cards while the feature is off', async () => { + mocks.cached = { enable_desktop_cards: false }; + mocks.list.mockResolvedValue({ enabled: false, desktopPinningSupported: true, cards: [card('a')] }); + await render(); + expect(pinRows()).toHaveLength(0); + expect(mocks.list).not.toHaveBeenCalled(); +}); + +it('reports a rejected pin change without flipping the switch', async () => { + mocks.list.mockResolvedValue({ + enabled: true, + desktopPinningSupported: true, + cards: [card('a')], + }); + mocks.setDesktopPinned.mockRejectedValue(new Error('Explorer unavailable')); + await render(); + await act(async () => pinSwitch(pinRows()[0]).click()); + expect(mocks.notifyError).toHaveBeenCalledWith('features.desktopCards.pinFailed'); + expect(pinSwitch(pinRows()[0]).checked).toBe(false); +}); diff --git a/src/web-ui/src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.tsx b/src/web-ui/src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.tsx index 9852f9df88..b5c587731d 100644 --- a/src/web-ui/src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/application/DesktopCardsSettingsSection.tsx @@ -2,14 +2,57 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { Switch } from '@openbitfun/ui'; import { ConfigLoadingState, ConfigPageRow, ConfigPageSection, ConfigRetryState } from '@/infrastructure/config/components/common'; import { aiExperienceConfigService } from '@/infrastructure/config/services/AIExperienceConfigService'; +import { + desktopCardAPI, + hasDesktopPinFailure, + isDesktopPinned, + type DesktopCardRecord, +} from '@/infrastructure/api/service-api/DesktopCardAPI'; import { useI18n } from '@/infrastructure/i18n'; import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { isTauriRuntime } from '@/infrastructure/runtime'; import { useNotification } from '@/shared/notification-system'; import { createLogger } from '@/shared/utils/logger'; import { useSettingsSectionAnchor } from '../shared/useSettingsSectionAnchor'; const log = createLogger('DesktopCardsSettingsSection'); +const sortCards = (cards: DesktopCardRecord[]): DesktopCardRecord[] => + [...cards].sort((a, b) => b.updatedAtMs - a.updatedAtMs); + +/** + * Reads the pinning capability from the host. Desktop cards are windows on this + * computer, so a surface that cannot reach them simply keeps the pin row hidden. + */ +function useDesktopCardPinning(active: boolean) { + const [supported, setSupported] = useState(false); + const [cards, setCards] = useState([]); + + useEffect(() => { + if (!active || !isTauriRuntime()) return; + let disposed = false; + void desktopCardAPI.list() + .then(list => { + if (disposed) return; + setSupported(list.desktopPinningSupported === true); + setCards(sortCards(list.cards)); + }) + .catch(error => log.warn('Failed to read desktop cards for pinning', error)); + const unlisten = desktopCardAPI.onChanged(payload => { + setCards(current => { + const rest = current.filter(card => card.id !== payload.cardId); + return payload.deleted || !payload.card ? rest : sortCards([...rest, payload.card]); + }); + }); + return () => { + disposed = true; + unlisten(); + }; + }, [active]); + + return { supported, cards }; +} + export default function DesktopCardsSettingsSection() { const { t } = useI18n('settings/runtime'); const notification = useNotification(); @@ -19,6 +62,8 @@ export default function DesktopCardsSettingsSection() { const [saving, setSaving] = useState(false); const [enabled, setEnabled] = useState(cachedSettings?.enable_desktop_cards); const saveInFlight = useRef(false); + const [pinBusyId, setPinBusyId] = useState(null); + const cardPinning = useDesktopCardPinning(enabled === true); const load = useCallback(async () => { setLoading(!cachedSettings); @@ -62,6 +107,20 @@ export default function DesktopCardsSettingsSection() { } }; + /** Hidden cards have no window, so this row is their only pinning entry point. */ + const handlePinnedChange = async (card: DesktopCardRecord) => { + if (pinBusyId !== null) return; + setPinBusyId(card.id); + try { + await desktopCardAPI.setDesktopPinned(card.id, !isDesktopPinned(card)); + } catch (error) { + log.warn('Failed to change desktop card pinning', { cardId: card.id, error }); + notification.error(t('features.desktopCards.pinFailed')); + } finally { + setPinBusyId(null); + } + }; + if (loading || loadFailed) { return ( @@ -88,6 +147,29 @@ export default function DesktopCardsSettingsSection() { aria-label={t('features.desktopCards.enable')} /> + {enabled === true && cardPinning.supported && cardPinning.cards.map(card => { + const pinned = isDesktopPinned(card); + return ( + + void handlePinnedChange(card)} + disabled={pinBusyId !== null} + aria-label={t('features.desktopCards.pinCard', { title: card.title })} + /> + + ); + })} ); } diff --git a/src/web-ui/src/infrastructure/api/generated/productControl.ts b/src/web-ui/src/infrastructure/api/generated/productControl.ts index fde570fb80..58c4082ee3 100644 --- a/src/web-ui/src/infrastructure/api/generated/productControl.ts +++ b/src/web-ui/src/infrastructure/api/generated/productControl.ts @@ -1,5 +1,5 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. -export const PRODUCT_CONTROL_GRAPH_DIGEST = "513e184cc2d93f183cdea258516f532caf58ac6400ef76dce9b54f6de0752627" as const; +export const PRODUCT_CONTROL_GRAPH_DIGEST = "6ae2eeaa19e6342f9dcf7ff33b7c0fa94547ee1c02fc1835f6f4471caab6fbb3" as const; export type ProductControlCapabilityId = "feature.ai-assistant" | "feature.agents" | "feature.personal-assistants" | "feature.projects" | "feature.files-editor" | "feature.terminal" | "feature.git" | "feature.code-review" | "feature.browser" | "feature.computer-use" | "feature.skills" | "feature.miniapps" | "feature.canvas" | "feature.tasks-automation" | "feature.insights" | "feature.ecosystem-compatibility" | "feature.remote-workspaces" | "feature.remote-connect" | "feature.detached-dispatch" | "feature.pages" | "feature.voice-input" | "feature.desktop-pet" | "feature.desktop-cards" | "setting.application.general" | "setting.application.appearance" | "setting.application.pet" | "setting.application.input" | "setting.application.shortcuts" | "setting.application.development" | "setting.ai.models" | "setting.ai.memory" | "setting.workspace.session" | "setting.workspace.worktrees" | "setting.tools.execution" | "setting.application.terminal" | "setting.tools.desktop-control" | "setting.tools.browser-control" | "setting.tools.automation" | "setting.tools.web-search" | "setting.tools.mcp" | "setting.tools.acp" | "setting.data.usage" | "setting.data.archived" | "setting.data.diagnostics"; diff --git a/src/web-ui/src/infrastructure/api/service-api/DesktopCardAPI.test.ts b/src/web-ui/src/infrastructure/api/service-api/DesktopCardAPI.test.ts new file mode 100644 index 0000000000..784445ba6c --- /dev/null +++ b/src/web-ui/src/infrastructure/api/service-api/DesktopCardAPI.test.ts @@ -0,0 +1,61 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { DesktopCardAPI, isDesktopPinned } from './DesktopCardAPI'; + +const invoke = vi.hoisted(() => vi.fn()); +vi.mock('./ApiClient', () => ({ api: { invoke } })); + +const legacyCard = { + id: 'card-1', title: 'Note', template: { kind: 'note', text: 'hello' }, + visible: true, alwaysOnTop: true, createdAtMs: 1, updatedAtMs: 1, +}; + +describe('DesktopCardAPI desktop pinning compatibility', () => { + const cards = new DesktopCardAPI(); + beforeEach(() => invoke.mockReset()); + + it.each([undefined, false])('refuses an unsupported host without mutating its window (%s)', async supported => { + invoke.mockResolvedValue({ ...legacyCard, desktopPinningSupported: supported }); + await expect(cards.setDesktopPinned('card-1', true)).rejects.toThrow('requires a Windows host'); + expect(invoke.mock.calls).toEqual([['desktop_card_get', { request: { cardId: 'card-1' } }]]); + }); + + it.each([true, false])('negotiates before sending the additive request (%s)', async pinned => { + const result = { ...legacyCard, alwaysOnTop: false, desktopPinned: pinned }; + invoke.mockResolvedValueOnce({ ...legacyCard, desktopPinningSupported: true }).mockResolvedValueOnce(result); + await expect(cards.setDesktopPinned('card-1', pinned)).resolves.toEqual(result); + expect(invoke.mock.calls).toEqual([ + ['desktop_card_get', { request: { cardId: 'card-1' } }], + ['desktop_card_set_always_on_top', { request: { cardId: 'card-1', alwaysOnTop: false, desktopPinned: pinned } }], + ]); + }); + + it('keeps the old always-on-top payload unchanged', async () => { + invoke.mockResolvedValue(legacyCard); + await cards.setAlwaysOnTop('card-1', true); + expect(invoke).toHaveBeenCalledWith('desktop_card_set_always_on_top', { + request: { cardId: 'card-1', alwaysOnTop: true }, + }); + }); + + it.each([{ supported: true }, { supported: false }, {}])( + 'reads the pinning capability from the list payload without dropping cards (%o)', + async payload => { + invoke.mockResolvedValue({ + enabled: true, + cards: [{ ...legacyCard, desktopPinned: true }], + ...('supported' in payload ? { desktopPinningSupported: payload.supported } : {}), + }); + const list = await cards.list(); + expect(invoke).toHaveBeenCalledWith('desktop_card_list', { request: {} }); + expect(list.desktopPinningSupported).toBe('supported' in payload ? payload.supported : false); + expect(list.cards).toHaveLength(1); + expect(list.cards[0].desktopPinned).toBe(true); + }, + ); + + it('treats desktop pinning and global topmost as exclusive', () => { + expect(isDesktopPinned({ desktopPinned: true, alwaysOnTop: false })).toBe(true); + expect(isDesktopPinned({ desktopPinned: true, alwaysOnTop: true })).toBe(false); + expect(isDesktopPinned({ alwaysOnTop: false })).toBe(false); + }); +}); diff --git a/src/web-ui/src/infrastructure/api/service-api/DesktopCardAPI.ts b/src/web-ui/src/infrastructure/api/service-api/DesktopCardAPI.ts index bfeafe36ec..d0dfa66ceb 100644 --- a/src/web-ui/src/infrastructure/api/service-api/DesktopCardAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/DesktopCardAPI.ts @@ -127,6 +127,16 @@ export interface DesktopCardRecord { position?: { x: number; y: number }; visible: boolean; alwaysOnTop: boolean; + /** Windows host presentation preference; absent on legacy records. */ + desktopPinned?: boolean; + /** + * Set by the Windows host when it had to unpin the card because the desktop + * could not take it back (for example after Explorer restarted). Cleared by + * the next explicit stacking change. + */ + desktopPinFailure?: string; + /** Runtime capability advertised by get(), not a persisted preference. */ + desktopPinningSupported?: boolean; origin?: { sessionId?: string; agentType?: string; workspacePath?: string }; createdAtMs: number; updatedAtMs: number; @@ -136,6 +146,8 @@ export interface DesktopCardRecord { export interface DesktopCardList { enabled: boolean; cards: DesktopCardRecord[]; + /** Host capability from `desktop_card_list`; absent on older hosts. */ + desktopPinningSupported?: boolean; } export interface DesktopCardChangedPayload { @@ -148,6 +160,20 @@ export interface DesktopCardStatePayload { enabled: boolean; } +/** Desktop pinning and global always-on-top are exclusive on the host. */ +export function isDesktopPinned( + card: Pick, +): boolean { + return card.desktopPinned === true && !card.alwaysOnTop; +} + +/** True when the host unpinned the card on its own and the user should know. */ +export function hasDesktopPinFailure( + card: Pick, +): boolean { + return typeof card.desktopPinFailure === 'string' && !isDesktopPinned(card); +} + /** Desktop cards are host windows on this computer; every command stays controller-local. */ export class DesktopCardAPI { private async invoke(command: string, request: Record): Promise { @@ -163,6 +189,7 @@ export class DesktopCardAPI { return { enabled: result?.enabled !== false, cards: Array.isArray(result?.cards) ? result.cards : [], + desktopPinningSupported: result?.desktopPinningSupported === true, }; } @@ -190,6 +217,16 @@ export class DesktopCardAPI { return this.invoke('desktop_card_set_always_on_top', { cardId, alwaysOnTop }); } + async setDesktopPinned(cardId: string, desktopPinned: boolean): Promise { + const card = await this.get(cardId); + if (card.desktopPinningSupported !== true) { + throw new Error('Desktop pinning requires a Windows host that supports this feature.'); + } + return this.invoke('desktop_card_set_always_on_top', { + cardId, alwaysOnTop: false, desktopPinned, + }); + } + onChanged(callback: (payload: DesktopCardChangedPayload) => void): () => void { return api.listen(DESKTOP_CARD_CHANGED_EVENT, callback); } diff --git a/src/web-ui/src/locales/en-US/components.json b/src/web-ui/src/locales/en-US/components.json index fb6e84e36d..7f48142a00 100644 --- a/src/web-ui/src/locales/en-US/components.json +++ b/src/web-ui/src/locales/en-US/components.json @@ -667,6 +667,8 @@ "loading": "Loading…", "loadFailed": "This card could not be loaded.", "unsupportedTemplate": "This card needs a newer version of OpenBitFun.", + "stackingFailed": "Could not change the display mode: {{error}}", + "pinRecoveryFailed": "Could not keep this card on the desktop, so it is shown as a normal window. Pin it again from the menu.", "updated": "Updated {{time}}", "updatedWithWarning": "Updated {{time}}, some data may be missing", "refreshFailed": "Refresh failed: {{error}}", @@ -675,7 +677,8 @@ "refresh": "Refresh", "openLink": "Open link", "openSession": "Open source session", - "alwaysOnTop": "Keep on top", + "alwaysOnTop": "Always on top (all apps)", + "desktopPinned": "Pin to desktop", "hide": "Hide card", "delete": "Delete card" }, diff --git a/src/web-ui/src/locales/en-US/scenes/capabilities.json b/src/web-ui/src/locales/en-US/scenes/capabilities.json index 46e5658090..317bb86b1c 100644 --- a/src/web-ui/src/locales/en-US/scenes/capabilities.json +++ b/src/web-ui/src/locales/en-US/scenes/capabilities.json @@ -374,7 +374,8 @@ "agent-cards": "Create countdown, checklist, note, progress, metrics, chart, scheduled-job, and custom cards on request or during a task, optionally refreshed from an HTTP endpoint or a local command", "home-management": "See every card in the Home Desktop cards section, and show, hide, or delete individual cards", "card-actions": "Refresh data, check off list items, toggle always-on-top, open the link, or return to the source session from a card", - "drag-restore": "Drag cards anywhere on the desktop and resize them from their edges or corners; they disappear when OpenBitFun closes and return with the same position and size when it reopens" + "drag-restore": "Drag cards anywhere on the desktop and resize them from their edges or corners; they disappear when OpenBitFun closes and return with the same position and size when it reopens", + "desktop-pinning": "Pin a card to the Windows desktop from the card menu, the Home card list, or Settings, including hidden cards" } } }, diff --git a/src/web-ui/src/locales/en-US/scenes/personal-overview.json b/src/web-ui/src/locales/en-US/scenes/personal-overview.json index 7efcfff1da..e91dff0ab4 100644 --- a/src/web-ui/src/locales/en-US/scenes/personal-overview.json +++ b/src/web-ui/src/locales/en-US/scenes/personal-overview.json @@ -82,6 +82,10 @@ "hidden": "Hidden", "show": "Show on desktop", "hide": "Hide from desktop", + "pin": "Pin to desktop", + "unpin": "Unpin from desktop", + "pinned": "Pinned to desktop", + "pinLost": "Unpinned: desktop unavailable", "delete": "Delete card", "deleteConfirmTitle": "Delete card", "deleteConfirmMessage": "Delete \"{{title}}\"? This cannot be undone.", diff --git a/src/web-ui/src/locales/en-US/settings/runtime.json b/src/web-ui/src/locales/en-US/settings/runtime.json index b08fdaf721..660056f8b0 100644 --- a/src/web-ui/src/locales/en-US/settings/runtime.json +++ b/src/web-ui/src/locales/en-US/settings/runtime.json @@ -46,7 +46,12 @@ "subtitle": "Small cards outside the main window for reminders, PR status, progress, weather, and other things worth a glance", "enable": "Enable desktop cards", "description": "When off, cards are hidden and the agent can no longer create or update them. Existing cards are kept.", - "unsupported": "Update this host to manage desktop cards." + "unsupported": "Update this host to manage desktop cards.", + "pinnedOn": "Pinned to the desktop, above the icons and behind other apps", + "pinnedOff": "Not pinned to the desktop", + "pinRecoveryFailed": "Unpinned because the Windows desktop was unavailable. Turn this on to pin it again.", + "pinCard": "Pin {{title}} to the desktop", + "pinFailed": "Could not change the pin state. Try again." }, "workspaceSearch": { "title": "Accelerated workspace search", diff --git a/src/web-ui/src/locales/zh-CN/components.json b/src/web-ui/src/locales/zh-CN/components.json index 0342e72646..1421793632 100644 --- a/src/web-ui/src/locales/zh-CN/components.json +++ b/src/web-ui/src/locales/zh-CN/components.json @@ -667,6 +667,8 @@ "loading": "加载中…", "loadFailed": "无法加载此卡片。", "unsupportedTemplate": "此卡片需要更新版本的 OpenBitFun。", + "stackingFailed": "无法切换显示模式:{{error}}", + "pinRecoveryFailed": "无法将此卡片保持在桌面上,已改为普通窗口显示。可在菜单中重新固定。", "updated": "更新于{{time}}", "updatedWithWarning": "更新于{{time}},部分数据可能缺失", "refreshFailed": "刷新失败:{{error}}", @@ -675,7 +677,8 @@ "refresh": "刷新", "openLink": "打开链接", "openSession": "打开来源会话", - "alwaysOnTop": "保持置顶", + "alwaysOnTop": "全局置顶", + "desktopPinned": "固定桌面", "hide": "隐藏卡片", "delete": "删除卡片" }, diff --git a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json index e8b657e4bb..93280d1ce4 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json @@ -374,7 +374,8 @@ "agent-cards": "按需求或在任务过程中创建倒计时、清单、便签、进度、指标、图表、定时任务和自定义卡片,可定时从 HTTP 接口或本机命令刷新数据", "home-management": "在首页“小卡片”区查看全部卡片,并显示、隐藏或删除单张卡片", "card-actions": "在卡片上刷新数据、勾选清单项、切换置顶、打开链接或回到来源会话", - "drag-restore": "拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复" + "drag-restore": "拖动卡片到桌面任意位置,拖动卡片边缘或四角调整大小;关闭 OpenBitFun 时卡片消失,重新打开后按原位置和大小恢复", + "desktop-pinning": "在卡片菜单、首页卡片列表或设置里把卡片固定到 Windows 桌面,隐藏的卡片同样可以切换固定状态" } } }, diff --git a/src/web-ui/src/locales/zh-CN/scenes/personal-overview.json b/src/web-ui/src/locales/zh-CN/scenes/personal-overview.json index ee174c15dc..524a10c3bf 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/personal-overview.json +++ b/src/web-ui/src/locales/zh-CN/scenes/personal-overview.json @@ -82,6 +82,10 @@ "hidden": "已隐藏", "show": "在桌面显示", "hide": "从桌面隐藏", + "pin": "固定到桌面", + "unpin": "取消固定", + "pinned": "已固定桌面", + "pinLost": "桌面不可用,已取消固定", "delete": "删除卡片", "deleteConfirmTitle": "删除卡片", "deleteConfirmMessage": "删除“{{title}}”?此操作无法撤销。", diff --git a/src/web-ui/src/locales/zh-CN/settings/runtime.json b/src/web-ui/src/locales/zh-CN/settings/runtime.json index bccf805328..66e5d5154d 100644 --- a/src/web-ui/src/locales/zh-CN/settings/runtime.json +++ b/src/web-ui/src/locales/zh-CN/settings/runtime.json @@ -46,7 +46,12 @@ "subtitle": "在主窗口之外显示提醒、PR 状态、进度、天气等值得随时看一眼的小卡片", "enable": "启用小卡片", "description": "关闭后卡片会隐藏,智能体也无法再创建或更新卡片,已有卡片会保留。", - "unsupported": "请更新当前主机后再管理小卡片。" + "unsupported": "请更新当前主机后再管理小卡片。", + "pinnedOn": "已固定到桌面,位于图标之上并在其他应用之下", + "pinnedOff": "未固定到桌面", + "pinRecoveryFailed": "Windows 桌面不可用,已取消固定。开启即可重新固定。", + "pinCard": "把“{{title}}”固定到桌面", + "pinFailed": "无法切换固定状态,请重试。" }, "workspaceSearch": { "title": "加速工作区搜索", diff --git a/src/web-ui/src/locales/zh-TW/components.json b/src/web-ui/src/locales/zh-TW/components.json index 15a6a94063..475a93bf2a 100644 --- a/src/web-ui/src/locales/zh-TW/components.json +++ b/src/web-ui/src/locales/zh-TW/components.json @@ -667,6 +667,8 @@ "loading": "載入中…", "loadFailed": "無法載入此卡片。", "unsupportedTemplate": "此卡片需要更新版本的 OpenBitFun。", + "stackingFailed": "無法切換顯示模式:{{error}}", + "pinRecoveryFailed": "無法將此卡片保持在桌面上,已改為一般視窗顯示。可在選單中重新固定。", "updated": "更新於{{time}}", "updatedWithWarning": "更新於{{time}},部分資料可能缺失", "refreshFailed": "重新整理失敗:{{error}}", @@ -675,7 +677,8 @@ "refresh": "重新整理", "openLink": "開啟連結", "openSession": "開啟來源會話", - "alwaysOnTop": "保持置頂", + "alwaysOnTop": "全域置頂", + "desktopPinned": "固定桌面", "hide": "隱藏卡片", "delete": "刪除卡片" }, diff --git a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json index 0516ec948b..643cf632fd 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json @@ -374,7 +374,8 @@ "agent-cards": "按需求或在任務過程中創建倒計時、清單、便簽、進度、指標、圖表、定時任務和自定義卡片,可定時從 HTTP 接口或本機命令重新整理數據", "home-management": "在首頁“小卡片”區查看全部卡片,並顯示、隱藏或刪除單張卡片", "card-actions": "在卡片上重新整理數據、勾選清單項、切換置頂、打開鏈接或回到來源工作階段", - "drag-restore": "拖動卡片到桌面任意位置,拖動卡片邊緣或四角調整大小;關閉 OpenBitFun 時卡片消失,重新打開後按原位置和大小恢復" + "drag-restore": "拖動卡片到桌面任意位置,拖動卡片邊緣或四角調整大小;關閉 OpenBitFun 時卡片消失,重新打開後按原位置和大小恢復", + "desktop-pinning": "在卡片選單、首頁卡片列表或設定裡把卡片釘選到 Windows 桌面,隱藏的卡片同樣可以切換釘選狀態" } } }, diff --git a/src/web-ui/src/locales/zh-TW/scenes/personal-overview.json b/src/web-ui/src/locales/zh-TW/scenes/personal-overview.json index cd68800fd2..0be6b29bf1 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/personal-overview.json +++ b/src/web-ui/src/locales/zh-TW/scenes/personal-overview.json @@ -82,6 +82,10 @@ "hidden": "已隱藏", "show": "在桌面顯示", "hide": "從桌面隱藏", + "pin": "釘選到桌面", + "unpin": "取消釘選", + "pinned": "已釘選桌面", + "pinLost": "桌面無法使用,已取消釘選", "delete": "刪除卡片", "deleteConfirmTitle": "刪除卡片", "deleteConfirmMessage": "刪除「{{title}}」?此操作無法復原。", diff --git a/src/web-ui/src/locales/zh-TW/settings/runtime.json b/src/web-ui/src/locales/zh-TW/settings/runtime.json index 9c48a03d48..5f47b35b7e 100644 --- a/src/web-ui/src/locales/zh-TW/settings/runtime.json +++ b/src/web-ui/src/locales/zh-TW/settings/runtime.json @@ -46,7 +46,12 @@ "subtitle": "在主視窗之外顯示提醒、PR 狀態、進度、天氣等值得隨時看一眼的小卡片", "enable": "啟用小卡片", "description": "關閉後卡片會隱藏,智慧體也無法再建立或更新卡片,現有卡片會保留。", - "unsupported": "請更新目前主機後再管理小卡片。" + "unsupported": "請更新目前主機後再管理小卡片。", + "pinnedOn": "已釘選到桌面,位於圖示之上並在其他應用程式之下", + "pinnedOff": "未釘選到桌面", + "pinRecoveryFailed": "Windows 桌面無法使用,已取消釘選。開啟即可重新釘選。", + "pinCard": "將「{{title}}」釘選到桌面", + "pinFailed": "無法切換釘選狀態,請重試。" }, "workspaceSearch": { "title": "加速工作區搜尋",