diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index fbbd04fcd0..7fa2dcfaae 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -1,9 +1,9 @@ # OpenBitFun 功能与设置目录 / OpenBitFun Features & Settings -OpenBitFun Playbook 当前包含 **24 个功能**和 **24 个设置页**,共 **48 个**用户可理解的条目、**369 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 +OpenBitFun Playbook 当前包含 **24 个功能**和 **24 个设置页**,共 **48 个**用户可理解的条目、**370 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 -OpenBitFun Playbook currently contains **24 features**, **24 settings pages**, and **369** source-backed sub-capabilities across **48** 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 **24 features**, **24 settings pages**, and **370** source-backed sub-capabilities across **48** 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 @@ -27,20 +27,20 @@ OpenBitFun Playbook currently contains **24 features**, **24 settings pages**, a - Generated per-item interaction audit: `docs/interactive-capabilities/technical/product-control-open-audit.json` - Generated low-level audit map: `docs/interactive-capabilities/technical/tauri-command-map.json` -说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **703** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 +说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **704** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 -Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **703** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes. +Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **704** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes. ## 控制边界 / Control boundary -- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **63**、委托 **74**、需交互 **232**、不支持 **0**。 +- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **63**、委托 **74**、需交互 **233**、不支持 **0**。 - 稳定行为声明为带 JSON 输入契约的 `operations` 或 `options`,并绑定原生产品控制 Provider;智能体不接触原始 Tauri Command。 -- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 369 项子能力都不会写入 system prompt。 +- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 370 项子能力都不会写入 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 **63 direct**, **74 delegated**, **232 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 **63 direct**, **74 delegated**, **233 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 369 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 370 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 3d70f69f28..376c5cce68 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": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", + "digest": "6a6de5f67359bdd2aead1692c4afd1b748e601045004dc140dd73b92342dd2bc", "ownerDigest": "6f0746578f3c56479f7c289bb05395dfe6917042f4d419de8c9a2f719d31f815", "searchAcceptance": [ { @@ -187,11 +187,11 @@ "features": 24, "settings": 24, "userFacing": 48, - "documentedItems": 369, + "documentedItems": 370, "controlCoverage": { "direct": 63, "delegated": 74, - "interactive": 232, + "interactive": 233, "unsupported": 0 } }, @@ -18865,6 +18865,7 @@ "id": "setting.tools.desktop-control:query", "capabilityId": "setting.tools.desktop-control", "itemIds": [ + "external-control", "permissions", "safety-posture" ], @@ -18907,6 +18908,52 @@ "pageId": "tools.desktop-control" } }, + { + "id": "setting.tools.desktop-control:open:external-control", + "capabilityId": "setting.tools.desktop-control", + "itemIds": [ + "external-control" + ], + "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": "visualSelection", + "presentationTarget": { + "kind": "settings", + "pageId": "tools.desktop-control" + } + }, { "id": "setting.tools.desktop-control:open:permissions", "capabilityId": "setting.tools.desktop-control", @@ -35578,6 +35625,19 @@ "Locking down desktop input during regular coding: turn off Allow desktop control on this page—agents immediately lose desktop control even if OS permissions remain granted." ], "items": [ + { + "id": "external-control", + "titleZh": "为本机集成授权工作区", + "titleEn": "Authorize workspaces for local integrations", + "descriptionZh": "启用本机 HTTP 接口,为每个集成创建或撤销令牌。外部任务在桌面会话中运行。", + "descriptionEn": "Enable local HTTP access and issue or revoke workspace-scoped integration tokens. Submitted tasks run in desktop sessions.", + "control": { + "kind": "open", + "reasonCode": "visualSelection", + "reasonZh": "用户需要在桌面设置中选择此集成可以访问的工作区,并复制仅在创建时显示一次的令牌。", + "reasonEn": "In Desktop settings, the user chooses which workspaces the integration can access and copies the token while it is visible at creation." + } + }, { "id": "permissions", "titleZh": "查看“允许桌面控制”开关及“辅助功能”、“屏幕录制”系统授权状态并完成授权", @@ -35675,6 +35735,8 @@ "Shows live grant status for both Accessibility (mouse/keyboard input) and Screen Recording (visual capture)", "One-click permission request or direct jump into your operating system’s Privacy & Security settings", "Works alongside single-window App Sharing, live control status cards, and immediate stop controls", + "为本机集成授权工作区", + "Authorize workspaces for local integrations", "查看“允许桌面控制”开关及“辅助功能”、“屏幕录制”系统授权状态并完成授权", "Inspect Allow desktop control plus Accessibility and Screen Recording grants and authorize in OS settings", "结合应用级总开关、单窗口共享与主机边界安全管控桌面操作", diff --git a/docs/interactive-capabilities/capabilities/setting.tools.desktop-control.md b/docs/interactive-capabilities/capabilities/setting.tools.desktop-control.md index 9deb54e348..2b4e61e1de 100644 --- a/docs/interactive-capabilities/capabilities/setting.tools.desktop-control.md +++ b/docs/interactive-capabilities/capabilities/setting.tools.desktop-control.md @@ -24,6 +24,10 @@ Manage the Allow desktop control master switch for native desktop GUI automation ## 完整功能清单 / Everything included +- **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 为本机集成授权工作区 + - Authorize workspaces for local integrations + - 说明:启用本机 HTTP 接口,为每个集成创建或撤销令牌。外部任务在桌面会话中运行。 + - Why & how: Enable local HTTP access and issue or revoke workspace-scoped integration tokens. Submitted tasks run in desktop sessions. - **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 查看“允许桌面控制”开关及“辅助功能”、“屏幕录制”系统授权状态并完成授权 - Inspect Allow desktop control plus Accessibility and Screen Recording grants and authorize in OS settings - 说明:在 macOS 上需同时授予“辅助功能”(用于模拟点击与键盘输入)和“屏幕录制”(用于截取目标画面)才能完整运行桌面自动化;未就绪时可直接点击“系统设置”跳转授权。 diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index 802073f3cf..8bdb322675 100644 --- a/docs/interactive-capabilities/technical/product-control-open-audit.json +++ b/docs/interactive-capabilities/technical/product-control-open-audit.json @@ -1,13 +1,13 @@ { "schemaVersion": 1, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", - "count": 232, + "catalogDigest": "6a6de5f67359bdd2aead1692c4afd1b748e601045004dc140dd73b92342dd2bc", + "count": 233, "reasonCounts": { "externalAuth": 4, "secretEntry": 6, "unstructuredInteraction": 195, - "visualSelection": 27 + "visualSelection": 28 }, "entries": [ { @@ -3425,6 +3425,22 @@ "command:browser_control_enable_default_cdp" ] }, + { + "capabilityId": "setting.tools.desktop-control", + "itemId": "external-control", + "titleZh": "为本机集成授权工作区", + "titleEn": "Authorize workspaces for local integrations", + "reasonCode": "visualSelection", + "reasonZh": "用户需要在桌面设置中选择此集成可以访问的工作区,并复制仅在创建时显示一次的令牌。", + "reasonEn": "In Desktop settings, the user chooses which workspaces the integration can access and copies the token while it is visible at creation.", + "presentationTarget": { + "kind": "settings", + "pageId": "tools.desktop-control" + }, + "evidence": [ + "command:desktop_external_control" + ] + }, { "capabilityId": "setting.tools.desktop-control", "itemId": "permissions", diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 89a1d9c7f8..8ef16f1d26 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -1,11 +1,11 @@ { "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", - "commandCount": 703, + "catalogDigest": "6a6de5f67359bdd2aead1692c4afd1b748e601045004dc140dd73b92342dd2bc", + "commandCount": 704, "coverage": { - "commandCount": 703, - "documentedCommandCount": 637, + "commandCount": 704, + "documentedCommandCount": 638, "implementationCommandCount": 66, "implementationDigest": "22a8353380694e1246a4b15ec83c4f5a10c781fd5dfb0a0fb9d2a135e53380b6" }, @@ -1716,7 +1716,7 @@ "visibility": "documented", "rustPath": "api::agentic_api::create_session", "sourceFile": "src/apps/desktop/src/api/agentic_api.rs", - "signature": "fn create_session( coordinator: State<'_, Arc>, app_state: State<'_, AppState>, runtime: State<'_, DesktopRuntimeContext>, mut request: CreateSessionRequest, ) -> Result", + "signature": "fn create_session( coordinator: State<'_, Arc>, app_state: State<'_, AppState>, runtime: State<'_, DesktopRuntimeContext>, request: CreateSessionRequest, ) -> Result", "remoteWorkspacePolicy": "LegacyUnaudited" }, { @@ -2155,6 +2155,22 @@ "signature": "fn desktop_card_set_visible( cards: State<'_, Arc>, request: DesktopCardSetVisibleRequest, ) -> Result", "remoteWorkspacePolicy": "LocalOnly" }, + { + "id": "desktop_external_control", + "moduleId": "external_control", + "capabilityId": "setting.tools.desktop-control", + "capabilityIds": [ + "setting.tools.desktop-control" + ], + "documentedItemIds": [ + "setting.tools.desktop-control:external-control" + ], + "visibility": "documented", + "rustPath": "external_control::desktop_external_control", + "sourceFile": "src/apps/desktop/src/external_control.rs", + "signature": "fn desktop_external_control( webview: tauri::Webview, app: AppHandle, request: ControllerSettingsRequest, ) -> Result", + "remoteWorkspacePolicy": "WorkspaceAgnostic" + }, { "id": "dispatch_answer", "moduleId": "dispatch", diff --git a/src/apps/desktop/README.md b/src/apps/desktop/README.md index 2b9a71221f..c38e25e08c 100644 --- a/src/apps/desktop/README.md +++ b/src/apps/desktop/README.md @@ -1150,3 +1150,30 @@ directory together with `workspace_data.json` in a full backup. A workspace meta export does not embed image bytes; missing assets display the default icon with a load warning and preserve the saved reference. Unreferenced assets are retained; resetting an icon does not delete another record's shared image. Unknown icon versions remain intact. + +## Control Desktop from a local application + +In **Settings → Browser & desktop control → External control**, enable local HTTP access. Choose a listening port (default 38371), name the integration, select its local project workspaces and create a token. Copy the token while it is displayed. Enter a browser origin only for a web page connecting directly. For a task board with its own backend, keep the token in that backend. Each integration can access only the sessions it creates. Revoke its token in the same settings section. + +Send requests to the API address shown in Settings with an `Authorization: Bearer ` header. The listener binds to IPv4 loopback. The workspace ID comes from the catalog on this desktop. The following example uses a token supplied through the environment. + +```sh +base=http://127.0.0.1:38371/v1 +curl -sS -H "Authorization: Bearer $OBF_TOKEN" "$base/workspaces" + +curl -sS -H "Authorization: Bearer $OBF_TOKEN" -H 'Content-Type: application/json' \ + -d '{"workspaceId":"WORKSPACE_ID","title":"Review issue 17","prompt":"Summarize the affected code","idempotencyKey":"issue-17-attempt-1"}' \ + "$base/turns" +``` + +| Request | Behavior | +| --- | --- | +| `GET /v1/capabilities` | Read the API version, execution host and supported operations. | +| `GET /v1/workspaces` | List eligible local projects granted to this token. | +| `POST /v1/turns` | Create a regular desktop session and start its first turn. Returns HTTP 202 with `sessionId`, `turnId`, `workspaceId` and admission state. To continue a session, send its `sessionId` and a fresh idempotency key, omitting the title. | +| `GET /v1/turns/{turnId}` | Read current status, waiting reason through `awaiting_approval` or `awaiting_input`, and the terminal reply or error when available. | +| `GET /v1/turns/{turnId}/events` | Subscribe to SSE `snapshot` events with the same bearer header. Use streaming fetch in a browser. Reconnect to receive the current snapshot. | +| `POST /v1/turns/{turnId}/cancel` | Request cancellation of this turn. Read status to observe settlement. | +| `POST /v1/turns/{turnId}/open` | Bring the desktop window forward and request navigation to the owning session. | + +Repeat a submission with the same key and payload after a lost response. Reusing the key for different content returns HTTP 409. A busy session also returns 409. A browser disconnect leaves an accepted turn running in Desktop. If Desktop exits during handoff, `outcome_unknown` preserves the original IDs for inspection. Desktop does not replay the prompt automatically. Busy work retains Desktop's normal tool and question handling. Remote workspaces, peer hosts and detached workers are outside this listener's execution scope. diff --git a/src/apps/desktop/src/api/agentic_api.rs b/src/apps/desktop/src/api/agentic_api.rs index a438f2403b..517ee73474 100644 --- a/src/apps/desktop/src/api/agentic_api.rs +++ b/src/apps/desktop/src/api/agentic_api.rs @@ -1606,6 +1606,21 @@ pub async fn create_session( coordinator: State<'_, Arc>, app_state: State<'_, AppState>, runtime: State<'_, DesktopRuntimeContext>, + request: CreateSessionRequest, +) -> Result { + create_desktop_session( + coordinator.inner(), + app_state.inner(), + runtime.inner(), + request, + ) + .await +} + +pub(crate) async fn create_desktop_session( + coordinator: &ConversationCoordinator, + app_state: &AppState, + runtime: &DesktopRuntimeContext, mut request: CreateSessionRequest, ) -> Result { fn norm_conn(s: Option) -> Option { @@ -1863,7 +1878,7 @@ pub async fn create_session( .as_deref() .ok_or_else(|| "Idempotent worktree session requires a session ID".to_string())?; let effective_path = desktop_session_storage_root( - &coordinator, + coordinator, project_workspace_id.as_deref(), Some(&project_workspace_path), remote_conn.as_deref(), @@ -1898,7 +1913,7 @@ pub async fn create_session( .as_deref() .ok_or_else(|| "Idempotent Review session requires a session ID".to_string())?; let effective_path = desktop_session_storage_root( - &coordinator, + coordinator, project_workspace_id.as_deref(), Some(&project_workspace_path), remote_conn.as_deref(), diff --git a/src/apps/desktop/src/appearance.rs b/src/apps/desktop/src/appearance.rs index 1e4301a298..281c3d1dcf 100644 --- a/src/apps/desktop/src/appearance.rs +++ b/src/apps/desktop/src/appearance.rs @@ -711,6 +711,7 @@ pub fn create_main_window( let build_started_at = Instant::now(); match builder.build() { Ok(window) => { + tauri::async_runtime::spawn(crate::external_control::restore(app_handle.clone())); #[cfg(target_os = "linux")] if let Err(error) = crate::linux_browser_layout::install(&window) { error!("Failed to install browser WebView layout: {error}"); diff --git a/src/apps/desktop/src/external_control.rs b/src/apps/desktop/src/external_control.rs new file mode 100644 index 0000000000..163b6d9fc3 --- /dev/null +++ b/src/apps/desktop/src/external_control.rs @@ -0,0 +1,240 @@ +//! Opt-in loopback control of the Runtime owned by this desktop instance. +mod http; +mod store; +mod turns; + +use crate::api::app_state::AppState; +use openbitfun_core::service::workspace::{WorkspaceInfo, WorkspaceKind}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::{collections::BTreeSet, path::PathBuf, sync::Arc}; +use store::{Grant, Settings, Store}; +use tauri::{AppHandle, Manager}; +use tokio::{ + net::TcpListener, + sync::{oneshot, Mutex}, +}; +use uuid::Uuid; + +pub(super) const PORT: u16 = 38371; + +struct Listener { + generation: Uuid, + _shutdown: oneshot::Sender<()>, +} + +struct Inner { + settings: Settings, + listener: Option, + listener_error: Option, +} + +pub(crate) struct DesktopController { + storage: Result, + inner: Mutex, + instance: Uuid, + admission: Mutex<()>, +} + +impl DesktopController { + pub(crate) fn new(root: PathBuf) -> Arc { + let source = Store::open(root).and_then(|store| Ok((store.settings()?, store))); + let (settings, storage) = match source { + Ok((settings, store)) => (settings, Ok(store)), + Err(e) => (Settings::default(), Err(e)), + }; + Arc::new(Self { + storage, + inner: Mutex::new(Inner { + settings, + listener: None, + listener_error: None, + }), + instance: Uuid::new_v4(), + admission: Mutex::new(()), + }) + } + + fn store(&self) -> Result<&Store, String> { + self.storage.as_ref().map_err(Clone::clone) + } + + async fn listen(&self, app: AppHandle, port: u16) -> Result { + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port)) + .await + .map_err(|e| format!("Cannot listen on 127.0.0.1:{port}: {e}"))?; + let generation = Uuid::new_v4(); + let router = http::router(app.clone(), generation, port); + let (shutdown, end) = oneshot::channel(); + tauri::async_runtime::spawn(async move { + let result = axum::serve(listener, router) + .with_graceful_shutdown(async { + let _ = end.await; + }) + .await; + let controller = app.state::>(); + let mut inner = controller.inner.lock().await; + if inner + .listener + .as_ref() + .is_some_and(|l| l.generation == generation) + { + inner.listener = None; + inner.listener_error = Some( + result + .err() + .map(|e| e.to_string()) + .unwrap_or_else(|| "Controller stopped".into()), + ); + } + }); + Ok(Listener { + generation, + _shutdown: shutdown, + }) + } +} + +pub(crate) async fn restore(app: AppHandle) { + let host = app.state::>(); + let mut inner = host.inner.lock().await; + if inner.settings.enabled && inner.listener.is_none() { + match host + .listen(app.clone(), inner.settings.port.unwrap_or(PORT)) + .await + { + Ok(listener) => inner.listener = Some(listener), + Err(error) => { + log::warn!("Desktop external controller unavailable: {error}"); + inner.listener_error = Some(error); + } + } + } +} + +fn eligible(w: &WorkspaceInfo) -> bool { + w.workspace_kind == WorkspaceKind::Normal && w.worktree.as_ref().is_none_or(|tree| tree.is_main) +} + +async fn workspaces(app: &AppHandle) -> Vec { + app.state::() + .workspace_service + .list_workspace_infos() + .await + .into_iter() + .filter(eligible) + .collect() +} + +#[derive(Deserialize)] +#[serde( + tag = "operation", + rename_all = "camelCase", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +pub(crate) enum ControllerSettingsRequest { + Status, + SetEnabled { + enabled: bool, + port: Option, + }, + Issue { + name: String, + workspace_ids: BTreeSet, + origin: Option, + }, + Revoke { + id: Uuid, + }, +} + +fn browser_origin(value: &str) -> Result { + let url = reqwest::Url::parse(value).map_err(|_| "Invalid browser origin")?; + let origin = url.origin().ascii_serialization(); + if !matches!(url.scheme(), "https" | "http") || origin != value.trim_end_matches('/') { + return Err("Enter an exact HTTP or HTTPS origin".into()); + } + Ok(origin) +} + +#[tauri::command] +pub(crate) async fn desktop_external_control( + webview: tauri::Webview, + app: AppHandle, + request: ControllerSettingsRequest, +) -> Result { + if webview.label() != "main" { + return Err("Desktop controller settings require the main webview".into()); + } + let host = app.state::>(); + let store = host.store()?; + let catalog = workspaces(&app).await; + let mut inner = host.inner.lock().await; + let mut next = inner.settings.clone(); + let mut token = None; + match request { + ControllerSettingsRequest::Status => {} + ControllerSettingsRequest::SetEnabled { enabled, port } => { + let port = port.map(|p| p.get()).or(next.port).unwrap_or(PORT); + let listener = + if enabled && (inner.listener.is_none() || next.port.unwrap_or(PORT) != port) { + Some(host.listen(app.clone(), port).await?) + } else { + None + }; + next.enabled = enabled; + next.port = Some(port); + store.save_settings(&next)?; + if !enabled { + inner.listener = None; + } else if listener.is_some() { + inner.listener = listener; + } + inner.listener_error = None; + } + ControllerSettingsRequest::Issue { + name, + workspace_ids, + origin, + } => { + if name.trim().is_empty() + || name.len() > 128 + || workspace_ids.is_empty() + || !workspace_ids + .iter() + .all(|id| catalog.iter().any(|w| &w.id == id)) + { + return Err("Select a local workspace and enter an integration name".into()); + } + let origin = origin + .as_deref() + .filter(|s| !s.is_empty()) + .map(browser_origin) + .transpose()?; + let secret = format!("obf_{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple()); + next.grants.push(Grant { + id: Uuid::new_v4(), + name: name.trim().into(), + workspace_ids, + origin, + token_hash: store::digest(secret.as_bytes()), + }); + store.save_settings(&next)?; + token = Some(secret); + } + ControllerSettingsRequest::Revoke { id } => { + next.grants.retain(|g| g.id != id); + store.save_settings(&next)?; + } + } + inner.settings = next; + Ok(json!({ + "enabled": inner.settings.enabled, "listening": inner.listener.is_some(), + "port": inner.settings.port.unwrap_or(PORT), + "endpoint": format!("http://127.0.0.1:{}/v1", inner.settings.port.unwrap_or(PORT)), "error": inner.listener_error, + "token": token, + "grants": inner.settings.grants.iter().map(|g| json!({"id":g.id, "name":g.name, "workspaceIds":g.workspace_ids, "origin":g.origin})).collect::>(), + "workspaces": catalog.iter().map(|w| json!({"id":w.id, "name":w.name})).collect::>() + })) +} diff --git a/src/apps/desktop/src/external_control/http.rs b/src/apps/desktop/src/external_control/http.rs new file mode 100644 index 0000000000..26f5a11fd3 --- /dev/null +++ b/src/apps/desktop/src/external_control/http.rs @@ -0,0 +1,260 @@ +use super::{ + store::{Grant, Receipt}, + turns, workspaces, DesktopController, +}; +use axum::{ + extract::{DefaultBodyLimit, Path, Request, State}, + http::{header, HeaderValue, Method, StatusCode}, + middleware::{self, Next}, + response::{ + sse::{Event, KeepAlive}, + IntoResponse, Response, Sse, + }, + routing::{get, post}, + Extension, Json, Router, +}; +use serde_json::{json, Value}; +use std::{convert::Infallible, sync::Arc, time::Duration}; +use tauri::{AppHandle, Emitter, Manager}; +use uuid::Uuid; + +#[derive(Clone)] +pub(super) struct Host { + pub app: AppHandle, + generation: Uuid, + authority: String, +} + +pub(super) struct Error(pub StatusCode, pub String); +impl From for Error { + fn from(message: String) -> Self { + Self(StatusCode::INTERNAL_SERVER_ERROR, message) + } +} +impl IntoResponse for Error { + fn into_response(self) -> Response { + (self.0, Json(json!({"error": self.1}))).into_response() + } +} + +impl Host { + pub(super) fn controller(&self) -> tauri::State<'_, Arc> { + self.app.state() + } + + pub(super) async fn active(&self, id: Uuid) -> bool { + let controller = self.controller(); + let inner = controller.inner.lock().await; + inner + .listener + .as_ref() + .is_some_and(|l| l.generation == self.generation) + && inner.settings.grants.iter().any(|g| g.id == id) + } + + pub(super) async fn receipt(&self, grant: &Grant, id: Uuid) -> Result { + let receipt = self + .controller() + .store()? + .receipt(grant.id, id)? + .filter(|r| grant.workspace_ids.contains(&r.workspace_id)) + .ok_or_else(|| Error(StatusCode::NOT_FOUND, "Turn not found".into()))?; + turns::workspace(&self.app, &receipt.workspace_id).await?; + Ok(receipt) + } +} + +pub(super) fn router(app: AppHandle, generation: Uuid, port: u16) -> Router { + let host = Host { + app, + generation, + authority: format!("127.0.0.1:{port}"), + }; + Router::new() + .route("/v1/capabilities", get(capabilities)) + .route("/v1/workspaces", get(catalog)) + .route("/v1/turns", post(submit)) + .route("/v1/turns/{id}", get(status)) + .route("/v1/turns/{id}/events", get(events)) + .route("/v1/turns/{id}/cancel", post(cancel)) + .route("/v1/turns/{id}/open", post(open)) + .layer(DefaultBodyLimit::max(64 * 1024)) + .layer(middleware::from_fn_with_state(host.clone(), authorize)) + .with_state(host) +} + +async fn authorize(State(host): State, mut request: Request, next: Next) -> Response { + let headers = request.headers(); + if headers.get(header::HOST).and_then(|v| v.to_str().ok()) != Some(host.authority.as_str()) { + return StatusCode::FORBIDDEN.into_response(); + } + let origin = headers.get(header::ORIGIN).cloned(); + let origin_str = match origin.as_ref().map(HeaderValue::to_str).transpose() { + Ok(value) => value, + Err(_) => return StatusCode::FORBIDDEN.into_response(), + }; + let controller = host.controller(); + let inner = controller.inner.lock().await; + if !inner + .listener + .as_ref() + .is_some_and(|l| l.generation == host.generation) + { + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + } + let mut response = if request.method() == Method::OPTIONS { + if origin_str.is_none() + || !inner + .settings + .grants + .iter() + .any(|g| g.origin.as_deref() == origin_str) + { + return StatusCode::FORBIDDEN.into_response(); + } + let mut response = StatusCode::NO_CONTENT.into_response(); + response.headers_mut().insert( + header::ACCESS_CONTROL_ALLOW_METHODS, + HeaderValue::from_static("GET, POST, OPTIONS"), + ); + response.headers_mut().insert( + header::ACCESS_CONTROL_ALLOW_HEADERS, + HeaderValue::from_static("Authorization, Content-Type"), + ); + response.headers_mut().insert( + "access-control-allow-private-network", + HeaderValue::from_static("true"), + ); + response + } else { + let token = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.strip_prefix("Bearer ")); + let Some(grant) = token + .and_then(|token| { + inner + .settings + .grants + .iter() + .find(|g| g.accepts(token, origin_str)) + }) + .cloned() + else { + return StatusCode::UNAUTHORIZED.into_response(); + }; + drop(inner); + request.extensions_mut().insert(grant); + next.run(request).await + }; + response + .headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + if let Some(origin) = origin { + response + .headers_mut() + .insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin); + response + .headers_mut() + .append(header::VARY, HeaderValue::from_static("Origin")); + } + response +} + +async fn capabilities() -> Json { + Json( + json!({"version":1,"executionHost":"desktop","workspaceKinds":["localProject"], + "operations":["submit","continue","status","events","cancel","open"],"approvalSurface":"desktop"}), + ) +} + +async fn catalog(State(host): State, Extension(grant): Extension) -> Json { + Json( + json!({"workspaces":workspaces(&host.app).await.into_iter().filter(|w| grant.workspace_ids.contains(&w.id)) + .map(|w| json!({"id":w.id,"name":w.name})).collect::>() }), + ) +} + +async fn submit( + State(host): State, + Extension(grant): Extension, + Json(request): Json, +) -> Result { + // A dropped HTTP connection must not cancel admission between the persisted receipt and Runtime handoff. + let result = + tauri::async_runtime::spawn(async move { turns::submit(host, grant, request).await }) + .await + .map_err(|e| Error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))??; + Ok((result.0, Json(result.1))) +} + +async fn status( + State(host): State, + Extension(grant): Extension, + Path(id): Path, +) -> Result, Error> { + let receipt = host.receipt(&grant, id).await?; + Ok(Json(turns::snapshot(&host, &receipt).await?)) +} + +async fn events( + State(host): State, + Extension(grant): Extension, + Path(id): Path, +) -> Result { + let receipt = host.receipt(&grant, id).await?; + // Every attachment gets a fresh full snapshot. No client cursor or replay buffer is needed. + let stream = futures::stream::unfold( + (host, grant, receipt, None::), + |(host, grant, receipt, mut previous)| async move { + if previous + .as_ref() + .and_then(|v| v["status"].as_str()) + .is_some_and(|s| matches!(s, "completed" | "cancelled" | "failed")) + { + return None; + } + loop { + if previous.is_some() { + tokio::time::sleep(Duration::from_secs(1)).await; + } + if !host.active(grant.id).await { + return None; + } + let current = match turns::snapshot(&host, &receipt).await { + Ok(value) => value, + Err(error) => json!({"status":"unavailable","error":error.1}), + }; + if previous.as_ref() != Some(¤t) { + let event = Event::default().event("snapshot").data(current.to_string()); + previous = Some(current); + return Some((Ok::<_, Infallible>(event), (host, grant, receipt, previous))); + } + } + }, + ); + Ok(Sse::new(stream) + .keep_alive(KeepAlive::default()) + .into_response()) +} + +async fn cancel( + State(host): State, + Extension(grant): Extension, + Path(id): Path, +) -> Result, Error> { + let receipt = host.receipt(&grant, id).await?; + Ok(Json(turns::cancel(&host.app, &receipt).await?)) +} + +async fn open( + State(host): State, + Extension(grant): Extension, + Path(id): Path, +) -> Result { + let receipt = host.receipt(&grant, id).await?; + crate::appearance::show_main_window(host.app.clone()).await?; + host.app.emit_to(tauri::EventTarget::webview("main"), "desktop-control://open-session", + json!({"sessionId":receipt.session_id,"workspaceId":receipt.workspace_id,"surfaceId":"local"})).map_err(|e| e.to_string())?; + Ok(StatusCode::ACCEPTED) +} diff --git a/src/apps/desktop/src/external_control/store.rs b/src/apps/desktop/src/external_control/store.rs new file mode 100644 index 0000000000..38f1cba1d2 --- /dev/null +++ b/src/apps/desktop/src/external_control/store.rs @@ -0,0 +1,205 @@ +use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeSet, + fs, + io::ErrorKind, + path::{Path, PathBuf}, +}; +use uuid::Uuid; + +#[derive(Clone, Default, Deserialize, Serialize)] +pub(super) struct Settings { + #[serde(default)] + pub enabled: bool, + #[serde(default)] + pub port: Option, + #[serde(default)] + pub grants: Vec, +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct Grant { + pub id: Uuid, + pub name: String, + pub workspace_ids: BTreeSet, + pub origin: Option, + pub token_hash: String, +} + +impl Grant { + pub(super) fn accepts(&self, token: &str, origin: Option<&str>) -> bool { + self.token_hash == digest(token.as_bytes()) + && origin.is_none_or(|origin| self.origin.as_deref() == Some(origin)) + } +} + +pub(super) fn digest(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} + +pub(super) fn turn_id(grant: Uuid, key: &str) -> Uuid { + let hash = Sha256::new() + .chain_update(grant.as_bytes()) + .chain_update(key) + .finalize(); + Uuid::from_bytes(hash[..16].try_into().expect("SHA256 has at least 16 bytes")) +} + +/// Journal admission before handing work to the Runtime. An ambiguous handoff is +/// observable by its original IDs but is never submitted a second time. +#[derive(Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct Receipt { + pub session_id: Uuid, + pub turn_id: Uuid, + pub workspace_id: String, + pub fingerprint: String, + pub admission: String, + pub error: Option, + pub instance: Uuid, +} + +pub(super) struct Store { + root: PathBuf, + _lock: fs::File, +} + +impl Store { + pub(super) fn open(root: PathBuf) -> Result { + fs::create_dir_all(&root).map_err(|e| e.to_string())?; + let lock = fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(root.join("host.lock")) + .map_err(|e| e.to_string())?; + lock.try_lock() + .map_err(|e| format!("Cannot acquire desktop controller storage: {e}"))?; + Ok(Self { root, _lock: lock }) + } + + pub(super) fn settings(&self) -> Result { + Ok(read(&self.root.join("settings.json"))?.unwrap_or_default()) + } + + pub(super) fn save_settings(&self, settings: &Settings) -> Result<(), String> { + write(&self.root.join("settings.json"), settings) + } + + fn receipt_path(&self, grant: Uuid, turn: Uuid) -> PathBuf { + self.root + .join(grant.to_string()) + .join(format!("{turn}.json")) + } + + pub(super) fn receipt(&self, grant: Uuid, turn: Uuid) -> Result, String> { + read(&self.receipt_path(grant, turn)) + } + + pub(super) fn save_receipt(&self, grant: Uuid, receipt: &Receipt) -> Result<(), String> { + write(&self.receipt_path(grant, receipt.turn_id), receipt) + } +} + +fn read(path: &Path) -> Result, String> { + match fs::File::open(path) { + Ok(file) => serde_json::from_reader(file) + .map(Some) + .map_err(|e| e.to_string()), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.to_string()), + } +} + +fn write(path: &Path, data: &impl Serialize) -> Result<(), String> { + let parent = path + .parent() + .ok_or("Missing controller storage directory")?; + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + let mut file = tempfile::NamedTempFile::new_in(parent).map_err(|e| e.to_string())?; + serde_json::to_writer(&mut file, data).map_err(|e| e.to_string())?; + file.as_file().sync_all().map_err(|e| e.to_string())?; + file.persist(path).map_err(|e| e.to_string())?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn external_control_grants_and_admission_survive_restart_and_stay_isolated() { + let root = tempfile::tempdir().unwrap(); + let store = Store::open(root.path().to_owned()).unwrap(); + assert!(!store.settings().unwrap().enabled); + let id = Uuid::new_v4(); + let grant = Grant { + id, + name: "Board".into(), + workspace_ids: BTreeSet::from(["project".into()]), + origin: Some("https://board.example".into()), + token_hash: digest(b"one-time-token"), + }; + assert!(grant.accepts("one-time-token", None)); + assert!(grant.accepts("one-time-token", Some("https://board.example"))); + assert!(!grant.accepts("one-time-token", Some("https://unrelated.example"))); + assert!(!grant.accepts("different-token", None)); + store + .save_settings(&Settings { + enabled: true, + port: None, + grants: vec![grant], + }) + .unwrap(); + assert!(!fs::read_to_string(root.path().join("settings.json")) + .unwrap() + .contains("one-time-token")); + let turn = turn_id(id, "issue-17"); + store + .save_receipt( + id, + &Receipt { + session_id: turn, + turn_id: turn, + workspace_id: "project".into(), + fingerprint: "intent".into(), + admission: "outcome_unknown".into(), + error: None, + instance: Uuid::new_v4(), + }, + ) + .unwrap(); + assert!(Store::open(root.path().to_owned()).is_err()); + drop(store); + let reopened = Store::open(root.path().to_owned()).unwrap(); + assert!(reopened.settings().unwrap().enabled); + assert_eq!( + reopened + .receipt(id, turn_id(id, "issue-17")) + .unwrap() + .unwrap() + .turn_id, + turn + ); + let other = Uuid::new_v4(); + assert_ne!(turn_id(other, "issue-17"), turn); + assert!(reopened.receipt(other, turn).unwrap().is_none()); + } + + #[test] + fn external_control_settings_tolerate_legacy_shape_and_preserve_corrupt_records() { + let settings: Settings = + serde_json::from_str(r#"{"enabled":false,"future":true}"#).unwrap(); + let restored: Settings = + serde_json::from_value(serde_json::to_value(&settings).unwrap()).unwrap(); + assert!(restored.grants.is_empty() && restored.port.is_none() && !restored.enabled); + let root = tempfile::tempdir().unwrap(); + let store = Store::open(root.path().to_owned()).unwrap(); + let path = root.path().join("settings.json"); + fs::write(&path, "incomplete").unwrap(); + assert!(store.settings().is_err()); + assert_eq!(fs::read_to_string(path).unwrap(), "incomplete"); + } +} diff --git a/src/apps/desktop/src/external_control/turns.rs b/src/apps/desktop/src/external_control/turns.rs new file mode 100644 index 0000000000..5a369f4836 --- /dev/null +++ b/src/apps/desktop/src/external_control/turns.rs @@ -0,0 +1,389 @@ +use super::{ + eligible, + http::{Error, Host}, + store::{digest, turn_id, Grant, Receipt}, +}; +use crate::{ + api::{ + agentic_api::{create_desktop_session, CreateSessionRequest}, + app_state::AppState, + }, + runtime::{DesktopRuntimeContext, DesktopSessionScopeRequest}, +}; +use axum::http::StatusCode; +use openbitfun_core::{ + agentic::{ + coordination::{ConversationCoordinator, DialogScheduler}, + core::SessionState, + }, + service::{ + session::{DialogTurnData, SessionTurnWindowResponse, TurnStatus}, + workspace::WorkspaceInfo, + }, +}; +use openbitfun_runtime_ports::{ + AgentDialogTurnRequest, AgentSubmissionSource, AgentTurnCancellationRequest, + DialogSubmissionPolicy, DialogSubmitOutcome, SessionTurnWindowRequest, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::sync::Arc; +use tauri::{AppHandle, Manager}; +use uuid::Uuid; + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Submit { + workspace_id: String, + session_id: Option, + title: Option, + prompt: String, + idempotency_key: String, +} + +pub(super) async fn workspace(app: &AppHandle, id: &str) -> Result { + let record = app + .state::() + .workspace_service + .require_workspace(id) + .await + .map_err(|_| Error(StatusCode::NOT_FOUND, "Workspace unavailable".into()))?; + if !eligible(&record) { + return Err(Error( + StatusCode::UNPROCESSABLE_ENTITY, + "Unsupported workspace on this desktop".into(), + )); + } + Ok(record) +} + +fn scope(workspace: &WorkspaceInfo) -> DesktopSessionScopeRequest { + DesktopSessionScopeRequest { + workspace_id: Some(workspace.id.clone()), + workspace_path: workspace.root_path.to_string_lossy().into_owned(), + remote_connection_id: None, + remote_ssh_host: None, + } +} + +fn acknowledgement(r: &Receipt) -> (StatusCode, Value) { + let mut body = json!({ + "sessionId": r.session_id, "turnId": r.turn_id, + "workspaceId": r.workspace_id, "admission": r.admission + }); + if let Some(error) = &r.error { + body["error"] = json!(error); + } + let status = if r.admission == "failed" { + StatusCode::CONFLICT + } else { + StatusCode::ACCEPTED + }; + (status, body) +} + +pub(super) async fn submit( + host: Host, + grant: Grant, + request: Submit, +) -> Result<(StatusCode, Value), Error> { + if request.prompt.trim().is_empty() + || request.idempotency_key.trim().is_empty() + || request.idempotency_key.len() > 128 + || request.title.as_ref().is_some_and(|title| { + title.trim().is_empty() || title.chars().count() > 160 || request.session_id.is_some() + }) + { + return Err(Error( + StatusCode::BAD_REQUEST, + "A prompt and idempotency key are required. Titles apply only to new sessions.".into(), + )); + } + if !grant.workspace_ids.contains(&request.workspace_id) { + return Err(Error( + StatusCode::FORBIDDEN, + "Workspace is outside the grant".into(), + )); + } + let controller = host.controller(); + let _serial = controller.admission.lock().await; + if !host.active(grant.id).await { + return Err(Error( + StatusCode::UNAUTHORIZED, + "Integration disabled".into(), + )); + } + let target = workspace(&host.app, &request.workspace_id).await?; + let turn = turn_id(grant.id, &request.idempotency_key); + let fingerprint = digest(&serde_json::to_vec(&request).map_err(|e| e.to_string())?); + let store = controller.store()?; + if let Some(existing) = store.receipt(grant.id, turn)? { + if existing.fingerprint != fingerprint { + return Err(Error( + StatusCode::CONFLICT, + "Idempotency key was used for a different request".into(), + )); + } + return Ok(acknowledgement(&existing)); + } + let session = request.session_id.unwrap_or(turn); + if request.session_id.is_some() { + // The first turn doubles as an unforgeable session ownership record within this grant. + let owner = host.receipt(&grant, session).await?; + if owner.session_id != session || owner.workspace_id != target.id { + return Err(Error( + StatusCode::NOT_FOUND, + "Session not found in this workspace".into(), + )); + } + if host + .app + .state::>() + .is_session_busy_or_queued(&session.to_string()) + { + return Err(Error(StatusCode::CONFLICT, "Session is busy".into())); + } + } + let mut receipt = Receipt { + session_id: session, + turn_id: turn, + workspace_id: target.id.clone(), + fingerprint, + admission: "outcome_unknown".into(), + error: None, + instance: controller.instance, + }; + store.save_receipt(grant.id, &receipt)?; + let result = start(&host.app, &request, &target, &receipt).await; + match result { + Ok(DialogSubmitOutcome::Queued { .. }) => receipt.admission = "queued".into(), + Ok(DialogSubmitOutcome::Started { .. }) => receipt.admission = "started".into(), + Err(error) => { + if error.kind != openbitfun_runtime_ports::PortErrorKind::OutcomeUnknown { + receipt.admission = "failed".into(); + } + receipt.error = Some(error.message); + } + } + store.save_receipt(grant.id, &receipt)?; + Ok(acknowledgement(&receipt)) +} + +async fn start( + app: &AppHandle, + request: &Submit, + workspace: &WorkspaceInfo, + r: &Receipt, +) -> Result { + use openbitfun_runtime_ports::{PortError, PortErrorKind}; + let path = workspace + .root_path + .to_str() + .ok_or_else(|| { + PortError::new( + PortErrorKind::InvalidRequest, + "Unsupported workspace path encoding", + ) + })? + .to_owned(); + let session_id = r.session_id.to_string(); + let context = app.state::(); + if request.session_id.is_none() { + let title = request.title.clone().unwrap_or_else(|| { + request + .prompt + .trim() + .lines() + .next() + .unwrap_or_default() + .chars() + .take(80) + .collect() + }); + create_desktop_session( + app.state::>().inner(), + app.state::().inner(), + &context, + CreateSessionRequest { + session_id: Some(session_id.clone()), + session_name: title, + agent_type: "Standard".into(), + workspace_path: path.clone(), + workspace_id: Some(workspace.id.clone()), + project_workspace_path: None, + execution_target: None, + request_id: None, + session_kind: None, + remote_connection_id: None, + remote_ssh_host: None, + relationship: None, + deep_review_run_manifest: None, + review_target_evidence: None, + config: None, + }, + ) + .await + .map_err(|message| PortError::new(PortErrorKind::Backend, message))?; + } + openbitfun_core::product_runtime::idle_session_dialog_port( + app.state::>().inner().clone(), + app.state::>().inner().clone(), + ) + .submit_dialog_turn(AgentDialogTurnRequest { + session_id, + message: request.prompt.clone(), + original_message: None, + output_schema: None, + turn_id: Some(r.turn_id.to_string()), + execution: Default::default(), + agent_type: "Standard".into(), + workspace_path: Some(path), + workspace_id: Some(workspace.id.clone()), + remote_connection_id: None, + remote_ssh_host: None, + policy: DialogSubmissionPolicy::for_source(AgentSubmissionSource::DesktopApi), + reply_route: None, + prepended_reminders: Vec::new(), + attachments: Vec::new(), + metadata: Default::default(), + }) + .await +} + +async fn persisted_turn( + app: &AppHandle, + workspace: &WorkspaceInfo, + r: &Receipt, +) -> Result, String> { + let ctx = app.state::(); + let id = r.turn_id.to_string(); + let mut request = SessionTurnWindowRequest { + workspace_path: Default::default(), + session_id: r.session_id.to_string(), + include_internal: false, + target_storage_turn_index: 0, + expected_turn_id: Some(id.clone()), + expected_catalog_revision: None, + before: 0, + after: 1, + }; + // The window owner returns a lightweight catalog when its initial index does not match. + for _ in 0..2 { + match ctx + .session_application() + .load_session_turn_window(scope(workspace), request.clone()) + .await + .map_err(|e| e.to_string())? + { + SessionTurnWindowResponse::Ready { turns, .. } => { + return Ok(turns.into_iter().find(|t| t.turn_id == id)) + } + SessionTurnWindowResponse::Stale { catalog } + | SessionTurnWindowResponse::NotFound { catalog } => { + let Some(entry) = catalog + .entries + .iter() + .find(|e| e.turn_id.as_deref() == Some(&id)) + else { + return Ok(None); + }; + request.target_storage_turn_index = entry.storage_turn_index; + request.expected_catalog_revision = Some(catalog.revision); + } + } + } + Ok(None) +} + +pub(super) async fn snapshot(host: &Host, r: &Receipt) -> Result { + let app = &host.app; + let workspace = workspace(app, &r.workspace_id).await?; + let session = r.session_id.to_string(); + let id = r.turn_id.to_string(); + let ctx = app.state::(); + let manager = app.state::>(); + let mut value = json!({"sessionId":session,"turnId":id,"workspaceId":r.workspace_id}); + if let Some(SessionState::Processing { + current_turn_id, + phase, + }) = manager.get_session_manager().get_session_state(&session) + { + if current_turn_id == id { + let mailbox = ctx + .session_application() + .session_interaction_snapshot(&session); + value["status"] = json!(if !mailbox.permissions.requests.is_empty() { + "awaiting_approval" + } else if !mailbox.user_questions.questions.is_empty() { + "awaiting_input" + } else { + "running" + }); + value["phase"] = json!(phase); + return Ok(value); + } + } + if r.admission == "failed" { + value["status"] = json!("failed"); + value["error"] = json!(r.error); + return Ok(value); + } + // Desktop may have exited after journaling and before creating the session. + if r.admission == "outcome_unknown" + && ctx + .session_application() + .load_session_metadata(scope(&workspace), &session) + .await + .map_err(|e| e.to_string())? + .is_none() + { + value["status"] = json!("outcome_unknown"); + value["error"] = json!(r.error); + return Ok(value); + } + let turn = persisted_turn(app, &workspace, r).await?; + if let Some(turn) = turn.filter(|t| t.status != TurnStatus::InProgress) { + value["status"] = json!(match turn.status { + TurnStatus::Completed => "completed", + TurnStatus::Cancelled => "cancelled", + _ => "failed", + }); + value["error"] = json!(turn.error); + value["finalReply"] = json!(turn + .model_rounds + .last() + .filter(|_| turn.has_final_response != Some(false)) + .map(|round| round + .text_items + .iter() + .map(|item| item.content.as_str()) + .collect::())); + } else { + value["status"] = json!(if r.instance == host.controller().instance + && r.admission == "queued" + { + "queued" + } else { + "outcome_unknown" + }); + } + Ok(value) +} + +pub(super) async fn cancel(app: &AppHandle, r: &Receipt) -> Result { + let result = app + .state::() + .agent_runtime() + .cancel_turn(AgentTurnCancellationRequest { + session_id: r.session_id.to_string(), + turn_id: Some(r.turn_id.to_string()), + source: Some(AgentSubmissionSource::DesktopApi), + requester_session_id: None, + reason: None, + wait_timeout_ms: None, + cancel_descendants: false, + }) + .await + .map_err(|e| Error(StatusCode::CONFLICT, e.into_message()))?; + Ok(json!(result)) +} diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index 829118b33f..d61eed276f 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -27,6 +27,7 @@ pub mod computer_use; pub mod crash_diagnostics; pub mod desktop_cards; mod embedded_relay_host; +mod external_control; mod figure_verifier; mod frontend_asset_cache; pub mod frontend_workbench; @@ -760,6 +761,10 @@ pub async fn run() { &path_manager.user_data_dir(), )); + let mut controller_dir = path_manager.user_data_dir().join("external-control"); + if !miniapp_host_channel.is_default() { + controller_dir.push("development"); + } let mut builder = tauri::Builder::default(); let frontend_protocol_manager = Arc::clone(&frontend_workbench); // The synchronous registration runs the handler inline on the WebView @@ -822,6 +827,7 @@ pub async fn run() { .manage(miniapp_desktop::DesktopMiniApps::new(miniapp_host_channel)) .manage(sleep_prevention::SleepPreventionState::default()) .manage(desktop_runtime) + .manage(external_control::DesktopController::new(controller_dir)) .manage(coordinator_state) .manage(scheduler_state) .manage(path_manager) @@ -1403,6 +1409,7 @@ pub async fn run() { get_startup_native_trace, api::agentic_api::list_sessions, api::agentic_api::get_session_interaction_mailbox, + external_control::desktop_external_control, api::agentic_api::list_pending_permission_requests, api::agentic_api::subscribe_permission_requests, api::agentic_api::respond_permission, diff --git a/src/crates/assembly/core/src/product_runtime.rs b/src/crates/assembly/core/src/product_runtime.rs index 94461276d1..80dc299ca8 100644 --- a/src/crates/assembly/core/src/product_runtime.rs +++ b/src/crates/assembly/core/src/product_runtime.rs @@ -91,6 +91,7 @@ use crate::service::snapshot::{ open_snapshot_manager_for_view, SnapshotError, SnapshotManager, }; use crate::service::token_usage::TokenUsageService; +pub use crate::service_agent_runtime::idle_session_dialog_port; use crate::service_agent_runtime::CoreServiceAgentRuntime; use crate::util::errors::{OpenBitFunError, OpenBitFunResult}; diff --git a/src/crates/assembly/core/src/service_agent_runtime.rs b/src/crates/assembly/core/src/service_agent_runtime.rs index 82302bf64f..6906e366b8 100644 --- a/src/crates/assembly/core/src/service_agent_runtime.rs +++ b/src/crates/assembly/core/src/service_agent_runtime.rs @@ -1615,9 +1615,18 @@ impl AgentSessionRevertPort for ScheduledSessionManagementPort { } } -/// ACP accepts one prompt at a time per session. Keep that protocol-specific -/// admission rule in the product assembly instead of changing the shared -/// scheduler policy used by GUI, TUI, and remote-control surfaces. +/// Build a scoped submission adapter over an existing host scheduler. Admission +/// and the busy check share its session lock, including races with desktop input. +pub fn idle_session_dialog_port( + coordinator: Arc, + scheduler: Arc, +) -> Arc { + configured_plugin_dialog_turn_port( + coordinator, + Arc::new(RejectBusyAgentDialogTurnPort(scheduler)), + ) +} + struct RejectBusyAgentDialogTurnPort(Arc); #[async_trait::async_trait] 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 44fd066c5f..d74295f203 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": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", + "digest": "6a6de5f67359bdd2aead1692c4afd1b748e601045004dc140dd73b92342dd2bc", "ownerDigest": "6f0746578f3c56479f7c289bb05395dfe6917042f4d419de8c9a2f719d31f815", "searchAcceptance": [ { @@ -187,11 +187,11 @@ "features": 24, "settings": 24, "userFacing": 48, - "documentedItems": 369, + "documentedItems": 370, "controlCoverage": { "direct": 63, "delegated": 74, - "interactive": 232, + "interactive": 233, "unsupported": 0 } }, @@ -18865,6 +18865,7 @@ "id": "setting.tools.desktop-control:query", "capabilityId": "setting.tools.desktop-control", "itemIds": [ + "external-control", "permissions", "safety-posture" ], @@ -18907,6 +18908,52 @@ "pageId": "tools.desktop-control" } }, + { + "id": "setting.tools.desktop-control:open:external-control", + "capabilityId": "setting.tools.desktop-control", + "itemIds": [ + "external-control" + ], + "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": "visualSelection", + "presentationTarget": { + "kind": "settings", + "pageId": "tools.desktop-control" + } + }, { "id": "setting.tools.desktop-control:open:permissions", "capabilityId": "setting.tools.desktop-control", @@ -34004,6 +34051,17 @@ "Works alongside single-window App Sharing, live control status cards, and immediate stop controls" ], "items": [ + { + "id": "external-control", + "titleZh": "为本机集成授权工作区", + "titleEn": "Authorize workspaces for local integrations", + "control": { + "kind": "open", + "reasonCode": "visualSelection", + "reasonZh": "用户需要在桌面设置中选择此集成可以访问的工作区,并复制仅在创建时显示一次的令牌。", + "reasonEn": "In Desktop settings, the user chooses which workspaces the integration can access and copies the token while it is visible at creation." + } + }, { "id": "permissions", "titleZh": "查看“允许桌面控制”开关及“辅助功能”、“屏幕录制”系统授权状态并完成授权", @@ -34081,6 +34139,8 @@ "Shows live grant status for both Accessibility (mouse/keyboard input) and Screen Recording (visual capture)", "One-click permission request or direct jump into your operating system’s Privacy & Security settings", "Works alongside single-window App Sharing, live control status cards, and immediate stop controls", + "为本机集成授权工作区", + "Authorize workspaces for local integrations", "查看“允许桌面控制”开关及“辅助功能”、“屏幕录制”系统授权状态并完成授权", "Inspect Allow desktop control plus Accessibility and Screen Recording grants and authorize in OS settings", "结合应用级总开关、单窗口共享与主机边界安全管控桌面操作", diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index eebd85b083..f6bd585c48 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:90361f729e6ce746", + "digest": "fnv1a64:bbde1d4e263a15c2", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -1731,6 +1731,18 @@ "reason": "the controller keeps this command; peer hosts refuse it before dispatch" } }, + { + "id": "desktop_external_control", + "surface": "tauri_command", + "remoteWorkspace": "WorkspaceAgnostic", + "peer": { + "kind": "controller_local" + }, + "cliPeer": { + "kind": "unsupported", + "reason": "the controller keeps this command; peer hosts refuse it before dispatch" + } + }, { "id": "dispatch_answer", "surface": "tauri_command", diff --git a/src/crates/contracts/product-domains/src/remote_surface/table.rs b/src/crates/contracts/product-domains/src/remote_surface/table.rs index ff1307a2cc..c59f1017c7 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -230,6 +230,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("desktop_card_set_always_on_top", LocalOnly, ControllerLocal, REFUSED), op("desktop_card_set_checklist_item", LocalOnly, ControllerLocal, REFUSED), op("desktop_card_set_visible", LocalOnly, ControllerLocal, REFUSED), + op("desktop_external_control", Agnostic, ControllerLocal, REFUSED), op("dispatch_answer", Agnostic, ControllerLocal, REFUSED), op("dispatch_append", Agnostic, ControllerLocal, REFUSED), op("dispatch_cancel", Agnostic, ControllerLocal, REFUSED), diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index 020f04ec9f..f08f238318 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -11533,6 +11533,22 @@ "Locking down desktop input during regular coding: turn off Allow desktop control on this page—agents immediately lose desktop control even if OS permissions remain granted." ], "items": [ + { + "id": "external-control", + "titleZh": "为本机集成授权工作区", + "titleEn": "Authorize workspaces for local integrations", + "descriptionZh": "启用本机 HTTP 接口,为每个集成创建或撤销令牌。外部任务在桌面会话中运行。", + "descriptionEn": "Enable local HTTP access and issue or revoke workspace-scoped integration tokens. Submitted tasks run in desktop sessions.", + "control": { + "kind": "open", + "reasonCode": "visualSelection", + "reasonZh": "用户需要在桌面设置中选择此集成可以访问的工作区,并复制仅在创建时显示一次的令牌。", + "reasonEn": "In Desktop settings, the user chooses which workspaces the integration can access and copies the token while it is visible at creation." + }, + "evidence": [ + "command:desktop_external_control" + ] + }, { "id": "permissions", "titleZh": "查看“允许桌面控制”开关及“辅助功能”、“屏幕录制”系统授权状态并完成授权", @@ -13777,6 +13793,9 @@ "agentic": { "capabilityId": "feature.ai-assistant" }, + "external_control": { + "capabilityId": "setting.tools.desktop-control" + }, "frontend_workbench": { "capabilityId": "feature.ai-assistant" }, diff --git a/src/web-ui/src/app/App.tsx b/src/web-ui/src/app/App.tsx index 4aa7844dea..187069e5bb 100644 --- a/src/web-ui/src/app/App.tsx +++ b/src/web-ui/src/app/App.tsx @@ -780,6 +780,25 @@ function App() { }; }, []); + useEffect(() => { + if (!isTauriRuntime()) return; + let disposed = false; + const subscription = import('@/infrastructure/api/service-api/DesktopExternalControlAPI') + .then(({ listenForControllerSessionOpen }) => listenForControllerSessionOpen(async (sessionId, workspaceId) => { + if (disposed) return; + try { + const { openAgentCompanionSession } = await import('./services/openAgentCompanionSession'); + if (!disposed && !await openAgentCompanionSession(sessionId, 'local', workspaceId)) { + log.warn('External controller session could not be opened', { sessionId }); + } + } catch (error) { + log.warn('Failed to navigate to external controller session', { sessionId, error }); + } + })) + .catch(error => { log.warn('Failed to subscribe to external controller navigation', { error }); }); + return () => { disposed = true; void subscription.then(remove => remove?.()); }; + }, []); + useEffect(() => { let disposed = false; let unlisten: (() => void) | null = null; 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 d27a072188..686dac4148 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": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", + "digest": "6a6de5f67359bdd2aead1692c4afd1b748e601045004dc140dd73b92342dd2bc", "ownerDigest": "6f0746578f3c56479f7c289bb05395dfe6917042f4d419de8c9a2f719d31f815", "searchAcceptance": [ { @@ -187,11 +187,11 @@ "features": 24, "settings": 24, "userFacing": 48, - "documentedItems": 369, + "documentedItems": 370, "controlCoverage": { "direct": 63, "delegated": 74, - "interactive": 232, + "interactive": 233, "unsupported": 0 } }, @@ -18865,6 +18865,7 @@ "id": "setting.tools.desktop-control:query", "capabilityId": "setting.tools.desktop-control", "itemIds": [ + "external-control", "permissions", "safety-posture" ], @@ -18907,6 +18908,52 @@ "pageId": "tools.desktop-control" } }, + { + "id": "setting.tools.desktop-control:open:external-control", + "capabilityId": "setting.tools.desktop-control", + "itemIds": [ + "external-control" + ], + "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": "visualSelection", + "presentationTarget": { + "kind": "settings", + "pageId": "tools.desktop-control" + } + }, { "id": "setting.tools.desktop-control:open:permissions", "capabilityId": "setting.tools.desktop-control", @@ -33546,6 +33593,17 @@ "Works alongside single-window App Sharing, live control status cards, and immediate stop controls" ], "items": [ + { + "id": "external-control", + "titleZh": "为本机集成授权工作区", + "titleEn": "Authorize workspaces for local integrations", + "control": { + "kind": "open", + "reasonCode": "visualSelection", + "reasonZh": "用户需要在桌面设置中选择此集成可以访问的工作区,并复制仅在创建时显示一次的令牌。", + "reasonEn": "In Desktop settings, the user chooses which workspaces the integration can access and copies the token while it is visible at creation." + } + }, { "id": "permissions", "titleZh": "查看“允许桌面控制”开关及“辅助功能”、“屏幕录制”系统授权状态并完成授权", @@ -33623,6 +33681,8 @@ "Shows live grant status for both Accessibility (mouse/keyboard input) and Screen Recording (visual capture)", "One-click permission request or direct jump into your operating system’s Privacy & Security settings", "Works alongside single-window App Sharing, live control status cards, and immediate stop controls", + "为本机集成授权工作区", + "Authorize workspaces for local integrations", "查看“允许桌面控制”开关及“辅助功能”、“屏幕录制”系统授权状态并完成授权", "Inspect Allow desktop control plus Accessibility and Screen Recording grants and authorize in OS settings", "结合应用级总开关、单窗口共享与主机边界安全管控桌面操作", diff --git a/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx b/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx index 0d1fddc06d..b643011849 100644 --- a/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx @@ -25,6 +25,12 @@ vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: mocks.t }), })); vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ api: { invoke: mocks.invoke } })); +vi.mock('@/infrastructure/api/service-api/DesktopExternalControlAPI', () => ({ + desktopControllerSettings: async () => ({ + enabled: false, listening: false, port: 38371, endpoint: 'http://127.0.0.1:38371/v1', + error: null, token: null, grants: [], workspaces: [], + }), +})); vi.mock('@/infrastructure/api/service-api/SystemAPI', () => ({ systemAPI: { getSystemInfo: async () => ({ platform: 'macos' }) } })); vi.mock('../../../../../infrastructure/config/services/ConfigManager', () => ({ configManager: { hasCachedConfig: () => false, getCachedConfig: () => undefined, getConfig: mocks.getConfig, @@ -172,6 +178,12 @@ afterEach(async () => { }); describe('Browser and desktop control settings', () => { + it('places external control at the end of the page', async () => { + await render(); + const titles = container.querySelectorAll('[data-openbitfun-part="sectionTitle"]'); + expect(titles[titles.length - 1]?.textContent).toBe('externalControl.title'); + }); + it('keeps detailed host permissions in the standard compact settings rows', async () => { const original = mocks.invoke.getMockImplementation()!; mocks.invoke.mockImplementation(async (command: string, ...args: unknown[]) => command === 'computer_use_get_status' diff --git a/src/web-ui/src/app/scenes/settings/pages/tools/DeviceControlSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/tools/DeviceControlSettingsPage.tsx index e891e7be71..e63293e2ef 100644 --- a/src/web-ui/src/app/scenes/settings/pages/tools/DeviceControlSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/tools/DeviceControlSettingsPage.tsx @@ -35,6 +35,7 @@ import { import React, { useCallback, useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { SettingsPage } from '../shared/SettingsPage'; +import ExternalControlSection from './ExternalControlSection'; import BrowserLinkSettingsSection from './BrowserLinkSettingsSection'; const log = createLogger('DeviceControlSettingsPage'); @@ -857,6 +858,7 @@ const DeviceControlSettingsPage: React.FC = () => { )} + {IS_TAURI_DESKTOP && !peerModeActive && } ); }; diff --git a/src/web-ui/src/app/scenes/settings/pages/tools/ExternalControlSection.tsx b/src/web-ui/src/app/scenes/settings/pages/tools/ExternalControlSection.tsx new file mode 100644 index 0000000000..019f379934 --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/tools/ExternalControlSection.tsx @@ -0,0 +1,82 @@ +import { useEffect, useRef, useState } from 'react'; +import { Button, Input, MultiSelect, Switch } from '@openbitfun/ui'; +import { ConfigPageRow, ConfigPageSection } from '@/infrastructure/config/components/common'; +import { desktopControllerSettings, type ControllerRequest, type DesktopControllerSettings } from '@/infrastructure/api/service-api/DesktopExternalControlAPI'; +import { useI18n } from '@/infrastructure/i18n'; + +export default function ExternalControlSection() { + const { t } = useI18n('settings/runtime'); + const [settings, setSettings] = useState(); + const [error, setError] = useState(''); + const [busy, setBusy] = useState(false); + const [port, setPort] = useState(''); + const [name, setName] = useState(''); + const [workspaceIds, setWorkspaceIds] = useState([]); + const [origin, setOrigin] = useState(''); + const activeRequest = useRef(null); + + async function run(request: ControllerRequest) { + const requestId = Symbol(); + activeRequest.current = requestId; + setBusy(true); + setError(''); + try { + const result = await desktopControllerSettings(request); + if (activeRequest.current !== requestId) return; + setSettings(result); + setPort(String(result.port)); + if (request.operation === 'issue') { + setName(''); + setWorkspaceIds([]); + setOrigin(''); + } + } catch (err) { + if (activeRequest.current === requestId) setError(String(err)); + } finally { + if (activeRequest.current === requestId) setBusy(false); + } + } + + useEffect(() => { + void run({ operation: 'status' }); + return () => { activeRequest.current = null; }; + }, []); + + return + + 65535 || !Number.isInteger(Number(port))} onChange={event => void run({ operation: 'setEnabled', enabled: event.target.checked, port: Number(port) })} /> + + {settings && !settings.listening && + setPort(e.target.value)} /> + } + {(error || settings?.error) && + + } + {settings?.listening && <> + {settings.endpoint} + + setName(e.target.value)} /> + + + ({ value: w.id, label: w.name }))} onValueChange={ids => setWorkspaceIds(ids.map(String))} /> + + + setOrigin(e.target.value)} /> + + + + + {settings.token && + e.target.select()} /> + } + } + {settings?.grants.map(grant => settings.workspaces.find(w => w.id === id)?.name ?? id).join(', ')}> + + )} + ; +} diff --git a/src/web-ui/src/app/scenes/settings/settingsRegistry.ts b/src/web-ui/src/app/scenes/settings/settingsRegistry.ts index 10067f784f..9b9d43903f 100644 --- a/src/web-ui/src/app/scenes/settings/settingsRegistry.ts +++ b/src/web-ui/src/app/scenes/settings/settingsRegistry.ts @@ -415,6 +415,7 @@ export const SETTINGS_PAGE_MANIFESTS: readonly SettingsPageManifest[] = [ phrase('settings/runtime', 'computerUse.sectionTitle'), phrase('settings/runtime', 'computerUse.accessibility'), phrase('settings/runtime', 'computerUse.screenCapture'), + phrase('settings/runtime', 'externalControl.title'), phrase('settings/runtime', 'browserLinks.sectionTitle'), phrase('settings/runtime', 'browserLinks.defaultTarget'), phrase('settings/runtime', 'browserLinks.builtin'), diff --git a/src/web-ui/src/infrastructure/api/generated/productControl.ts b/src/web-ui/src/infrastructure/api/generated/productControl.ts index e0c1da5eb5..cec5cf4eae 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 = "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294" as const; +export const PRODUCT_CONTROL_GRAPH_DIGEST = "6a6de5f67359bdd2aead1692c4afd1b748e601045004dc140dd73b92342dd2bc" as const; export type ProductControlCapabilityId = "feature.home-search" | "feature.ai-assistant" | "feature.agents" | "feature.personal-assistants" | "feature.projects" | "feature.files-editor" | "feature.terminal" | "feature.cli-tui" | "feature.git" | "feature.code-review" | "feature.browser" | "feature.computer-use" | "feature.skills" | "feature.miniapps" | "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.permissions" | "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.storage" | "setting.data.archived" | "setting.data.diagnostics" | "feature.generative-ui"; diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index fc8de1e0ae..461a13d673 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:90361f729e6ce746" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:bbde1d4e263a15c2" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -53,6 +53,7 @@ export const PEER_CONTROLLER_LOCAL_COMMANDS: ReadonlySet = new Set([ "desktop_card_set_always_on_top", "desktop_card_set_checklist_item", "desktop_card_set_visible", + "desktop_external_control", "dispatch_answer", "dispatch_append", "dispatch_cancel", diff --git a/src/web-ui/src/infrastructure/api/service-api/DesktopExternalControlAPI.ts b/src/web-ui/src/infrastructure/api/service-api/DesktopExternalControlAPI.ts new file mode 100644 index 0000000000..dea5ef62b7 --- /dev/null +++ b/src/web-ui/src/infrastructure/api/service-api/DesktopExternalControlAPI.ts @@ -0,0 +1,29 @@ +import { listen } from '@tauri-apps/api/event'; +import { api } from './ApiClient'; + +export type ControllerRequest = + | { operation: 'status' } + | { operation: 'setEnabled'; enabled: boolean; port?: number } + | { operation: 'issue'; name: string; workspaceIds: string[]; origin?: string } + | { operation: 'revoke'; id: string }; + +export interface DesktopControllerSettings { + enabled: boolean; + listening: boolean; + port: number; + endpoint: string; + error: string | null; + token: string | null; + grants: { id: string; name: string; workspaceIds: string[]; origin: string | null }[]; + workspaces: { id: string; name: string }[]; +} + +export function desktopControllerSettings(request: ControllerRequest): Promise { + return api.invoke('desktop_external_control', { request }, { retries: 0 }); +} + +export function listenForControllerSessionOpen(open: (sessionId: string, workspaceId: string) => void) { + return listen<{ sessionId: string; workspaceId: string }>('desktop-control://open-session', ({ payload }) => { + open(payload.sessionId, payload.workspaceId); + }); +} 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 43f319e548..7c12ac6169 100644 --- a/src/web-ui/src/locales/en-US/scenes/capabilities.json +++ b/src/web-ui/src/locales/en-US/scenes/capabilities.json @@ -605,6 +605,7 @@ "title": "Desktop control (Computer Use)", "summary": "Manage the Allow desktop control master switch for native desktop GUI automation, inspect Accessibility and Screen Recording OS grants, and jump straight to system privacy settings.", "items": { + "external-control": "Authorize workspaces for local integrations", "permissions": "Inspect Allow desktop control plus Accessibility and Screen Recording grants and authorize in OS settings", "safety-posture": "Keep desktop automation bounded with the in-app toggle, per-window sharing, and host isolation" } 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 20d96939d8..03cf6d2193 100644 --- a/src/web-ui/src/locales/en-US/settings/runtime.json +++ b/src/web-ui/src/locales/en-US/settings/runtime.json @@ -1,4 +1,21 @@ { + "externalControl": { + "port": "Listening port", + "title": "External control", + "enable": "Enable local HTTP access", + "description": "Allow integrations to run tasks in selected local project workspaces. Review tool approvals in Desktop.", + "retry": "Retry", + "endpoint": "API address", + "name": "Integration name", + "workspaces": "Allowed workspaces", + "origin": "Browser origin (optional)", + "originHint": "For direct browser access, enter the exact origin including its port. Leave empty for backend integrations.", + "access": "Integration access", + "issue": "Create token", + "token": "Access token", + "tokenHint": "Copy this token now. It is displayed once.", + "revoke": "Revoke access" + }, "defaultHarness": { "title": "Default agent execution mode", "description": "Applies to new standard sessions; assistants, ACP, and sessions with an explicit mode are unaffected", 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 045907297f..8d89ef5e7d 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json @@ -605,6 +605,7 @@ "title": "桌面控制(Computer Use)", "summary": "管理智能体操作原生桌面应用界面的“允许桌面控制”总开关,清晰核查并引导授予系统“辅助功能”与“屏幕录制”权限,在可控安全边界内完成跨应用自动化。", "items": { + "external-control": "为本机集成授权工作区", "permissions": "查看“允许桌面控制”开关及“辅助功能”、“屏幕录制”系统授权状态并完成授权", "safety-posture": "结合应用级总开关、单窗口共享与主机边界安全管控桌面操作" } 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 14a8ed97ec..14da888c95 100644 --- a/src/web-ui/src/locales/zh-CN/settings/runtime.json +++ b/src/web-ui/src/locales/zh-CN/settings/runtime.json @@ -1,4 +1,21 @@ { + "externalControl": { + "port": "监听端口", + "title": "外部控制", + "enable": "启用本机 HTTP 访问", + "description": "允许集成在选定的本机项目工作区执行任务。工具审批由桌面端处理。", + "retry": "重试", + "endpoint": "API 地址", + "name": "集成名称", + "workspaces": "授权工作区", + "origin": "网页来源(可选)", + "originHint": "网页直连时填写完整来源,包含端口。通过后端连接时留空。", + "access": "集成访问权限", + "issue": "创建令牌", + "token": "访问令牌", + "tokenHint": "请立即复制此令牌,它只显示一次。", + "revoke": "撤销授权" + }, "defaultHarness": { "title": "默认智能体执行模式", "description": "用于普通新会话;助理、ACP 和已指定模式的会话不受影响", 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 c7ea4a209a..05703998c6 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json @@ -605,6 +605,7 @@ "title": "桌面控制(Computer Use)", "summary": "管理智能體操作原生桌面應用介面的「允許桌面控制」總開關,清晰核查並引導授予系統「輔助功能」與「螢幕錄製」權限,在可控安全邊界內完成跨應用自動化。", "items": { + "external-control": "為本機整合授權工作區", "permissions": "檢視「允許桌面控制」開關及「輔助功能」、「螢幕錄製」系統授權狀態並完成授權", "safety-posture": "結合應用級總開關、單視窗共享與主機邊界安全管控桌面操作" } 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 05274191ff..de39c5c622 100644 --- a/src/web-ui/src/locales/zh-TW/settings/runtime.json +++ b/src/web-ui/src/locales/zh-TW/settings/runtime.json @@ -1,4 +1,21 @@ { + "externalControl": { + "port": "監聽連接埠", + "title": "外部控制", + "enable": "啟用本機 HTTP 存取", + "description": "允許整合工具在選取的本機專案工作區執行任務。工具核准由桌面端處理。", + "retry": "重試", + "endpoint": "API 位址", + "name": "整合名稱", + "workspaces": "授權工作區", + "origin": "網頁來源(選填)", + "originHint": "網頁直接連線時請填寫完整來源,包含連接埠。透過後端連線時留空。", + "access": "整合存取權限", + "issue": "建立權杖", + "token": "存取權杖", + "tokenHint": "請立即複製此權杖,它只會顯示一次。", + "revoke": "撤銷授權" + }, "defaultHarness": { "title": "預設智能體執行模式", "description": "用於一般新會話;助理、ACP 與已指定模式的會話不受影響",