From e50396ea6be1b5883b3b05b5bc576d23f2fce84c Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Wed, 18 Nov 2026 21:09:59 +0800 Subject: [PATCH 1/6] feat(dispatch): remove SSH deployment and limit manual target selection --- Cargo.lock | 1 - docs/architecture/detached-task-dispatch.md | 64 +- docs/interactive-capabilities/README.md | 16 +- .../capabilities.json | 91 +- .../capabilities/feature.detached-dispatch.md | 16 +- .../technical/product-control-open-audit.json | 28 +- .../technical/tauri-command-map.json | 72 +- src/apps/cli/src/daemon/mod.rs | 2 - src/apps/cli/src/daemon/provision.rs | 219 -- src/apps/cli/src/daemon/service.rs | 37 - src/apps/cli/src/dispatch/mod.rs | 4 - src/apps/cli/src/main.rs | 68 - src/apps/cli/src/peer_host/deny.rs | 4 - src/apps/desktop/src/api/dispatch_api.rs | 161 +- .../desktop/src/api/remote_connect_api.rs | 115 - src/apps/desktop/src/lib.rs | 4 - src/apps/server/src/routes/dispatch.rs | 40 +- .../core/src/service/dispatch/controller.rs | 82 +- .../assembly/core/src/service/dispatch/mod.rs | 20 +- .../generated/product-control-catalog.json | 89 +- .../generated/remote-surface-registry.json | 50 +- .../src/remote_surface/table.rs | 4 - .../services-core/src/dispatch_contract.rs | 55 - .../services/services-integrations/Cargo.toml | 2 - .../src/remote_connect/account.rs | 55 - .../src/remote_connect/device_crypto.rs | 28 - .../src/remote_ssh/disabled.rs | 49 - .../src/remote_ssh/dispatch_ssh.rs | 3147 +---------------- .../src/remote_ssh/mod.rs | 2 - .../src/remote_ssh/product_paths.rs | 12 +- .../src/remote_ssh/release_verify.rs | 170 - .../interactive-capabilities/catalog.json | 35 +- .../generated/interactive-capabilities.json | 89 +- .../dispatch/DispatchInstallDialog.tsx | 678 ---- ...lDialog.scss => DispatchTargetDialog.scss} | 30 - ...test.tsx => DispatchTargetDialog.test.tsx} | 256 +- .../dispatch/DispatchTargetDialog.tsx | 397 +++ .../dispatch/DispatchTargetPicker.test.tsx | 15 +- .../dispatch/DispatchTargetPicker.tsx | 103 +- src/web-ui/src/features/dispatch/README.md | 20 +- .../dispatch/dispatch.contract.test.ts | 4 - .../src/features/dispatch/dispatchApi.test.ts | 10 +- .../src/features/dispatch/dispatchApi.ts | 43 +- src/web-ui/src/features/dispatch/types.ts | 19 - .../features/dispatch/useDispatchTargets.ts | 21 +- .../api/generated/productControl.ts | 2 +- .../api/generated/remoteSurface.ts | 6 +- src/web-ui/src/locales/en-US/common.json | 18 - src/web-ui/src/locales/zh-CN/common.json | 18 - src/web-ui/src/locales/zh-TW/common.json | 18 - src/web-ui/src/shared/utils/logger.test.ts | 2 +- 51 files changed, 710 insertions(+), 5781 deletions(-) delete mode 100644 src/apps/cli/src/daemon/provision.rs delete mode 100644 src/crates/services/services-integrations/src/remote_ssh/release_verify.rs delete mode 100644 src/web-ui/src/features/dispatch/DispatchInstallDialog.tsx rename src/web-ui/src/features/dispatch/{DispatchInstallDialog.scss => DispatchTargetDialog.scss} (88%) rename src/web-ui/src/features/dispatch/{DispatchInstallDialog.test.tsx => DispatchTargetDialog.test.tsx} (66%) create mode 100644 src/web-ui/src/features/dispatch/DispatchTargetDialog.tsx diff --git a/Cargo.lock b/Cargo.lock index 7bf5755779..7e5e879918 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6768,7 +6768,6 @@ dependencies = [ "log", "mac_address", "md5", - "minisign-verify", "notify", "openbitfun-agent-runtime", "openbitfun-agent-tools", diff --git a/docs/architecture/detached-task-dispatch.md b/docs/architecture/detached-task-dispatch.md index 673eaa1144..7518409bb2 100644 --- a/docs/architecture/detached-task-dispatch.md +++ b/docs/architecture/detached-task-dispatch.md @@ -91,13 +91,6 @@ the target's validated submit acknowledgement. Preparation, retry, and recovery for the same job are serialized by one per-job run lock, so an expired-entry recovery cannot race a live attempt. -For automatic SSH CLI setup, audit progress is a fallible durable write rather -than an in-memory callback. The `cli-install-started` transition is persisted -before the first remote installer mutation, subsequent success or failure is -persisted before setup returns, and any audit write failure stops submission. -Keeping the journal until acknowledgement lets a retry recover setup actions -that completed remotely even if the controller exited before submit finished. - Before creating the baseline claim, preparation records the stable project workspace path that owns the worktree registry rather than relying on a linked worktree path that may disappear. An expired preparation lease is necessary but @@ -193,9 +186,7 @@ durable store; `DISPATCH_PROTOCOL_VERSION` in source, and the Web UI pins its copy against that file. Version 4 introduced Git worktree delivery and is intentionally incompatible with targets that do not implement it; version 5 adds the target-owned reasoning catalog and -per-turn preset selection (`reasoning_presets`). SSH submission can repair that mismatch -through signed release installation; an account device must be upgraded as a -OpenBitFun device. +per-turn preset selection (`reasoning_presets`). Each target must have a compatible runner before accepting a job. Public job verbs are: @@ -260,53 +251,7 @@ original binding and policy revision for a capable target to restore, while an older reader cannot turn the new account fields into its default OAuth login. -`probe` is read-only and never installs software. Immediately before SSH -provisioning, submission probes again and automatically installs or upgrades a -compatible latest prebuilt `openbitfun` release when needed. Release resolution -stays bound to the expected OS and architecture. GitHub is the default byte -source; when its measured transfer rate is below 512 KiB/s, OpenBitFun is tried -first and GitHub remains the fallback. The same policy applies whether the SSH -target downloads directly or the controller has to push the archive. The -controller verifies the -checksum sidecar, its publisher signature when present, and the mandatory -archive signature, pins the SHA-256 passed to the installer, waits with a -bounded deadline, and probes the installed binary again before continuing. - -The signed prebuilt release is the only install path. The controller never -compiles OpenBitFun on a target, and exposes no command to do so: when no published -binary can run there — an unsupported platform, a libc floor, a missing `tar`, -an unreachable release, or a release that predates a required capability — the -probe reports why and the target cannot be selected. - -### One-click SSH target bootstrap - -The Desktop readiness dialog may run the same signed installer before submit. -After the post-install protocol probe succeeds, it optionally turns the SSH -host into an account device: - -1. The target CLI returns its stable, non-secret machine identity through a - hidden capability-gated daemon command. -2. If the controller has a finalized account login, its full device token calls - the Relay's authenticated device-provisioning endpoint. The Relay creates a - distinct target device and a full device token; a delegated control token - cannot call this endpoint. If the controller is signed out, this entire - account/daemon phase is skipped. -3. The controller stages the target token, account master key, relay URL, and - target device id in a fresh owner-only file over SFTP. Secrets never enter a - shell argument or the renderer. The target verifies file ownership/mode and - its device id, consumes the file, and encrypts the session with its own - machine-bound key. -4. The target installs and starts the existing CLI daemon through its user - service manager (systemd user service with linger on Linux, LaunchAgent on - macOS). The controller does not report success until the new device is - visible online through the Relay. - -Any failure after credential issuance removes the target service/session and -deletes the Relay device best-effort. Stale rollback commands are bound to the -expected user and device id, so they cannot log out a session that appeared on -the target later. A signed-out controller installs only the CLI: detached SSH -job workers already persist independently and an idle account daemon would -provide no routing capability. +The manual target picker lists local execution and saved SSH hosts. Both the picker and submission probe the existing CLI. Install or upgrade the CLI on the target before dispatching. Agent tools can also submit to a same-account device. Account-device transport wraps target verbs in names reserved for detached dispatch, such as `dispatch_target_submit`. They are handled before the @@ -428,10 +373,7 @@ supervision alone is not evidence of that capability. - A missing or offline target fails submit; the Relay does not queue jobs. - A target missing a required behavioral capability fails preflight before a durable job is created, even when its CLI package version matches. -- A signed prebuilt SSH release may be installed automatically. Missing - platform support, failed signature or digest verification, installer timeout, - or an incompatible post-install probe fails closed before workspace - provisioning. +- A missing or incompatible target CLI fails the probe before workspace provisioning. - A lost submit response leaves `submission_unknown`; status or an idempotent retry reconciles the target's durable truth. - A live PID that no longer matches the exact worker command is never signaled diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index 91c15405ed..a32578af80 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -1,9 +1,9 @@ # OpenBitFun 功能与设置目录 / OpenBitFun Features & Settings -OpenBitFun Playbook 当前包含 **24 个功能**和 **23 个设置页**,共 **47 个**用户可理解的条目、**369 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 +OpenBitFun Playbook 当前包含 **24 个功能**和 **23 个设置页**,共 **47 个**用户可理解的条目、**368 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 -OpenBitFun Playbook currently contains **24 features**, **23 settings pages**, and **369** source-backed sub-capabilities across **47** 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**, **23 settings pages**, and **368** source-backed sub-capabilities across **47** 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**, **23 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 或可解析的源码标记;这些证据不会进入公开目录。当前 **705** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 +说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **701** 个 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 **705** 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 **701** 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 -- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **64**、委托 **74**、需交互 **231**、不支持 **0**。 +- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **64**、委托 **74**、需交互 **230**、不支持 **0**。 - 稳定行为声明为带 JSON 输入契约的 `operations` 或 `options`,并绑定原生产品控制 Provider;智能体不接触原始 Tauri Command。 -- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 369 项子能力都不会写入 system prompt。 +- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 368 项子能力都不会写入 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 **64 direct**, **74 delegated**, **231 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 **64 direct**, **74 delegated**, **230 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 368 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 688daf9b19..d33f458ef9 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": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", + "digest": "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c", "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { @@ -187,11 +187,11 @@ "features": 24, "settings": 23, "userFacing": 47, - "documentedItems": 369, + "documentedItems": 368, "controlCoverage": { "direct": 64, "delegated": 74, - "interactive": 231, + "interactive": 230, "unsupported": 0 } }, @@ -10247,7 +10247,6 @@ "capabilityId": "feature.detached-dispatch", "itemIds": [ "targets", - "provision", "model-sync", "submit", "status-list", @@ -10635,55 +10634,6 @@ } } }, - { - "id": "feature.detached-dispatch:open:provision", - "capabilityId": "feature.detached-dispatch", - "itemIds": [ - "provision" - ], - "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": "event", - "eventName": "openbitfun:open-remote-connect", - "detail": { - "group": "account" - } - } - }, { "id": "feature.detached-dispatch:open:model-sync", "capabilityId": "feature.detached-dispatch", @@ -29268,13 +29218,13 @@ "background host" ], "highlightsZh": [ - "一键列出同账号在线设备与已保存 SSH 主机作为派发目标", + "可选择已配置的 SSH 主机派发任务,智能体也可派发到同账号设备", "提交后控制端可随时断网或休眠,目标机在独立 Git Worktree 自治执行", "断线重连后按游标增量回填完整对话与工具轨迹,支持远程回答权限请求", "任务完成后可将目标端改动安全同步回本机,绝不把本机当成脆弱的文件代理" ], "highlightsEn": [ - "Discover same-account devices and saved SSH hosts as ready-to-run targets", + "Dispatch to a configured SSH host, or ask the Agent to dispatch to a same-account device", "Disconnect or close your laptop freely while the target works in an isolated Git worktree", "Replay missed events incrementally by cursor on reconnect and answer pending permissions remotely", "Sync completed changes back cleanly without turning your controller into a fragile file proxy" @@ -29294,19 +29244,6 @@ "options": [] } }, - { - "id": "provision", - "titleZh": "为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境", - "titleEn": "Provision the target host and install or update the OpenBitFun CLI", - "descriptionZh": "首次向全新的 SSH 服务器派发时,可在向导中一键检测并在远端部署匹配的 CLI 执行端,省去手工登录装环境。", - "descriptionEn": "Preparing a fresh SSH server? Detect its environment and install or update the matching OpenBitFun CLI right from the setup flow.", - "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "「为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境」涉及远端安装进度轮询、网络下载与中途取消控制;智能体会打开目标配置界面,由你确认并观察安装完成。", - "reasonEn": "\"Provision the target host and install or update the OpenBitFun CLI\" involves live remote installation polling and cancellation controls; the Agent opens the target provisioning flow so you can confirm and monitor setup." - } - }, { "id": "model-sync", "titleZh": "在派发前按需将任务所选的模型配置同步给目标主机", @@ -29404,15 +29341,15 @@ } ], "stepsZh": [ - "确保目标机器已登录同一账号在线,或已在本地保存好可用的 SSH 连接配置", - "在当前 Git 项目的聊天输入框底部点击「本机」芯片打开「这个任务在哪运行」菜单(或直接对智能体说明要派发到哪台设备),选定目标与权限审批策略", - "发送任务提示词;目标主机会自动准备环境、同步所需模型配置并在独立 Git Worktree 中启动执行", + "先在 SSH 目标上安装兼容的 OpenBitFun CLI,并保存 SSH 连接。", + "在聊天输入框底部点击「本机」,选择 SSH 主机。要派发到同账号设备时,直接告诉智能体目标设备和任务。", + "发送任务后,目标主机会同步所需的模型配置,并在独立的 Git worktree 中执行任务。", "执行期间可随时离线;重新打开会话即可查看最新进度、批复等待中的权限,完成后一键将结果同步回本机工作区" ], "stepsEn": [ - "Make sure your target device is signed in to the same account and online, or save an SSH connection profile first", - "Click the \"This computer\" chip at the bottom of the chat input to open the \"Where this task runs\" menu (or ask the agent explicitly to dispatch to a named device), and pick your target and approval policy", - "Submit your prompt; the target provisions its runtime if needed, syncs model settings, and starts working in a dedicated Git worktree", + "Install a compatible OpenBitFun CLI on the SSH target and save its SSH connection.", + "Select an SSH host from the This computer menu in the composer. To use a same-account device, ask the Agent to dispatch your task to that device.", + "Submit the task. The target syncs the required model configuration and runs the job in a dedicated Git worktree.", "Disconnect anytime; reopen the session later to catch up on streamed events, approve pending permissions, or sync finished changes back locally" ], "agentExamplesZh": [ @@ -29633,18 +29570,16 @@ "target host", "offline job", "background host", - "一键列出同账号在线设备与已保存 SSH 主机作为派发目标", + "可选择已配置的 SSH 主机派发任务,智能体也可派发到同账号设备", "提交后控制端可随时断网或休眠,目标机在独立 Git Worktree 自治执行", "断线重连后按游标增量回填完整对话与工具轨迹,支持远程回答权限请求", "任务完成后可将目标端改动安全同步回本机,绝不把本机当成脆弱的文件代理", - "Discover same-account devices and saved SSH hosts as ready-to-run targets", + "Dispatch to a configured SSH host, or ask the Agent to dispatch to a same-account device", "Disconnect or close your laptop freely while the target works in an isolated Git worktree", "Replay missed events incrementally by cursor on reconnect and answer pending permissions remotely", "Sync completed changes back cleanly without turning your controller into a fragile file proxy", "列出同账号下的所有设备与本机已保存的 SSH 目标", "List same-account devices and saved SSH dispatch targets", - "为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境", - "Provision the target host and install or update the OpenBitFun CLI", "在派发前按需将任务所选的模型配置同步给目标主机", "Sync required model configuration to the target before job submission", "从当前 Git 工作区向设备或 SSH 目标提交可离线运行的持久任务", diff --git a/docs/interactive-capabilities/capabilities/feature.detached-dispatch.md b/docs/interactive-capabilities/capabilities/feature.detached-dispatch.md index a9ac4f3947..13d92717f9 100644 --- a/docs/interactive-capabilities/capabilities/feature.detached-dispatch.md +++ b/docs/interactive-capabilities/capabilities/feature.detached-dispatch.md @@ -30,10 +30,6 @@ Send long-running coding, test, or refactoring jobs from your current Git worksp - List same-account devices and saved SSH dispatch targets - 说明:一次看清哪些同账号电脑当前在线(含系统与机型信息)以及哪些 SSH 主机可直接投递任务。 - Why & how: See every device on your account—with live online status, OS, and model info—alongside saved SSH hosts ready to accept jobs. -- **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境 - - Provision the target host and install or update the OpenBitFun CLI - - 说明:首次向全新的 SSH 服务器派发时,可在向导中一键检测并在远端部署匹配的 CLI 执行端,省去手工登录装环境。 - - Why & how: Preparing a fresh SSH server? Detect its environment and install or update the matching OpenBitFun CLI right from the setup flow. - **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 在派发前按需将任务所选的模型配置同步给目标主机 - Sync required model configuration to the target before job submission - 说明:确保远端机器拥有执行本次任务所需的模型通道配置,避免任务启动后才发现远端没配模型。 @@ -65,12 +61,12 @@ Send long-running coding, test, or refactoring jobs from your current Git worksp ## 怎么用 / How to use it -1. 确保目标机器已登录同一账号在线,或已在本地保存好可用的 SSH 连接配置 - Make sure your target device is signed in to the same account and online, or save an SSH connection profile first -2. 在当前 Git 项目的聊天输入框底部点击「本机」芯片打开「这个任务在哪运行」菜单(或直接对智能体说明要派发到哪台设备),选定目标与权限审批策略 - Click the "This computer" chip at the bottom of the chat input to open the "Where this task runs" menu (or ask the agent explicitly to dispatch to a named device), and pick your target and approval policy -3. 发送任务提示词;目标主机会自动准备环境、同步所需模型配置并在独立 Git Worktree 中启动执行 - Submit your prompt; the target provisions its runtime if needed, syncs model settings, and starts working in a dedicated Git worktree +1. 先在 SSH 目标上安装兼容的 OpenBitFun CLI,并保存 SSH 连接。 + Install a compatible OpenBitFun CLI on the SSH target and save its SSH connection. +2. 在聊天输入框底部点击「本机」,选择 SSH 主机。要派发到同账号设备时,直接告诉智能体目标设备和任务。 + Select an SSH host from the This computer menu in the composer. To use a same-account device, ask the Agent to dispatch your task to that device. +3. 发送任务后,目标主机会同步所需的模型配置,并在独立的 Git worktree 中执行任务。 + Submit the task. The target syncs the required model configuration and runs the job in a dedicated Git worktree. 4. 执行期间可随时离线;重新打开会话即可查看最新进度、批复等待中的权限,完成后一键将结果同步回本机工作区 Disconnect anytime; reopen the session later to catch up on streamed events, approve pending permissions, or sync finished changes back locally diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index c577614185..a4cd7db940 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": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", - "count": 231, + "catalogDigest": "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c", + "count": 230, "reasonCounts": { "externalAuth": 4, "secretEntry": 6, - "unstructuredInteraction": 194, + "unstructuredInteraction": 193, "visualSelection": 27 }, "entries": [ @@ -2222,28 +2222,6 @@ "command:peer_mode_ping" ] }, - { - "capabilityId": "feature.detached-dispatch", - "itemId": "provision", - "titleZh": "为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境", - "titleEn": "Provision the target host and install or update the OpenBitFun CLI", - "reasonCode": "unstructuredInteraction", - "reasonZh": "「为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境」涉及远端安装进度轮询、网络下载与中途取消控制;智能体会打开目标配置界面,由你确认并观察安装完成。", - "reasonEn": "\"Provision the target host and install or update the OpenBitFun CLI\" involves live remote installation polling and cancellation controls; the Agent opens the target provisioning flow so you can confirm and monitor setup.", - "presentationTarget": { - "kind": "event", - "eventName": "openbitfun:open-remote-connect", - "detail": { - "group": "account" - } - }, - "evidence": [ - "command:dispatch_provision_target", - "command:dispatch_install_cli_start", - "command:dispatch_install_cli_poll", - "command:dispatch_install_cli_cancel" - ] - }, { "capabilityId": "feature.detached-dispatch", "itemId": "model-sync", diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 85fbc91964..adfa1c0169 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": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", - "commandCount": 705, + "catalogDigest": "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c", + "commandCount": 701, "coverage": { - "commandCount": 705, - "documentedCommandCount": 638, + "commandCount": 701, + "documentedCommandCount": 634, "implementationCommandCount": 67, "implementationDigest": "3c03db6cdd74260fd8b7203d30ea4ab7224b4cfdea4a532c11e41a587cd92b19" }, @@ -2203,54 +2203,6 @@ "signature": "fn dispatch_continue( state: State<'_, AppState>, path_manager: State<'_, Arc>, request: DispatchContinueRequest, ) -> Result", "remoteWorkspacePolicy": "WorkspaceAgnostic" }, - { - "id": "dispatch_install_cli_cancel", - "moduleId": "dispatch", - "capabilityId": "feature.detached-dispatch", - "capabilityIds": [ - "feature.detached-dispatch" - ], - "documentedItemIds": [ - "feature.detached-dispatch:provision" - ], - "visibility": "documented", - "rustPath": "api::dispatch_api::dispatch_install_cli_cancel", - "sourceFile": "src/apps/desktop/src/api/dispatch_api.rs", - "signature": "fn dispatch_install_cli_cancel( state: State<'_, AppState>, request: DispatchConnectionRequest, ) -> Result<(), String>", - "remoteWorkspacePolicy": "WorkspaceAgnostic" - }, - { - "id": "dispatch_install_cli_poll", - "moduleId": "dispatch", - "capabilityId": "feature.detached-dispatch", - "capabilityIds": [ - "feature.detached-dispatch" - ], - "documentedItemIds": [ - "feature.detached-dispatch:provision" - ], - "visibility": "documented", - "rustPath": "api::dispatch_api::dispatch_install_cli_poll", - "sourceFile": "src/apps/desktop/src/api/dispatch_api.rs", - "signature": "fn dispatch_install_cli_poll( state: State<'_, AppState>, request: DispatchInstallPollRequest, ) -> Result", - "remoteWorkspacePolicy": "WorkspaceAgnostic" - }, - { - "id": "dispatch_install_cli_start", - "moduleId": "dispatch", - "capabilityId": "feature.detached-dispatch", - "capabilityIds": [ - "feature.detached-dispatch" - ], - "documentedItemIds": [ - "feature.detached-dispatch:provision" - ], - "visibility": "documented", - "rustPath": "api::dispatch_api::dispatch_install_cli_start", - "sourceFile": "src/apps/desktop/src/api/dispatch_api.rs", - "signature": "fn dispatch_install_cli_start( state: State<'_, AppState>, request: DispatchInstallStartRequest, ) -> Result", - "remoteWorkspacePolicy": "WorkspaceAgnostic" - }, { "id": "dispatch_list_jobs", "moduleId": "dispatch", @@ -2315,22 +2267,6 @@ "signature": "fn dispatch_probe_target( state: State<'_, AppState>, request: DispatchProbeTargetRequest, ) -> Result", "remoteWorkspacePolicy": "WorkspaceAgnostic" }, - { - "id": "dispatch_provision_target", - "moduleId": "dispatch", - "capabilityId": "feature.detached-dispatch", - "capabilityIds": [ - "feature.detached-dispatch" - ], - "documentedItemIds": [ - "feature.detached-dispatch:provision" - ], - "visibility": "documented", - "rustPath": "api::dispatch_api::dispatch_provision_target", - "sourceFile": "src/apps/desktop/src/api/dispatch_api.rs", - "signature": "fn dispatch_provision_target( state: State<'_, AppState>, request: DispatchConnectionRequest, ) -> Result", - "remoteWorkspacePolicy": "WorkspaceAgnostic" - }, { "id": "dispatch_query", "moduleId": "dispatch", diff --git a/src/apps/cli/src/daemon/mod.rs b/src/apps/cli/src/daemon/mod.rs index 75cd6ea0d7..8c7dc74160 100644 --- a/src/apps/cli/src/daemon/mod.rs +++ b/src/apps/cli/src/daemon/mod.rs @@ -9,11 +9,9 @@ pub(crate) mod control; mod pid; -mod provision; mod runner; mod service; pub(crate) use pid::{is_daemon_running, request_daemon_shutdown}; -pub(crate) use provision::{deprovision, print_identity, provision}; pub(crate) use runner::run_daemon; pub(crate) use service::{install_service, print_status, uninstall_service}; diff --git a/src/apps/cli/src/daemon/provision.rs b/src/apps/cli/src/daemon/provision.rs deleted file mode 100644 index 7d4e22888a..0000000000 --- a/src/apps/cli/src/daemon/provision.rs +++ /dev/null @@ -1,219 +0,0 @@ -//! Narrow SSH bootstrap surface for an account-backed daemon. -//! -//! The controller first reads the non-secret machine identity, asks the relay -//! to mint a distinct device token, then stages one owner-only request file. -//! This command consumes and removes that file, re-encrypts the session with -//! this machine's key, and installs the platform service transactionally. - -use std::path::{Path, PathBuf}; - -use anyhow::{anyhow, Context, Result}; -use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; -use openbitfun_core::service::remote_connect::{ - session_store, validate_relay_base_url, DeviceIdentity, -}; -use openbitfun_services_core::dispatch_contract::{ - DispatchAccountDaemonIdentity, DispatchAccountDaemonProvisionRequest, - DispatchAccountDaemonProvisionResponse, DISPATCH_ACCOUNT_DAEMON_PROVISIONING_SCHEMA_VERSION, -}; - -const MAX_PROVISION_REQUEST_BYTES: u64 = 16 * 1024; - -struct ProvisionRequestGuard(PathBuf); - -impl Drop for ProvisionRequestGuard { - fn drop(&mut self) { - let _ = std::fs::remove_file(&self.0); - } -} - -pub(crate) fn print_identity() -> Result<()> { - let identity = DeviceIdentity::from_current_machine().context("resolve target identity")?; - let response = DispatchAccountDaemonIdentity { - device_id: identity.device_id, - device_name: identity.device_name, - }; - println!("{}", serde_json::to_string(&response)?); - Ok(()) -} - -pub(crate) fn provision(request_path: PathBuf) -> Result<()> { - ensure_private_request_file(&request_path)?; - let _request_guard = ProvisionRequestGuard(request_path.clone()); - let bytes = std::fs::read(&request_path).context("read daemon provisioning request")?; - let request: DispatchAccountDaemonProvisionRequest = - serde_json::from_slice(&bytes).context("decode daemon provisioning request")?; - let validated = validate_request(request)?; - - match session_store::load_session_detailed() { - Ok(None) => {} - Ok(Some(_)) => { - return Err(anyhow!( - "the target already has an account session; refusing to replace it" - )); - } - Err(error) => { - return Err(anyhow!( - "the target account session cannot be read; refusing to replace it: {error}" - )); - } - } - - session_store::save_session_with_device( - &validated.token, - &validated.user_id, - &validated.master_key, - &validated.relay_url, - Some(&validated.device_id), - ) - .context("persist provisioned account session")?; - - if let Err(error) = super::service::install_service_for_provisioning() { - let _ = super::service::uninstall_service_for_provisioning(); - session_store::clear_session(); - return Err(error).context("install persistent OpenBitFun daemon service"); - } - - let response = DispatchAccountDaemonProvisionResponse { - device_id: validated.device_id, - service_installed: true, - }; - println!("{}", serde_json::to_string(&response)?); - Ok(()) -} - -/// Roll back only the account/device named by the controller. This prevents a -/// stale failed operation from logging out an unrelated session that appeared -/// on the target in the meantime. -pub(crate) fn deprovision(device_id: String, user_id: String) -> Result<()> { - let existing = session_store::load_session_detailed().context("read target account session")?; - let Some(existing) = existing else { - println!("{{\"removed\":false}}"); - return Ok(()); - }; - if existing.device_id.as_deref() != Some(device_id.trim()) || existing.user_id != user_id.trim() - { - return Err(anyhow!( - "the target account session changed; refusing stale provisioning rollback" - )); - } - - let uninstall_result = super::service::uninstall_service_for_provisioning(); - session_store::clear_session(); - uninstall_result.context("remove persistent OpenBitFun daemon service")?; - println!("{{\"removed\":true}}"); - Ok(()) -} - -struct ValidatedProvisionRequest { - token: String, - user_id: String, - master_key: [u8; 32], - relay_url: String, - device_id: String, -} - -fn validate_request( - request: DispatchAccountDaemonProvisionRequest, -) -> Result { - if request.schema_version != DISPATCH_ACCOUNT_DAEMON_PROVISIONING_SCHEMA_VERSION { - return Err(anyhow!("unsupported daemon provisioning schema")); - } - if request.token.len() != 64 - || !request - .token - .bytes() - .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) - { - return Err(anyhow!("invalid account device token")); - } - if request.user_id.trim().is_empty() - || request.user_id.len() > 256 - || request.user_id.chars().any(char::is_control) - { - return Err(anyhow!("invalid account user id")); - } - - let identity = DeviceIdentity::from_current_machine().context("resolve target identity")?; - if request.device_id != identity.device_id { - return Err(anyhow!( - "daemon provisioning device identity does not match this target" - )); - } - - let master_key_bytes = BASE64 - .decode(request.master_key_base64.trim()) - .context("decode account master key")?; - let master_key: [u8; 32] = master_key_bytes - .try_into() - .map_err(|_| anyhow!("invalid account master key length"))?; - let relay_url = validate_relay_base_url(request.relay_url.trim())?; - let relay_url = relay_url.as_str().trim_end_matches('/').to_string(); - - Ok(ValidatedProvisionRequest { - token: request.token, - user_id: request.user_id.trim().to_string(), - master_key, - relay_url, - device_id: request.device_id, - }) -} - -fn ensure_private_request_file(path: &Path) -> Result<()> { - let metadata = - std::fs::symlink_metadata(path).context("inspect daemon provisioning request")?; - if !metadata.file_type().is_file() || metadata.len() > MAX_PROVISION_REQUEST_BYTES { - return Err(anyhow!("invalid daemon provisioning request file")); - } - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt; - if metadata.mode() & 0o077 != 0 || metadata.uid() != unsafe { libc::geteuid() } { - return Err(anyhow!( - "daemon provisioning request must be owned by the current user with mode 0600" - )); - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - #[cfg(unix)] - use super::*; - - #[test] - fn token_shape_is_lowercase_hex() { - let valid = "ab".repeat(32); - assert!(valid - .bytes() - .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))); - for invalid in ["A".repeat(64), "g".repeat(64), "a".repeat(63)] { - assert!( - invalid.len() != 64 - || !invalid - .bytes() - .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) - ); - } - } - - #[cfg(unix)] - #[test] - fn provisioning_request_must_be_owner_only_and_not_a_symlink() { - use std::os::unix::fs::{symlink, PermissionsExt}; - - let temp = tempfile::tempdir().unwrap(); - let request = temp.path().join("request.json"); - std::fs::write(&request, b"{}").unwrap(); - std::fs::set_permissions(&request, std::fs::Permissions::from_mode(0o644)).unwrap(); - assert!(ensure_private_request_file(&request).is_err()); - - std::fs::set_permissions(&request, std::fs::Permissions::from_mode(0o600)).unwrap(); - ensure_private_request_file(&request).unwrap(); - - let link = temp.path().join("request-link.json"); - symlink(&request, &link).unwrap(); - assert!(ensure_private_request_file(&link).is_err()); - } -} diff --git a/src/apps/cli/src/daemon/service.rs b/src/apps/cli/src/daemon/service.rs index 779b36f194..53ff6c166a 100644 --- a/src/apps/cli/src/daemon/service.rs +++ b/src/apps/cli/src/daemon/service.rs @@ -355,43 +355,6 @@ fn ensure_persisted_account_session() -> Result<()> { } } -/// Install without printing human-oriented output. The provisioning command -/// needs stdout to remain a single JSON document for the SSH controller. -pub(super) fn install_service_for_provisioning() -> Result { - let executable = current_exe_path()?; - let message = install_platform_service(&executable)?; - if let Err(error) = ensure_platform_service_persistent() { - if let Err(recovery) = uninstall_platform_service() { - return Err(error.context(format!("Daemon provisioning rollback failed; service registration was retained: {recovery:#}"))); - } - return Err(error); - } - Ok(message) -} - -/// Best-effort rollback companion for account provisioning. -pub(super) fn uninstall_service_for_provisioning() -> Result { - uninstall_platform_service() -} - -#[cfg(all(unix, not(target_os = "macos")))] -fn ensure_platform_service_persistent() -> Result<()> { - // SAFETY: getuid has no preconditions and does not dereference pointers. - let uid = unsafe { libc::getuid() }.to_string(); - let output = run_command("loginctl", &["show-user", &uid, "-p", "Linger", "--value"])?; - if output.status.success() && String::from_utf8_lossy(&output.stdout).trim() == "yes" { - return Ok(()); - } - Err(anyhow!( - "the daemon started, but login linger could not be enabled; refusing to claim reboot persistence" - )) -} - -#[cfg(any(target_os = "macos", not(unix)))] -fn ensure_platform_service_persistent() -> Result<()> { - Ok(()) -} - /// Stop and remove the auto-start service. pub(crate) fn uninstall_service() -> Result<()> { let message = uninstall_platform_service()?; diff --git a/src/apps/cli/src/dispatch/mod.rs b/src/apps/cli/src/dispatch/mod.rs index 53b5ffa122..8f19ee209e 100644 --- a/src/apps/cli/src/dispatch/mod.rs +++ b/src/apps/cli/src/dispatch/mod.rs @@ -178,10 +178,6 @@ async fn probe(request: DispatchProbeRequest) -> Result { openbitfun_services_core::dispatch_contract::DISPATCH_DETACHED_WORKER_CAPABILITY .to_string(), ); - capabilities.push( - openbitfun_services_core::dispatch_contract::DISPATCH_ACCOUNT_DAEMON_PROVISIONING_CAPABILITY - .to_string(), - ); } Ok(DispatchProbeResponse { product_id: openbitfun_services_core::product_identity::product_id().to_string(), diff --git a/src/apps/cli/src/main.rs b/src/apps/cli/src/main.rs index c43e678be1..d1bc4bdfab 100644 --- a/src/apps/cli/src/main.rs +++ b/src/apps/cli/src/main.rs @@ -759,12 +759,6 @@ enum DaemonAction { Uninstall, /// Show daemon and auto-start service status Status, - #[command(name = "__dispatch_identity", hide = true)] - DispatchIdentity, - #[command(name = "__dispatch_provision", hide = true)] - DispatchProvision { request_path: std::path::PathBuf }, - #[command(name = "__dispatch_deprovision", hide = true)] - DispatchDeprovision { device_id: String, user_id: String }, } #[derive(Subcommand)] @@ -1603,11 +1597,6 @@ async fn run_cli() -> Result<()> { DaemonAction::Install => daemon::install_service()?, DaemonAction::Uninstall => daemon::uninstall_service()?, DaemonAction::Status => daemon::print_status()?, - DaemonAction::DispatchIdentity => daemon::print_identity()?, - DaemonAction::DispatchProvision { request_path } => daemon::provision(request_path)?, - DaemonAction::DispatchDeprovision { device_id, user_id } => { - daemon::deprovision(device_id, user_id)? - } }, Some(Commands::Dispatch { action }) => { @@ -2409,63 +2398,6 @@ mod harness_profile_compatibility_tests { } } -#[cfg(test)] -mod daemon_command_tests { - use super::{Cli, Commands, DaemonAction}; - use clap::{CommandFactory, Parser}; - - #[test] - fn dispatch_daemon_bootstrap_commands_parse_and_stay_hidden() { - let identity = Cli::try_parse_from(["openbitfun", "daemon", "__dispatch_identity"]) - .expect("parse target identity command"); - assert!(matches!( - identity.command, - Some(Commands::Daemon { - action: DaemonAction::DispatchIdentity - }) - )); - - let provision = Cli::try_parse_from([ - "openbitfun", - "daemon", - "__dispatch_provision", - "/tmp/request.json", - ]) - .expect("parse target provisioning command"); - assert!(matches!( - provision.command, - Some(Commands::Daemon { - action: DaemonAction::DispatchProvision { ref request_path } - }) if request_path == std::path::Path::new("/tmp/request.json") - )); - - let rollback = Cli::try_parse_from([ - "openbitfun", - "daemon", - "__dispatch_deprovision", - "device-1", - "user-1", - ]) - .expect("parse target rollback command"); - assert!(matches!( - rollback.command, - Some(Commands::Daemon { - action: DaemonAction::DispatchDeprovision { - ref device_id, - ref user_id, - } - }) if device_id == "device-1" && user_id == "user-1" - )); - - let daemon_help = Cli::command() - .find_subcommand_mut("daemon") - .expect("daemon command") - .render_long_help() - .to_string(); - assert!(!daemon_help.contains("__dispatch_")); - } -} - /// Resolves the stable workspace record for a directory the CLI is operating in /// (its cwd, `--workspace`, or a command operand). Session and protocol routing /// must use the resulting record ID. diff --git a/src/apps/cli/src/peer_host/deny.rs b/src/apps/cli/src/peer_host/deny.rs index bbc1e1b5c1..33cd65211f 100644 --- a/src/apps/cli/src/peer_host/deny.rs +++ b/src/apps/cli/src/peer_host/deny.rs @@ -57,10 +57,6 @@ mod tests { for command in [ "dispatch_list_targets", "dispatch_probe_target", - "dispatch_install_cli_start", - "dispatch_install_cli_poll", - "dispatch_install_cli_cancel", - "dispatch_provision_target", "dispatch_sync_model_config", "dispatch_submit", "dispatch_status", diff --git a/src/apps/desktop/src/api/dispatch_api.rs b/src/apps/desktop/src/api/dispatch_api.rs index 40f6dbad1a..82d37b3de7 100644 --- a/src/apps/desktop/src/api/dispatch_api.rs +++ b/src/apps/desktop/src/api/dispatch_api.rs @@ -10,16 +10,13 @@ use async_trait::async_trait; use openbitfun_core::infrastructure::PathManager; use openbitfun_core::service::dispatch::{ answer_device_dispatch, answer_dispatch, append_device_dispatch, append_dispatch, - cancel_device_dispatch, cancel_dispatch, cancel_dispatch_cli_install, - continue_device_dispatch_job, continue_dispatch_job, decode_device_dispatch_response, - encode_device_dispatch_command, get_device_dispatch_status, get_dispatch_status, - list_device_dispatch_jobs, list_dispatch_jobs, list_dispatch_targets, - poll_dispatch_cli_install, probe_device_dispatch_target, probe_dispatch_target, - query_device_dispatch_job, query_dispatch_job, start_dispatch_cli_install, - submit_device_dispatch, submit_dispatch, sync_device_dispatch_result, + cancel_device_dispatch, cancel_dispatch, continue_device_dispatch_job, continue_dispatch_job, + decode_device_dispatch_response, encode_device_dispatch_command, get_device_dispatch_status, + get_dispatch_status, list_device_dispatch_jobs, list_dispatch_jobs, list_dispatch_targets, + probe_device_dispatch_target, probe_dispatch_target, query_device_dispatch_job, + query_dispatch_job, submit_device_dispatch, submit_dispatch, sync_device_dispatch_result, sync_dispatch_model_config, sync_dispatch_result, DeviceDispatchRpc, DispatchAnswerRequest, - DispatchAppendRequest, DispatchConnectionRequest, DispatchContinueRequest, - DispatchInstallPollRequest, DispatchInstallStartRequest, DispatchJobRequest, + DispatchAppendRequest, DispatchConnectionRequest, DispatchContinueRequest, DispatchJobRequest, DispatchListJobsRequest, DispatchListTargetsRequest, DispatchProbeTargetRequest, DispatchQueryJobRequest, DispatchSaveTranscriptRequest, DispatchStatusRequest, DispatchSubmitRequest, DispatchSyncResultRequest, DispatchTarget, DispatchTargetOption, @@ -29,11 +26,9 @@ use openbitfun_core::service::dispatch::{ execute_dispatch_control, DispatchAccountAccess, DispatchControlContext, }; use openbitfun_core::service::remote_connect::account_runtime::AccountDevice; -use openbitfun_core::service::remote_ssh::dispatch_ssh::{ - self, DispatchInstallPoll, DispatchInstallStart, DispatchSshProbe, -}; +use openbitfun_core::service::remote_ssh::dispatch_ssh::DispatchSshProbe; use openbitfun_product_domains::detached_dispatch_control::DetachedDispatchControlRequest; -use serde::{Deserialize, Serialize}; + use serde_json::Value; use tauri::State; @@ -123,9 +118,13 @@ pub async fn dispatch_list_targets( .get_ssh_manager_async() .await .map_err(|error| error.to_string())?; + let ssh_only = request.ssh_only; let mut targets = list_dispatch_targets(&manager, request) .await .map_err(|error| error.to_string())?; + if ssh_only { + return Ok(targets); + } let current_device_id = super::remote_connect_api::remote_connect_get_device_info() .await .ok() @@ -167,125 +166,6 @@ pub async fn dispatch_probe_target( .map_err(|error| error.to_string()) } -#[tauri::command] -pub async fn dispatch_install_cli_start( - state: State<'_, AppState>, - request: DispatchInstallStartRequest, -) -> Result { - let manager = state - .get_ssh_manager_async() - .await - .map_err(|error| error.to_string())?; - start_dispatch_cli_install(&manager, request) - .await - .map_err(|error| error.to_string()) -} - -#[tauri::command] -pub async fn dispatch_install_cli_poll( - state: State<'_, AppState>, - request: DispatchInstallPollRequest, -) -> Result { - let manager = state - .get_ssh_manager_async() - .await - .map_err(|error| error.to_string())?; - poll_dispatch_cli_install(&manager, request) - .await - .map_err(|error| error.to_string()) -} - -#[tauri::command] -pub async fn dispatch_install_cli_cancel( - state: State<'_, AppState>, - request: DispatchConnectionRequest, -) -> Result<(), String> { - let manager = state - .get_ssh_manager_async() - .await - .map_err(|error| error.to_string())?; - cancel_dispatch_cli_install(&manager, request) - .await - .map_err(|error| error.to_string()) -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum DispatchAccountBootstrapStatus { - Synced, - SkippedNotLoggedIn, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct DispatchProvisionTargetResult { - pub account_status: DispatchAccountBootstrapStatus, - pub daemon_installed: bool, -} - -/// Finish a freshly installed SSH target without exposing account secrets to -/// the renderer: mint a distinct relay device, stage its bootstrap over SFTP, -/// install the user service, and prove that it connected before returning. -#[tauri::command] -pub async fn dispatch_provision_target( - state: State<'_, AppState>, - request: DispatchConnectionRequest, -) -> Result { - let connection_id = request.connection_id.trim(); - if connection_id.is_empty() { - return Err("SSH connection id is required".to_string()); - } - let manager = state - .get_ssh_manager_async() - .await - .map_err(|error| error.to_string())?; - let identity = dispatch_ssh::account_daemon_identity(&manager, connection_id) - .await - .map_err(|error| error.to_string())?; - let Some(provisioning) = - super::remote_connect_api::provision_dispatch_account_device(&identity).await? - else { - return Ok(DispatchProvisionTargetResult { - account_status: DispatchAccountBootstrapStatus::SkippedNotLoggedIn, - daemon_installed: false, - }); - }; - - let provision_result = - dispatch_ssh::provision_account_daemon(&manager, connection_id, &provisioning.request) - .await; - if let Err(error) = provision_result { - let _ = dispatch_ssh::deprovision_account_daemon( - &manager, - connection_id, - provisioning.device_id(), - provisioning.user_id(), - ) - .await; - let _ = super::remote_connect_api::remove_dispatch_account_device(&provisioning).await; - return Err(format!("provision persistent OpenBitFun daemon: {error}")); - } - - if let Err(error) = - super::remote_connect_api::wait_for_dispatch_account_device_online(&provisioning).await - { - let _ = dispatch_ssh::deprovision_account_daemon( - &manager, - connection_id, - provisioning.device_id(), - provisioning.user_id(), - ) - .await; - let _ = super::remote_connect_api::remove_dispatch_account_device(&provisioning).await; - return Err(error); - } - - Ok(DispatchProvisionTargetResult { - account_status: DispatchAccountBootstrapStatus::Synced, - daemon_installed: true, - }) -} - #[tauri::command] pub async fn dispatch_sync_model_config( state: State<'_, AppState>, @@ -617,10 +497,7 @@ pub async fn dispatch_save_transcript( #[cfg(test)] mod tests { - use super::{ - decode_device_dispatch_response, DispatchAccountBootstrapStatus, - DispatchProvisionTargetResult, - }; + use super::decode_device_dispatch_response; fn decode_device_dispatch_rpc(raw: &str) -> anyhow::Result { decode_device_dispatch_response("dispatch_target_submit", raw) @@ -642,16 +519,4 @@ mod tests { assert!(rejected.to_string().contains("target rejected")); assert!(decode_device_dispatch_rpc(r#"{"sent":true}"#).is_err()); } - - #[test] - fn target_provisioning_response_is_redacted_and_stable() { - let value = serde_json::to_value(DispatchProvisionTargetResult { - account_status: DispatchAccountBootstrapStatus::Synced, - daemon_installed: true, - }) - .unwrap(); - assert_eq!(value["accountStatus"], "synced"); - assert_eq!(value["daemonInstalled"], true); - assert_eq!(value.as_object().unwrap().len(), 2); - } } diff --git a/src/apps/desktop/src/api/remote_connect_api.rs b/src/apps/desktop/src/api/remote_connect_api.rs index 2f9bf029a7..716945c5b3 100644 --- a/src/apps/desktop/src/api/remote_connect_api.rs +++ b/src/apps/desktop/src/api/remote_connect_api.rs @@ -1,15 +1,10 @@ //! Tauri commands for Remote Connect. use crate::embedded_relay_host::DesktopEmbeddedRelayHost; -use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; use openbitfun_core::agentic::tools::account_login_capability::set_account_login_available; use openbitfun_core::agentic::tools::page_deploy_host::set_page_deploy_handler; use openbitfun_core::agentic::tools::page_manage_host::set_page_manage_handler; use openbitfun_core::agentic::tools::page_publish_host::set_page_publish_handler; -use openbitfun_core::service::dispatch::{ - DispatchAccountDaemonIdentity, DispatchAccountDaemonProvisionRequest, - DISPATCH_ACCOUNT_DAEMON_PROVISIONING_SCHEMA_VERSION, -}; use openbitfun_core::service::remote_connect::session_store::{ clear_credential_hint, load_credential_hint, save_credential_hint, AccountHint, }; @@ -902,116 +897,6 @@ pub(crate) async fn read_account_context_for_generation( Ok(context) } -/// Secret-bearing, Rust-only handoff for one SSH target bootstrap. It is never -/// serialized through Tauri; only its redacted outcome reaches the Web UI. -pub(crate) struct DispatchAccountDeviceProvisioning { - pub(crate) request: DispatchAccountDaemonProvisionRequest, - target_session: AccountSession, - relay_url: String, -} - -impl DispatchAccountDeviceProvisioning { - pub(crate) fn device_id(&self) -> &str { - &self.request.device_id - } - - pub(crate) fn user_id(&self) -> &str { - &self.request.user_id - } -} - -/// Mint a distinct full device credential for an SSH host. Callers receive -/// `None` and skip account/daemon setup when this Desktop is logged out. -pub(crate) async fn provision_dispatch_account_device( - identity: &DispatchAccountDaemonIdentity, -) -> Result, String> { - let generation = account_context_generation(); - let Ok(_account_guard) = lock_account_operation(generation).await else { - return Ok(None); - }; - let (session, relay_url) = match read_account_context_for_generation(generation).await { - Ok(context) => context, - Err(error) if error == "not logged in" => return Ok(None), - Err(error) => return Err(error), - }; - let request_id = uuid::Uuid::new_v4(); - let target_secret = - openbitfun_services_integrations::remote_connect::device_crypto::provisioning_secret( - &session.master_key, - &identity.device_id, - &request_id.to_string(), - ); - let issued = AccountClient::new() - .provision_device_token( - &relay_url, - &session, - &identity.device_id, - &identity.device_name, - "desktop", - request_id, - &target_secret, - ) - .await - .map_err(|error| format!("provision remote account device: {error}"))?; - let target_session = - AccountSession::new(issued.token.clone(), issued.user_id.clone(), target_secret); - let provisioning = DispatchAccountDeviceProvisioning { - request: DispatchAccountDaemonProvisionRequest { - schema_version: DISPATCH_ACCOUNT_DAEMON_PROVISIONING_SCHEMA_VERSION, - token: issued.token, - user_id: issued.user_id, - master_key_base64: BASE64.encode(target_secret), - relay_url: relay_url.clone(), - device_id: issued.device_id, - }, - target_session, - relay_url, - }; - if !account_context_matches(generation, &session.token).await { - let _ = remove_dispatch_account_device(&provisioning).await; - return Err("account context changed while provisioning the SSH target".to_string()); - } - Ok(Some(provisioning)) -} - -pub(crate) async fn wait_for_dispatch_account_device_online( - provisioning: &DispatchAccountDeviceProvisioning, -) -> Result<(), String> { - let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30); - loop { - let devices = AccountClient::new() - .list_devices(&provisioning.relay_url, &provisioning.target_session) - .await - .map_err(|error| format!("verify remote daemon connection: {error}"))?; - if devices - .iter() - .any(|device| device.device_id == provisioning.request.device_id && device.online) - { - return Ok(()); - } - if tokio::time::Instant::now() >= deadline { - return Err( - "remote OpenBitFun daemon did not connect to the relay within 30 seconds" - .to_string(), - ); - } - tokio::time::sleep(std::time::Duration::from_millis(500)).await; - } -} - -pub(crate) async fn remove_dispatch_account_device( - provisioning: &DispatchAccountDeviceProvisioning, -) -> Result<(), String> { - AccountClient::new() - .delete_device( - &provisioning.relay_url, - &provisioning.target_session, - &provisioning.request.device_id, - ) - .await - .map_err(|error| format!("remove provisioned account device: {error}")) -} - async fn account_context_matches(generation: u64, token: &str) -> bool { if !account_context_is_current(generation) { return false; diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index fbe03d1f6d..642cb61b3e 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -2032,10 +2032,6 @@ pub async fn run() { // Detached task dispatch (controller-side SSH transport) api::dispatch_api::dispatch_list_targets, api::dispatch_api::dispatch_probe_target, - api::dispatch_api::dispatch_install_cli_start, - api::dispatch_api::dispatch_install_cli_poll, - api::dispatch_api::dispatch_install_cli_cancel, - api::dispatch_api::dispatch_provision_target, api::dispatch_api::dispatch_sync_model_config, api::dispatch_api::dispatch_submit, api::dispatch_api::dispatch_status, diff --git a/src/apps/server/src/routes/dispatch.rs b/src/apps/server/src/routes/dispatch.rs index 69d4def830..177323be03 100644 --- a/src/apps/server/src/routes/dispatch.rs +++ b/src/apps/server/src/routes/dispatch.rs @@ -8,13 +8,12 @@ use openbitfun_core::external_sources::{ ExternalSourceOperationError, ExternalSourceOperationErrorCode, ExternalSourceOperationResult, }; use openbitfun_core::service::dispatch::{ - answer_dispatch, append_dispatch, cancel_dispatch, cancel_dispatch_cli_install, - get_dispatch_status, list_dispatch_jobs, list_dispatch_targets, poll_dispatch_cli_install, - probe_dispatch_target, start_dispatch_cli_install, submit_dispatch, sync_dispatch_model_config, + answer_dispatch, append_dispatch, cancel_dispatch, get_dispatch_status, list_dispatch_jobs, + list_dispatch_targets, probe_dispatch_target, submit_dispatch, sync_dispatch_model_config, sync_dispatch_result, DispatchAnswerRequest, DispatchAppendRequest, DispatchConnectionRequest, - DispatchInstallPollRequest, DispatchInstallStartRequest, DispatchJobRequest, - DispatchListJobsRequest, DispatchListTargetsRequest, DispatchProbeTargetRequest, - DispatchStatusRequest, DispatchSubmitRequest, DispatchSyncResultRequest, OutboundDispatchStore, + DispatchJobRequest, DispatchListJobsRequest, DispatchListTargetsRequest, + DispatchProbeTargetRequest, DispatchStatusRequest, DispatchSubmitRequest, + DispatchSyncResultRequest, OutboundDispatchStore, }; use serde::de::DeserializeOwned; @@ -25,9 +24,6 @@ pub(crate) fn supports(method: &str) -> bool { method, "dispatch_list_targets" | "dispatch_probe_target" - | "dispatch_install_cli_start" - | "dispatch_install_cli_poll" - | "dispatch_install_cli_cancel" | "dispatch_sync_model_config" | "dispatch_submit" | "dispatch_status" @@ -69,29 +65,6 @@ pub(crate) async fn dispatch( .map_err(operation_error)?, ) } - "dispatch_install_cli_start" => { - let request = parse_request::(¶ms)?; - encode( - start_dispatch_cli_install(&host.ssh_manager, request) - .await - .map_err(operation_error)?, - ) - } - "dispatch_install_cli_poll" => { - let request = parse_request::(¶ms)?; - encode( - poll_dispatch_cli_install(&host.ssh_manager, request) - .await - .map_err(operation_error)?, - ) - } - "dispatch_install_cli_cancel" => { - let request = parse_request::(¶ms)?; - cancel_dispatch_cli_install(&host.ssh_manager, request) - .await - .map_err(operation_error)?; - Ok(serde_json::Value::Null) - } "dispatch_sync_model_config" => { let request = parse_request::(¶ms)?; sync_dispatch_model_config(&host.ssh_manager, request) @@ -191,9 +164,6 @@ mod tests { for method in [ "dispatch_list_targets", "dispatch_probe_target", - "dispatch_install_cli_start", - "dispatch_install_cli_poll", - "dispatch_install_cli_cancel", "dispatch_sync_model_config", "dispatch_submit", "dispatch_status", diff --git a/src/crates/assembly/core/src/service/dispatch/controller.rs b/src/crates/assembly/core/src/service/dispatch/controller.rs index 6cba97ca95..57dbcbc85d 100644 --- a/src/crates/assembly/core/src/service/dispatch/controller.rs +++ b/src/crates/assembly/core/src/service/dispatch/controller.rs @@ -1,7 +1,5 @@ use openbitfun_services_integrations::remote_ssh::{ - dispatch_ssh::{ - self, DispatchCliRelease, DispatchInstallPoll, DispatchInstallStart, DispatchSshProbe, - }, + dispatch_ssh::{self, DispatchSshProbe}, SSHConnectionManager, }; use serde::{Deserialize, Serialize}; @@ -26,7 +24,10 @@ pub(super) const MAX_DISPATCH_TEXT_BYTES: usize = 32 * 1024; #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct DispatchListTargetsRequest {} +pub struct DispatchListTargetsRequest { + #[serde(default)] + pub ssh_only: bool, +} #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -40,21 +41,6 @@ pub struct DispatchConnectionRequest { pub connection_id: String, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct DispatchInstallStartRequest { - pub connection_id: String, - pub release: DispatchCliRelease, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct DispatchInstallPollRequest { - pub connection_id: String, - #[serde(default)] - pub cursor: u64, -} - #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DispatchSubmitRequest { @@ -280,27 +266,6 @@ pub async fn probe_target( dispatch_ssh::probe(manager, &connection_id, nonempty(&workspace_path)).await } -pub async fn install_cli_start( - manager: &SSHConnectionManager, - request: DispatchInstallStartRequest, -) -> anyhow::Result { - dispatch_ssh::install_cli_start(manager, request.connection_id.trim(), &request.release).await -} - -pub async fn install_cli_poll( - manager: &SSHConnectionManager, - request: DispatchInstallPollRequest, -) -> anyhow::Result { - dispatch_ssh::install_cli_poll(manager, request.connection_id.trim(), request.cursor).await -} - -pub async fn install_cli_cancel( - manager: &SSHConnectionManager, - request: DispatchConnectionRequest, -) -> anyhow::Result<()> { - dispatch_ssh::install_cli_cancel(manager, request.connection_id.trim()).await -} - #[derive(Debug, thiserror::Error)] #[error("{reason}")] struct SubscriptionModelSyncUnsupported { @@ -549,7 +514,7 @@ pub async fn submit( WorktreeService::resolve_project_workspace_path(source_workspace_path) .await .map_err(|error| anyhow::anyhow!("resolve the dispatch project workspace: {error}"))?; - // One controller process at a time may install/provision/submit a job. The + // One controller process at a time may prepare and submit a job. The // JSON journal uses a different lock, so audit events can still be appended // atomically while this long-lived guard is held. let _preparation_run_lock = store.acquire_preparation_run_lock(&request.job_id).await?; @@ -576,40 +541,7 @@ pub async fn submit( }) .await?; - // Re-check the executable that will receive this submission, installing it - // when missing. The picker probe can be stale, and headless callers bypass - // the UI entirely. Every audit event is durably journaled before the - // corresponding remote mutation, then replayed into the target event log. - let audit_attempt = uuid::Uuid::new_v4().as_simple().to_string(); - let mut audit_sequence = 0_u32; - let audit_store = store.clone(); - let audit_job_id = request.job_id.clone(); - let cli_probe = - dispatch_ssh::ensure_target_cli(manager, connection_id, move |stage, release| { - audit_sequence = audit_sequence.saturating_add(1); - let event_id = format!("{audit_attempt}:{audit_sequence}"); - let stage = stage.to_string(); - let audit_store = audit_store.clone(); - let audit_job_id = audit_job_id.clone(); - async move { - log::info!("Dispatch SSH CLI install: stage={stage} details={release}"); - audit_store - .append_preparation_setup_audit( - &audit_job_id, - &event_id, - json!({ - "timestamp": chrono::Utc::now().to_rfc3339(), - "action": "cli-install", - "details": { - "stage": stage, - "release": release, - }, - }), - ) - .await - } - }) - .await?; + let cli_probe = dispatch_ssh::probe(manager, connection_id, None).await?; recover_interrupted_cli_install_audit(store, &request.job_id, &cli_probe).await?; let cli_protocol = cli_probe.protocol.as_ref().ok_or_else(|| { anyhow::anyhow!( diff --git a/src/crates/assembly/core/src/service/dispatch/mod.rs b/src/crates/assembly/core/src/service/dispatch/mod.rs index 36e1ee86c7..674c2ca579 100644 --- a/src/crates/assembly/core/src/service/dispatch/mod.rs +++ b/src/crates/assembly/core/src/service/dispatch/mod.rs @@ -54,17 +54,15 @@ pub use agent_control::{ #[cfg(all(feature = "agent-runtime", feature = "ssh-remote"))] pub use controller::{ answer as answer_dispatch, append as append_dispatch, cancel as cancel_dispatch, - continue_job as continue_dispatch_job, install_cli_cancel as cancel_dispatch_cli_install, - install_cli_poll as poll_dispatch_cli_install, install_cli_start as start_dispatch_cli_install, - list_jobs as list_dispatch_jobs, list_targets as list_dispatch_targets, - probe_target as probe_dispatch_target, query_job as query_dispatch_job, - status as get_dispatch_status, submit as submit_dispatch, + continue_job as continue_dispatch_job, list_jobs as list_dispatch_jobs, + list_targets as list_dispatch_targets, probe_target as probe_dispatch_target, + query_job as query_dispatch_job, status as get_dispatch_status, submit as submit_dispatch, sync_model_config as sync_dispatch_model_config, sync_result as sync_dispatch_result, DispatchAnswerRequest, DispatchAppendRequest, DispatchConnectionRequest, - DispatchContinueRequest, DispatchInstallPollRequest, DispatchInstallStartRequest, - DispatchJobRequest, DispatchListJobsRequest, DispatchListTargetsRequest, - DispatchPermissionReplyKind, DispatchProbeTargetRequest, DispatchQueryJobRequest, - DispatchStatusRequest, DispatchSubmitRequest, DispatchSyncResultRequest, DispatchTargetOption, + DispatchContinueRequest, DispatchJobRequest, DispatchListJobsRequest, + DispatchListTargetsRequest, DispatchPermissionReplyKind, DispatchProbeTargetRequest, + DispatchQueryJobRequest, DispatchStatusRequest, DispatchSubmitRequest, + DispatchSyncResultRequest, DispatchTargetOption, }; #[cfg(all(feature = "agent-runtime", feature = "ssh-remote"))] pub use device_controller::{ @@ -75,10 +73,6 @@ pub use device_controller::{ submit_device as submit_device_dispatch, sync_device_result as sync_device_dispatch_result, DeviceDispatchRpc, }; -pub use openbitfun_services_core::dispatch_contract::{ - DispatchAccountDaemonIdentity, DispatchAccountDaemonProvisionRequest, - DISPATCH_ACCOUNT_DAEMON_PROVISIONING_SCHEMA_VERSION, -}; pub use status_error::{ classify_target_status_error, is_target_job_not_found_message, DispatchJobNotFoundOnTarget, DISPATCH_JOB_NOT_FOUND_MARKER, 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 30197834b2..2cfcc7f07c 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": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", + "digest": "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c", "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { @@ -187,11 +187,11 @@ "features": 24, "settings": 23, "userFacing": 47, - "documentedItems": 369, + "documentedItems": 368, "controlCoverage": { "direct": 64, "delegated": 74, - "interactive": 231, + "interactive": 230, "unsupported": 0 } }, @@ -10247,7 +10247,6 @@ "capabilityId": "feature.detached-dispatch", "itemIds": [ "targets", - "provision", "model-sync", "submit", "status-list", @@ -10635,55 +10634,6 @@ } } }, - { - "id": "feature.detached-dispatch:open:provision", - "capabilityId": "feature.detached-dispatch", - "itemIds": [ - "provision" - ], - "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": "event", - "eventName": "openbitfun:open-remote-connect", - "detail": { - "group": "account" - } - } - }, { "id": "feature.detached-dispatch:open:model-sync", "capabilityId": "feature.detached-dispatch", @@ -28140,13 +28090,13 @@ "background host" ], "highlightsZh": [ - "一键列出同账号在线设备与已保存 SSH 主机作为派发目标", + "可选择已配置的 SSH 主机派发任务,智能体也可派发到同账号设备", "提交后控制端可随时断网或休眠,目标机在独立 Git Worktree 自治执行", "断线重连后按游标增量回填完整对话与工具轨迹,支持远程回答权限请求", "任务完成后可将目标端改动安全同步回本机,绝不把本机当成脆弱的文件代理" ], "highlightsEn": [ - "Discover same-account devices and saved SSH hosts as ready-to-run targets", + "Dispatch to a configured SSH host, or ask the Agent to dispatch to a same-account device", "Disconnect or close your laptop freely while the target works in an isolated Git worktree", "Replay missed events incrementally by cursor on reconnect and answer pending permissions remotely", "Sync completed changes back cleanly without turning your controller into a fragile file proxy" @@ -28164,17 +28114,6 @@ "options": [] } }, - { - "id": "provision", - "titleZh": "为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境", - "titleEn": "Provision the target host and install or update the OpenBitFun CLI", - "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "「为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境」涉及远端安装进度轮询、网络下载与中途取消控制;智能体会打开目标配置界面,由你确认并观察安装完成。", - "reasonEn": "\"Provision the target host and install or update the OpenBitFun CLI\" involves live remote installation polling and cancellation controls; the Agent opens the target provisioning flow so you can confirm and monitor setup." - } - }, { "id": "model-sync", "titleZh": "在派发前按需将任务所选的模型配置同步给目标主机", @@ -28258,15 +28197,15 @@ } ], "stepsZh": [ - "确保目标机器已登录同一账号在线,或已在本地保存好可用的 SSH 连接配置", - "在当前 Git 项目的聊天输入框底部点击「本机」芯片打开「这个任务在哪运行」菜单(或直接对智能体说明要派发到哪台设备),选定目标与权限审批策略", - "发送任务提示词;目标主机会自动准备环境、同步所需模型配置并在独立 Git Worktree 中启动执行", + "先在 SSH 目标上安装兼容的 OpenBitFun CLI,并保存 SSH 连接。", + "在聊天输入框底部点击「本机」,选择 SSH 主机。要派发到同账号设备时,直接告诉智能体目标设备和任务。", + "发送任务后,目标主机会同步所需的模型配置,并在独立的 Git worktree 中执行任务。", "执行期间可随时离线;重新打开会话即可查看最新进度、批复等待中的权限,完成后一键将结果同步回本机工作区" ], "stepsEn": [ - "Make sure your target device is signed in to the same account and online, or save an SSH connection profile first", - "Click the \"This computer\" chip at the bottom of the chat input to open the \"Where this task runs\" menu (or ask the agent explicitly to dispatch to a named device), and pick your target and approval policy", - "Submit your prompt; the target provisions its runtime if needed, syncs model settings, and starts working in a dedicated Git worktree", + "Install a compatible OpenBitFun CLI on the SSH target and save its SSH connection.", + "Select an SSH host from the This computer menu in the composer. To use a same-account device, ask the Agent to dispatch your task to that device.", + "Submit the task. The target syncs the required model configuration and runs the job in a dedicated Git worktree.", "Disconnect anytime; reopen the session later to catch up on streamed events, approve pending permissions, or sync finished changes back locally" ], "agentExamplesZh": [ @@ -28483,18 +28422,16 @@ "target host", "offline job", "background host", - "一键列出同账号在线设备与已保存 SSH 主机作为派发目标", + "可选择已配置的 SSH 主机派发任务,智能体也可派发到同账号设备", "提交后控制端可随时断网或休眠,目标机在独立 Git Worktree 自治执行", "断线重连后按游标增量回填完整对话与工具轨迹,支持远程回答权限请求", "任务完成后可将目标端改动安全同步回本机,绝不把本机当成脆弱的文件代理", - "Discover same-account devices and saved SSH hosts as ready-to-run targets", + "Dispatch to a configured SSH host, or ask the Agent to dispatch to a same-account device", "Disconnect or close your laptop freely while the target works in an isolated Git worktree", "Replay missed events incrementally by cursor on reconnect and answer pending permissions remotely", "Sync completed changes back cleanly without turning your controller into a fragile file proxy", "列出同账号下的所有设备与本机已保存的 SSH 目标", "List same-account devices and saved SSH dispatch targets", - "为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境", - "Provision the target host and install or update the OpenBitFun CLI", "在派发前按需将任务所选的模型配置同步给目标主机", "Sync required model configuration to the target before job submission", "从当前 Git 工作区向设备或 SSH 目标提交可离线运行的持久任务", 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 63db5cbc41..d40d769d6b 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:67a20e107dd93ffd", + "digest": "fnv1a64:1457e10fcdbf7a86", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -1765,42 +1765,6 @@ "reason": "the controller keeps this command; peer hosts refuse it before dispatch" } }, - { - "id": "dispatch_install_cli_cancel", - "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_install_cli_poll", - "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_install_cli_start", - "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_list_jobs", "surface": "tauri_command", @@ -1849,18 +1813,6 @@ "reason": "the controller keeps this command; peer hosts refuse it before dispatch" } }, - { - "id": "dispatch_provision_target", - "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_query", "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 a7e2635427..e39675ea3a 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -226,14 +226,10 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("dispatch_append", Agnostic, ControllerLocal, REFUSED), op("dispatch_cancel", Agnostic, ControllerLocal, REFUSED), op("dispatch_continue", Agnostic, ControllerLocal, REFUSED), - op("dispatch_install_cli_cancel", Agnostic, ControllerLocal, REFUSED), - op("dispatch_install_cli_poll", Agnostic, ControllerLocal, REFUSED), - op("dispatch_install_cli_start", Agnostic, ControllerLocal, REFUSED), op("dispatch_list_jobs", Agnostic, ControllerLocal, REFUSED), op("dispatch_list_targets", Agnostic, ControllerLocal, REFUSED), op("dispatch_load_transcript", Agnostic, ControllerLocal, REFUSED), op("dispatch_probe_target", Agnostic, ControllerLocal, REFUSED), - op("dispatch_provision_target", Agnostic, ControllerLocal, REFUSED), op("dispatch_query", Agnostic, ControllerLocal, REFUSED), op("dispatch_save_transcript", Agnostic, ControllerLocal, REFUSED), op("dispatch_status", Agnostic, ControllerLocal, REFUSED), diff --git a/src/crates/services/services-core/src/dispatch_contract.rs b/src/crates/services/services-core/src/dispatch_contract.rs index 7326f9d9dd..74ab6bb746 100644 --- a/src/crates/services/services-core/src/dispatch_contract.rs +++ b/src/crates/services/services-core/src/dispatch_contract.rs @@ -63,15 +63,6 @@ pub const DISPATCH_SUBSCRIPTION_ACCOUNT_CAPABILITIES: &[&str] = &[ DISPATCH_SUBSCRIPTION_PROVIDER_ACCOUNTS_CAPABILITY, ]; -/// Optional capability for an SSH controller to turn a freshly installed CLI -/// into an account-backed, always-on device. It is deliberately not part of -/// [`dispatch_required_target_capabilities`]: detached SSH jobs work without -/// an account daemon, while one-click account provisioning must fail closed on -/// older CLIs that do not understand the secret-bearing bootstrap contract. -pub const DISPATCH_ACCOUNT_DAEMON_PROVISIONING_CAPABILITY: &str = "account_daemon_provisioning"; - -pub const DISPATCH_ACCOUNT_DAEMON_PROVISIONING_SCHEMA_VERSION: u32 = 1; - /// Setup-audit action every target has accepted since the audit channel /// existed. A target rejects a submission carrying any action it does not /// know, so this list — not the controller's journal — bounds what may be @@ -137,37 +128,6 @@ pub fn dispatch_supported_setup_audit_actions() -> impl Iterator impl Iterator { @@ -258,7 +218,6 @@ mod tests { for capability in DISPATCH_BASE_TARGET_CAPABILITIES { assert!(required.contains(capability)); } - assert!(!required.contains(&DISPATCH_ACCOUNT_DAEMON_PROVISIONING_CAPABILITY)); assert!(!required.contains(&DISPATCH_SETUP_AUDIT_MODEL_SYNC_CAPABILITY)); assert!(!required.contains(&DISPATCH_READ_FILE_CAPABILITY)); } @@ -293,18 +252,4 @@ mod tests { assert!(supported.contains(action)); } } - - #[test] - fn account_daemon_bootstrap_contract_rejects_unknown_fields() { - let value = serde_json::json!({ - "schemaVersion": DISPATCH_ACCOUNT_DAEMON_PROVISIONING_SCHEMA_VERSION, - "token": "a".repeat(64), - "userId": "user-1", - "masterKeyBase64": "key", - "relayUrl": "https://relay.example.test", - "deviceId": "b".repeat(32), - "unexpected": true, - }); - assert!(serde_json::from_value::(value).is_err()); - } } diff --git a/src/crates/services/services-integrations/Cargo.toml b/src/crates/services/services-integrations/Cargo.toml index 585ba53e25..e3a63d008d 100644 --- a/src/crates/services/services-integrations/Cargo.toml +++ b/src/crates/services/services-integrations/Cargo.toml @@ -43,7 +43,6 @@ git2 = { workspace = true, optional = true } hostname = { workspace = true, optional = true } image = { workspace = true, optional = true } hex = { workspace = true, optional = true } -minisign-verify = { version = "0.2", optional = true } libc = { workspace = true, optional = true } local-ip-address = { workspace = true, optional = true } mac_address = { workspace = true, optional = true } @@ -360,7 +359,6 @@ remote-ssh-concrete = [ "dep:openbitfun-runtime-ports", "chrono", "dirs", - "minisign-verify", "rand", "reqwest", "reqwest/rustls-no-provider", diff --git a/src/crates/services/services-integrations/src/remote_connect/account.rs b/src/crates/services/services-integrations/src/remote_connect/account.rs index f7b874aed4..0efd3e0dc4 100644 --- a/src/crates/services/services-integrations/src/remote_connect/account.rs +++ b/src/crates/services/services-integrations/src/remote_connect/account.rs @@ -375,16 +375,6 @@ pub struct DelegateToken { pub device_secret: [u8; 32], } -/// Full device credential minted for a distinct SSH host. Unlike -/// [`DelegateToken`], this token may authenticate a device WebSocket and is -/// therefore only issued by the narrow authenticated provisioning endpoint. -#[derive(Clone, Serialize, Deserialize)] -pub struct ProvisionedDeviceToken { - pub token: String, - pub user_id: String, - pub device_id: String, -} - // ── Relay HTTP client ─────────────────────────────────────────────────── #[derive(Deserialize)] @@ -710,51 +700,6 @@ impl AccountClient { }) } - /// Register a new account device and mint its full routing token. - /// - /// `device_kind` is what keeps the minted row out of the wrong lists: this - /// route serves both an SSH host being bootstrapped (`"desktop"`) and a - /// keyboard-less peer that cannot type a password (`"watch"`), and only the - /// caller knows which one it is holding. - /// `request_id` makes an ambiguous HTTP response safe to replay. - pub async fn provision_device_token( - &self, - relay_url: &str, - session: &AccountSession, - device_id: &str, - device_name: &str, - device_kind: &str, - request_id: uuid::Uuid, - device_secret: &[u8; 32], - ) -> Result { - let body = serde_json::json!({ - "device_id": device_id, - "device_name": device_name, - "device_kind": device_kind, - "public_key": device_crypto::public_key_base64(device_secret), - "request_id": request_id.to_string(), - }); - let resp = send_with_retry( - "provision account device", - self.http - .post(Self::endpoint(relay_url, "/api/auth/provision-device")?) - .header("Authorization", Self::auth_header(session)) - .json(&body), - RelayHttpRetry::IdempotentWrite, - ) - .await?; - if !resp.status().is_success() { - return Err(Self::into_buffered_error(resp)); - } - let provisioned: ProvisionedDeviceToken = resp.json().await?; - if provisioned.user_id != session.user_id || provisioned.device_id != device_id { - return Err(anyhow!( - "relay returned a mismatched provisioned device identity" - )); - } - Ok(provisioned) - } - /// Revoke the account token on the relay (server-side logout). pub async fn revoke_token(&self, relay_url: &str, session: &AccountSession) -> Result<()> { let resp = send_with_retry( diff --git a/src/crates/services/services-integrations/src/remote_connect/device_crypto.rs b/src/crates/services/services-integrations/src/remote_connect/device_crypto.rs index da83b78b19..4fc5f17ac9 100644 --- a/src/crates/services/services-integrations/src/remote_connect/device_crypto.rs +++ b/src/crates/services/services-integrations/src/remote_connect/device_crypto.rs @@ -14,24 +14,6 @@ pub fn generate_secret() -> [u8; 32] { StaticSecret::random_from_rng(rand::rngs::OsRng).to_bytes() } -/// Derive a distinct bootstrap key that is stable for an idempotent request. -/// Knowledge of the target key does not reveal the provisioning device's key. -pub fn provisioning_secret( - parent_secret: &[u8; 32], - device_id: &str, - request_id: &str, -) -> [u8; 32] { - let mut secret = [0; 32]; - let info = format!("{device_id}:{request_id}"); - Hkdf::::new( - Some(b"OpenBitFun device provisioning v1.0.0"), - parent_secret, - ) - .expand(info.as_bytes(), &mut secret) - .expect("32-byte HKDF output is valid"); - secret -} - pub fn public_key(secret: &[u8; 32]) -> [u8; 32] { PublicKey::from(&StaticSecret::from(*secret)).to_bytes() } @@ -68,16 +50,6 @@ mod tests { use super::*; use crate::remote_connect::encryption::{decrypt_from_base64, encrypt_to_base64}; - #[test] - fn provisioning_keys_are_isolated_and_replayable() { - let parent = [7; 32]; - let key = provisioning_secret(&parent, "target", "request"); - assert_ne!(key, parent); - assert_eq!(key, provisioning_secret(&parent, "target", "request")); - assert_ne!(key, provisioning_secret(&parent, "other", "request")); - assert_ne!(key, provisioning_secret(&parent, "target", "other")); - } - #[test] fn messages_round_trip_between_independent_devices_only() { let alice = [7; 32]; diff --git a/src/crates/services/services-integrations/src/remote_ssh/disabled.rs b/src/crates/services/services-integrations/src/remote_ssh/disabled.rs index 013a073a39..82cc84a07c 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/disabled.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/disabled.rs @@ -50,32 +50,6 @@ pub mod dispatch_ssh { pub protocol: Option, } - #[derive(Debug, Clone, Serialize, Deserialize)] - #[serde(rename_all = "camelCase")] - pub struct DispatchInstallStart { - pub script_path: String, - pub version: String, - pub target: String, - pub url: String, - pub sha256: String, - } - - #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] - #[serde(rename_all = "snake_case")] - pub enum DispatchInstallStatus { - Running, - Succeeded, - Failed, - } - - #[derive(Debug, Clone, Serialize, Deserialize)] - #[serde(rename_all = "camelCase")] - pub struct DispatchInstallPoll { - pub cursor: u64, - pub output: String, - pub status: DispatchInstallStatus, - } - pub async fn probe( _manager: &SSHConnectionManager, _connection_id: &str, @@ -84,29 +58,6 @@ pub mod dispatch_ssh { Err(unsupported()) } - pub async fn install_cli_start( - _manager: &SSHConnectionManager, - _connection_id: &str, - _expected_release: &DispatchCliRelease, - ) -> anyhow::Result { - Err(unsupported()) - } - - pub async fn install_cli_poll( - _manager: &SSHConnectionManager, - _connection_id: &str, - _cursor: u64, - ) -> anyhow::Result { - Err(unsupported()) - } - - pub async fn install_cli_cancel( - _manager: &SSHConnectionManager, - _connection_id: &str, - ) -> anyhow::Result<()> { - Err(unsupported()) - } - pub async fn submit( _manager: &SSHConnectionManager, _connection_id: &str, diff --git a/src/crates/services/services-integrations/src/remote_ssh/dispatch_ssh.rs b/src/crates/services/services-integrations/src/remote_ssh/dispatch_ssh.rs index 11cc0d0b07..4828afa3aa 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/dispatch_ssh.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/dispatch_ssh.rs @@ -3,61 +3,24 @@ //! The target-side runner is the `openbitfun dispatch` CLI surface. This module is //! deliberately only a controller transport: the remote CLI owns jobs, //! workspaces, sessions, transcripts, process detachment, supervision, and -//! cancellation semantics. +//! cancellation semantics. Submission probes the existing target CLI before workspace delivery. //! -//! `probe` is read-only. Submission may automatically install the latest -//! compatible prebuilt release when the target is missing a compatible CLI; -//! `install_cli_start` still verifies the signed SHA256 sidecar and mandatory -//! archive minisign signature before staging an owner-only installer. Source -//! builds remain a separate, explicitly confirmed operation. use anyhow::{anyhow, Context, Result}; use base64::Engine as _; -use openbitfun_services_core::dispatch_contract::{ - DispatchAccountDaemonIdentity, DispatchAccountDaemonProvisionRequest, - DispatchAccountDaemonProvisionResponse, DISPATCH_ACCOUNT_DAEMON_PROVISIONING_CAPABILITY, -}; use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest, Sha256}; -use std::future::Future; use std::time::Duration; use super::manager::SSHConnectionManager; -use super::product_paths::{ - product_data_path, product_data_relative_path, product_home_shell_path, -}; -use super::release_verify::{ - parse_sha256, release_tag_for_version, require_release_pubkey, verify_minisign, verify_sha256, - verify_signed_checksum, -}; +use super::product_paths::product_data_path; use super::remote_git::shell_quote_posix; use super::types::SSHCommandOptions; -const GITHUB_RELEASE_BASE: &str = "https://github.com/openBitFun/OpenBitFun/releases"; -const OPENBITFUN_RELEASE_BASE: &str = "https://openbitfun.com/release"; -const GITHUB_LATEST_MANIFEST: &str = - "https://github.com/openBitFun/OpenBitFun/releases/latest/download/latest-v1.json"; -const OPENBITFUN_LATEST_MANIFEST: &str = "https://openbitfun.com/release/latest-v1.json"; -const INSTALL_STEM: &str = "install-cli"; -const INSTALL_DONE_MARKER: &str = "OPENBITFUN_DISPATCH_CLI_INSTALL_DONE"; -const INSTALL_PREPARE_GRACE_SECONDS: u64 = 30; const COMMAND_TIMEOUT_MS: u64 = 30_000; -const ACCOUNT_DAEMON_COMMAND_TIMEOUT_MS: u64 = 90_000; const WORKSPACE_OPERATION_WAIT: Duration = Duration::from_secs(30 * 60); const WORKSPACE_OPERATION_POLL_INTERVAL: Duration = Duration::from_millis(750); -/// A release archive is tens of megabytes and the target's uplink is unknown, -/// so this is far longer than an ordinary setup command. -const TARGET_DOWNLOAD_TIMEOUT_MS: u64 = 10 * 60 * 1000; -const CLI_INSTALL_POLL_INTERVAL: Duration = Duration::from_millis(750); -/// A source-free release install is a download plus an unpack; anything past -/// this is a hung target rather than a slow one. -const CLI_INSTALL_WAIT: Duration = Duration::from_secs(15 * 60); -const RELEASE_READ_TIMEOUT_SECONDS: u64 = 30; -const RELEASE_PROBE_WINDOW: Duration = Duration::from_secs(10); -const RELEASE_PROBE_BYTES: u64 = 4 * 1024 * 1024; -const GITHUB_HEALTHY_THROUGHPUT: u64 = 512 * 1024; -const MAX_ARCHIVE_BYTES: usize = 512 * 1024 * 1024; /// A result bundle carries only commits since the dispatch baseline, so it is /// bounded well below a full repository clone in the usual case. const MAX_RESULT_BUNDLE_BYTES: u64 = 1024 * 1024 * 1024; @@ -89,18 +52,8 @@ impl Drop for UnverifiedResultBundle { } } } -/// Oldest glibc the published Linux binaries run against. Kept in step with -/// `scripts/ci/check-glibc-floor.sh`, which enforces it at release time. -const GLIBC_FLOOR: &str = "2.35"; const DISPATCH_PROTOCOL_VERSION: u64 = openbitfun_services_core::dispatch_contract::DISPATCH_PROTOCOL_VERSION as u64; -/// First stable release whose CLI is known to contain every capability below. -/// -/// Development builds can require capabilities before their next stable -/// version is published. In that window `CARGO_PKG_VERSION` still names the -/// previous release, so comparing only the installed and controller version -/// strings is not a sound compatibility test. -const FIRST_COMPATIBLE_STABLE_DISPATCH_RELEASE: (u64, u64, u64) = (1, 0, 0); /// Derived once from the shared contract: the unconditional target surface /// plus the platform-conditional detached worker. static REQUIRED_DISPATCH_CAPABILITIES: std::sync::LazyLock> = @@ -109,10 +62,6 @@ static REQUIRED_DISPATCH_CAPABILITIES: std::sync::LazyLock> = .collect() }); -fn install_state_relative_dir() -> String { - product_data_relative_path(&["dispatch", "install"]) -} - #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DispatchCliRelease { @@ -134,117 +83,19 @@ pub struct DispatchSshProbe { pub protocol_error: Option, pub release: Option, pub protocol: Option, - /// Present only when the published binaries cannot run here, so the UI can - /// explain why instead of offering an install that would fail the same way. + /// Legacy probe field retained for older controllers. pub prebuilt_incompatible: Option, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct DispatchInstallStart { - /// Absolute path of the staged driver. The task has already been launched; - /// this path is returned for diagnostics and must not be executed again. - pub script_path: String, - pub version: String, - pub target: String, - pub url: String, - pub sha256: String, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum DispatchInstallStatus { - Running, - Succeeded, - Failed, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct DispatchInstallPoll { - pub cursor: u64, - pub output: String, - pub status: DispatchInstallStatus, -} - #[derive(Debug)] struct RemoteTarget { os: String, arch: String, home: String, cli_path: Option, - tar_available: bool, - /// Fetcher the target can use to pull the release itself, if any. - downloader: Option, - /// Command the target can use to check a SHA256 digest, if any. - digest_tool: Option, - /// C library family on Linux targets; `None` off Linux or when unknown. - libc: Option, - /// glibc version, when the target reported one. - libc_version: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum RemoteLibc { - Glibc, - Musl, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum RemoteDownloader { - Curl, - Wget, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum RemoteDigestTool { - /// GNU coreutils, present on Linux. - Sha256Sum, - /// Perl-based, what macOS ships instead. - Shasum, -} - -#[derive(Debug)] -struct ResolvedRelease { - public: DispatchCliRelease, - filename: String, - sources: Vec, - /// Whether `public.sha256` came from a minisign signature this machine - /// verified, rather than from an unauthenticated sidecar. - /// - /// The target has no minisign and no trust root, so letting it fetch the - /// archive itself is only safe when the digest we hand it is provably the - /// publisher's. Without that proof the archive's own signature is the only - /// protection, and only this machine can check it. - checksum_signature_verified: bool, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ReleaseOrigin { - GitHub, - OpenBitFun, -} - -#[derive(Debug, Clone)] -struct ReleaseArtifactSource { - origin: ReleaseOrigin, - url: String, - checksum_url: String, - checksum_signature_url: String, - archive_signature_url: String, -} - -#[derive(Debug, Deserialize)] -struct LatestReleaseManifest { - version: String, } -/// Probe the remote OS/architecture and, when present, the target CLI dispatch -/// protocol. A missing or old CLI is a normal result rather than an error. -/// -/// Release metadata is resolved only when installation or upgrade is needed. -/// Resolving it verifies the signature over the SHA256 sidecar so the UI can -/// safely show the exact URL, version, and digest before asking for consent. +/// Inspect the target platform and the capabilities of its installed CLI. pub async fn probe( manager: &SSHConnectionManager, connection_id: &str, @@ -279,164 +130,28 @@ pub async fn probe( } } - let needs_install = target.cli_path.is_none() - || !protocol - .as_ref() - .is_some_and(dispatch_protocol_is_compatible); - // A platform mismatch is decided before any network work: no release exists - // that would install successfully, so resolving one only hides the reason. - let incompatibility = needs_install - .then(|| prebuilt_incompatibility(&target)) - .flatten(); - let (release, install_error) = if needs_install { - if let Some(incompatibility) = &incompatibility { - (None, Some(incompatibility.describe())) - } else if !target.tar_available { - ( - None, - Some("remote target has no tar executable; install tar and retry".to_string()), - ) - } else { - match resolve_release(&target.os, &target.arch).await { - // Capability support is a fact about the published artifact, - // not about whether its semver happens to equal the installed - // binary. A locally or previously source-built CLI may share a - // version string with a different artifact. - Ok(release) - if published_release_supports_required_dispatch_protocol( - &release.public.version, - ) => - { - (Some(release.public), None) - } - Ok(release) => ( - None, - Some(format!( - "published OpenBitFun CLI {} does not carry the dispatch capabilities this controller requires", - release.public.version - )), - ), - Err(error) => (None, Some(error.to_string())), - } - } - } else { - (None, None) - }; - let install_supported = release.is_some(); - Ok(DispatchSshProbe { cli_installed: target.cli_path.is_some(), cli_path: target.cli_path, os: target.os, arch: target.arch, - install_supported, - install_error, + install_supported: false, + install_error: None, protocol_error, - release, + release: None, protocol, - prebuilt_incompatible: incompatibility - .as_ref() - .map(PrebuiltIncompatibility::describe), + prebuilt_incompatible: None, }) } -/// Why the published binaries cannot run on this target. -/// -/// Kept structured rather than a flat string so the UI can say what is actually -/// wrong instead of leaving the user with an unexplained failure. -#[derive(Debug, Clone, PartialEq, Eq)] -enum PrebuiltIncompatibility { - UnsupportedPlatform { os: String, arch: String }, - MuslLibc, - GlibcTooOld { found: String }, -} - -impl PrebuiltIncompatibility { - fn describe(&self) -> String { - match self { - Self::UnsupportedPlatform { os, arch } => format!( - "OpenBitFun publishes no CLI binary for {os} {arch}" - ), - Self::MuslLibc => format!( - "target uses musl libc; published binaries are linked against glibc {GLIBC_FLOOR} or newer" - ), - Self::GlibcTooOld { found } => format!( - "target has glibc {found}; published binaries require {GLIBC_FLOOR} or newer" - ), - } - } -} - -/// Detect an incompatibility that no amount of reinstalling can fix. -fn prebuilt_incompatibility(target: &RemoteTarget) -> Option { - if release_target(&target.os, &target.arch).is_err() { - return Some(PrebuiltIncompatibility::UnsupportedPlatform { - os: target.os.clone(), - arch: target.arch.clone(), - }); - } - // Only Linux binaries carry a libc requirement; macOS builds do not. - if !target.os.trim().eq_ignore_ascii_case("Linux") { - return None; - } - match target.libc { - Some(RemoteLibc::Musl) => Some(PrebuiltIncompatibility::MuslLibc), - Some(RemoteLibc::Glibc) => { - let found = target.libc_version.as_deref()?; - (compare_versions(found, GLIBC_FLOOR) == std::cmp::Ordering::Less).then(|| { - PrebuiltIncompatibility::GlibcTooOld { - found: found.to_string(), - } - }) - } - None => None, - } -} - -/// Numeric dotted-version comparison. `2.9` must order below `2.35`, which a -/// lexicographic comparison would get backwards. -fn compare_versions(left: &str, right: &str) -> std::cmp::Ordering { - let parse = |value: &str| { - value - .split('.') - .map(|part| part.trim().parse::().unwrap_or(0)) - .collect::>() - }; - let (left, right) = (parse(left), parse(right)); - for index in 0..left.len().max(right.len()) { - let ordering = left - .get(index) - .copied() - .unwrap_or(0) - .cmp(&right.get(index).copied().unwrap_or(0)); - if ordering != std::cmp::Ordering::Equal { - return ordering; - } - } - std::cmp::Ordering::Equal -} - -/// Whether a published artifact is expected to implement the controller's -/// required protocol. -/// -/// OpenBitFun starts at 1.0.0. No OpenBitFun 0.x artifact is a compatible install -/// candidate, even if it was built from a checkout that happened to carry a -/// similar dispatch surface. -fn published_release_supports_required_dispatch_protocol(version: &str) -> bool { - let Ok(parsed) = semver::Version::parse(version) else { - return false; - }; - parsed.pre.is_empty() - && (parsed.major, parsed.minor, parsed.patch) >= FIRST_COMPATIBLE_STABLE_DISPATCH_RELEASE -} - +#[cfg(test)] fn dispatch_protocol_is_compatible(protocol: &Value) -> bool { validate_dispatch_protocol(protocol, None).is_ok() } /// Validate the target-side protocol immediately before submission. /// -/// `approval_policy = None` is used by installation probing and requires the +/// `approval_policy = None` is used by the readiness probe and requires the /// complete dispatch surface. Submission may validate only the selected /// unattended approval behavior in addition to the transport invariants. pub fn validate_dispatch_protocol(protocol: &Value, approval_policy: Option<&str>) -> Result<()> { @@ -508,889 +223,201 @@ pub fn validate_dispatch_protocol(protocol: &Value, approval_policy: Option<&str Ok(()) } -/// Explicitly install the latest confirmed OpenBitFun CLI release on the SSH target. +/// Keys of the `ai` config section that make up "model configuration": the +/// model catalog (credentials included) plus every default-selection table the +/// target consults when resolving a ready model. +const MODEL_CONFIG_KEYS: [&str; 5] = [ + "models", + "default_models", + "agent_model_defaults", + "agent_model_selections", + "model_pools", +]; + +/// Write the controller's model configuration into the target's global config +/// so `openbitfun dispatch probe` can report a ready model. /// -/// This function fails closed when the build has no release trust root, a -/// checksum/signature is absent, or either verification fails. It never uses -/// sudo and writes only below `~/.local/bin` and `~/.openbitfun`. -pub async fn install_cli_start( +/// `ai_model_config` is the snake_case `ai` slice restricted to +/// [`MODEL_CONFIG_KEYS`], exactly as `app.json` stores it. Everything else in +/// an existing target `app.json` is preserved; a target file that exists but +/// cannot be read or parsed aborts the sync instead of being overwritten. The +/// write is atomic (temp file + rename) and owner-only, because model entries +/// carry API credentials. +pub async fn sync_model_config( manager: &SSHConnectionManager, connection_id: &str, - expected_release: &DispatchCliRelease, -) -> Result { + ai_model_config: &Value, +) -> Result<()> { + let payload = validate_model_config_payload(ai_model_config)?; ensure_plain_ssh_target(manager, connection_id).await?; - let target = probe_remote_target(manager, connection_id).await?; - if !target.tar_available { + + let locate = exec_lines(manager, connection_id, locate_target_config_script()).await?; + let get = |key: &str| { + locate + .lines() + .find_map(|line| { + line.strip_prefix(key) + .and_then(|rest| rest.strip_prefix('=')) + }) + .unwrap_or("") + .trim() + .to_string() + }; + if get("os") == "unsupported" { return Err(anyhow!( - "remote target has no tar executable; install tar and retry" + "model configuration sync supports only Linux and macOS SSH targets" )); } - let release = resolve_release(&target.os, &target.arch).await?; - if !published_release_supports_required_dispatch_protocol(&release.public.version) { + let config_dir = get("dir"); + if config_dir.is_empty() { return Err(anyhow!( - "published OpenBitFun CLI {} does not contain the dispatch capabilities required by this controller", - release.public.version + "could not resolve the target OpenBitFun config directory" )); } - ensure_confirmed_release(&release.public, expected_release)?; - - // Stop an earlier attempt before replacing any of its staged files. A - // cancellation transport error is not safe to ignore: the old installer - // may still be reading the archive or paths this attempt would replace. - install_cli_cancel(manager, connection_id) - .await - .context("stop an earlier OpenBitFun CLI installation")?; + let config_path = format!("{config_dir}/app.json"); - let dir = product_data_path(&target.home, &["dispatch", "install"]); - let archive_path = format!("{dir}/{}", release.filename); - let body_path = format!("{dir}/{INSTALL_STEM}-body.sh"); - let script_path = format!("{dir}/{INSTALL_STEM}.sh"); - let install_token = format!( - "{}-install-{}", - openbitfun_services_core::product_identity::data_namespace(), - uuid::Uuid::new_v4().as_simple() - ); + let existing = if get("config") == "1" { + let bytes = manager + .sftp_read(connection_id, &config_path) + .await + .context("read existing target app.json; refusing to overwrite it blindly")?; + Some(String::from_utf8(bytes).context("target app.json is not UTF-8")?) + } else { + None + }; + let merged = merge_model_config(existing.as_deref(), payload)?; exec_ok( manager, connection_id, &format!( - "mkdir -p {dir} && chmod 700 {root} {dispatch} {dir}", - root = shell_quote_posix(&product_data_path(&target.home, &[])), - dispatch = shell_quote_posix(&product_data_path(&target.home, &["dispatch"])), - dir = shell_quote_posix(&dir), + "mkdir -p {dir} && chmod 700 \"$(dirname {dir})\" {dir}", + dir = shell_quote_posix(&config_dir), ), ) .await?; - - // Prefer letting the target pull the release straight from the publisher: - // the controller's uplink is usually the slowest hop, and pushing tens of - // megabytes through it is the worst available topology. Fall back to the - // push path whenever that is not safely possible. - let archive_source = match target_download_blocker(&target, &release) { - Some(reason) => ArchiveSource::ControllerPush { reason }, - None => match download_archive_on_target( - manager, - connection_id, - &target, - &release, - &archive_path, - ) + let data_namespace = openbitfun_services_core::product_identity::data_namespace(); + let staging_path = format!("{config_path}.{data_namespace}-sync.tmp"); + manager + .sftp_write(connection_id, &staging_path, merged.as_bytes()) .await - { - Ok(()) => ArchiveSource::TargetDownload, - Err(error) => ArchiveSource::ControllerPush { - reason: bounded_detail(&error.to_string()), - }, - }, - }; - - let body = to_unix_script(&install_body_script( - &dir, - &archive_path, - &release.public.version, - &archive_source, - )); - let driver = to_unix_script(&install_driver_script(&dir, &body_path, &install_token)); - if let ArchiveSource::ControllerPush { reason } = &archive_source { - log::info!("OpenBitFun CLI dispatch install is pushing the archive over SFTP: {reason}"); - let archive = download_verified_archive(&release).await?; - manager - .sftp_write(connection_id, &archive_path, &archive) - .await - .context("stage verified OpenBitFun CLI archive")?; - } - stage_and_launch_installer( + .context("stage merged target app.json")?; + exec_ok( manager, connection_id, - &dir, - &archive_path, - &body_path, - &script_path, - &body, - &driver, - &install_token, + &format!( + "chmod 600 {staged} && mv -f {staged} {config}", + staged = shell_quote_posix(&staging_path), + config = shell_quote_posix(&config_path), + ), ) - .await?; - - Ok(DispatchInstallStart { - script_path, - version: release.public.version, - target: release.public.target, - url: release.public.url, - sha256: release.public.sha256, - }) -} - -/// How the verified archive reached the target. -#[derive(Debug, Clone, PartialEq, Eq)] -enum ArchiveSource { - /// The target fetched the release itself and checked it against a digest - /// this machine proved with the publisher's signature. - TargetDownload, - /// This machine downloaded, fully verified, and pushed the bytes over SFTP. - /// Carries why the target could not fetch it, for the install log. - ControllerPush { reason: String }, + .await } -/// Why this target cannot safely fetch the release itself, if it cannot. -/// -/// The signature rule is the load-bearing one. A target has no minisign and no -/// trust root, so it can only check a plain SHA256. That is sound when the -/// digest is provably the publisher's, which is exactly what a verified -/// `.sha256.sig` gives us. When that signature is absent the digest is -/// unauthenticated, and the archive's own signature — checkable only here — -/// becomes the sole protection, so the bytes must flow through this machine. -fn target_download_blocker(target: &RemoteTarget, release: &ResolvedRelease) -> Option { - if !release.checksum_signature_verified { - return Some("release checksum sidecar is unsigned".to_string()); +fn validate_model_config_payload( + ai_model_config: &Value, +) -> Result<&serde_json::Map> { + let payload = ai_model_config + .as_object() + .ok_or_else(|| anyhow!("model configuration payload must be a JSON object"))?; + if let Some(unexpected) = payload + .keys() + .find(|key| !MODEL_CONFIG_KEYS.contains(&key.as_str())) + { + return Err(anyhow!( + "model configuration payload has unexpected key '{unexpected}'" + )); } - if target.downloader.is_none() { - return Some("target has neither curl nor wget".to_string()); + if payload + .get("models") + .and_then(Value::as_array) + .is_none_or(|models| models.is_empty()) + { + return Err(anyhow!( + "the controller has no configured AI models to sync" + )); } - if target.digest_tool.is_none() { - return Some("target cannot verify a SHA256 digest".to_string()); + Ok(payload) +} + +/// Graft the model-configuration keys onto an existing target config document, +/// leaving every other setting untouched. +fn merge_model_config( + existing: Option<&str>, + payload: &serde_json::Map, +) -> Result { + let mut root = match existing.map(str::trim).filter(|text| !text.is_empty()) { + Some(text) => serde_json::from_str::(text) + .context("target app.json exists but is not valid JSON; refusing to overwrite it")?, + None => Value::Object(serde_json::Map::new()), + }; + let root_map = root + .as_object_mut() + .ok_or_else(|| anyhow!("target app.json is not a JSON object; refusing to overwrite it"))?; + let ai = root_map + .entry("ai") + .or_insert_with(|| Value::Object(serde_json::Map::new())); + let ai_map = ai.as_object_mut().ok_or_else(|| { + anyhow!("target app.json has a non-object `ai` section; refusing to overwrite it") + })?; + for (key, value) in payload { + ai_map.insert(key.clone(), value.clone()); } - None + serde_json::to_string_pretty(&root).context("encode merged target app.json") } -/// Have the target fetch and digest-check the release into `archive_path`. -/// -/// Synchronous on purpose: it replaces the SFTP upload, which was synchronous -/// too, so a dropped session is no worse than before and the detached installer -/// below still only ever sees a fully verified archive already on disk. -async fn download_archive_on_target( +/// Where the target CLI reads its global config from, mirroring the +/// `dirs::config_dir()` resolution inside the CLI itself. +fn locate_target_config_script() -> &'static str { + r#" +LC_ALL=C +case "$(uname -s 2>/dev/null)" in + Darwin) CONFIG_DIR="$HOME/Library/Application Support/openbitfun/config" ;; + Linux) CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/openbitfun/config" ;; + *) printf 'os=unsupported\n'; exit 0 ;; +esac +printf 'os=supported\n' +printf 'dir=%s\n' "$CONFIG_DIR" +if [ -f "$CONFIG_DIR/app.json" ]; then printf 'config=1\n'; else printf 'config=0\n'; fi +"# +} + +async fn exec_lines( manager: &SSHConnectionManager, connection_id: &str, - target: &RemoteTarget, - release: &ResolvedRelease, - archive_path: &str, -) -> Result<()> { - let downloader = target - .downloader - .context("target download requires curl or wget")?; - let digest_tool = target - .digest_tool - .context("target download requires a SHA256 checker")?; - let github_url = release - .sources - .iter() - .find(|source| source.origin == ReleaseOrigin::GitHub) - .map(|source| source.url.as_str()) - .context("release has no GitHub source")?; - let mirror_url = release - .sources - .iter() - .find(|source| source.origin == ReleaseOrigin::OpenBitFun) - .map(|source| source.url.as_str()) - .unwrap_or(""); - let script = target_download_script( - downloader, - digest_tool, - archive_path, - github_url, - mirror_url, - &release.public.sha256, - ); + script: &str, +) -> Result { let result = manager .execute_command_with_options( connection_id, - &script, + script, SSHCommandOptions { - timeout_ms: Some(TARGET_DOWNLOAD_TIMEOUT_MS), + timeout_ms: Some(COMMAND_TIMEOUT_MS), cancellation_token: None, }, ) .await?; - ensure_command_completed(&result, "download OpenBitFun CLI release on the target")?; + ensure_command_completed(&result, "inspect SSH dispatch target")?; if result.exit_code != 0 { return Err(remote_command_error( - "download OpenBitFun CLI release on the target", + "inspect SSH dispatch target", result.exit_code, &result.stdout, &result.stderr, )); } - Ok(()) + Ok(result.stdout) } -fn target_download_script( - downloader: RemoteDownloader, - digest_tool: RemoteDigestTool, - archive_path: &str, - github_url: &str, - mirror_url: &str, - sha256: &str, -) -> String { - // Download to a scratch name and only publish it once the digest matches, - // so a truncated or tampered body can never be handed to the installer. - let fetch = match downloader { - RemoteDownloader::Curl => format!( - "curl -fsSL --retry 3 --retry-delay 1 --max-time {timeout} --max-filesize {max} -o \"$PART\" \"$URL\"", - timeout = TARGET_DOWNLOAD_TIMEOUT_MS / 1000, - max = MAX_ARCHIVE_BYTES, - ), - // wget has no --max-filesize; the size ceiling is enforced below. - RemoteDownloader::Wget => format!( - "wget -q --tries=3 --timeout={timeout} -O \"$PART\" \"$URL\"", - timeout = TARGET_DOWNLOAD_TIMEOUT_MS / 1000, - ), - }; - let probe = match downloader { - RemoteDownloader::Curl => format!( - r#"METRICS=$(curl -LsS --range 0-{probe_end} --connect-timeout 5 --max-time {window} -o /dev/null -w '%{{http_code}} %{{size_download}} %{{time_total}}' "$GITHUB_URL" 2>/dev/null || true) -GITHUB_SPEED=$(printf '%s\n' "$METRICS" | awk '($1 == 200 || $1 == 206) && $3 > 0 {{ printf "%.0f\n", $2 / $3; ok=1 }} END {{ if (!ok) print 0 }}')"#, - probe_end = RELEASE_PROBE_BYTES - 1, - window = RELEASE_PROBE_WINDOW.as_secs(), - ), - RemoteDownloader::Wget => format!( - r#"GITHUB_SPEED=0 -PROBE="$ARCHIVE.probe" -if command -v timeout >/dev/null 2>&1; then - rm -f "$PROBE" - START=$(date +%s) - timeout {window} wget -q --tries=1 --timeout={window} --header='Range: bytes=0-{probe_end}' -O "$PROBE" "$GITHUB_URL" || true - END=$(date +%s) - ELAPSED=$((END - START)) - [ "$ELAPSED" -gt 0 ] || ELAPSED=1 - if [ -f "$PROBE" ]; then - BYTES=$(wc -c <"$PROBE" | tr -d '[:space:]') - else - BYTES=0 - fi - GITHUB_SPEED=$((BYTES / ELAPSED)) - rm -f "$PROBE" -fi"#, - probe_end = RELEASE_PROBE_BYTES - 1, - window = RELEASE_PROBE_WINDOW.as_secs(), - ), - }; - let verify = match digest_tool { - RemoteDigestTool::Sha256Sum => "sha256sum -c -", - RemoteDigestTool::Shasum => "shasum -a 256 -c -", - }; - format!( - r#"set -eu -umask 077 -ARCHIVE={archive} -PART="$ARCHIVE.part" -GITHUB_URL={github_url} -MIRROR_URL={mirror_url} -EXPECTED={sha} -MAX={max} -rm -f "$PART" -cleanup() {{ rm -f "$PART"; }} -trap cleanup EXIT -{probe} -case "$GITHUB_SPEED" in ''|*[!0-9]*) GITHUB_SPEED=0 ;; esac -FIRST_URL="$GITHUB_URL" -SECOND_URL="$MIRROR_URL" -if [ -n "$MIRROR_URL" ] && [ "$GITHUB_SPEED" -lt {healthy_bps} ]; then - echo "GitHub CLI probe: $((GITHUB_SPEED / 1024)) KiB/s; trying OpenBitFun mirror first." - FIRST_URL="$MIRROR_URL" - SECOND_URL="$GITHUB_URL" -else - echo "GitHub CLI probe: $((GITHUB_SPEED / 1024)) KiB/s; keeping GitHub first." -fi -INSTALLED=0 -for URL in "$FIRST_URL" "$SECOND_URL"; do - [ -n "$URL" ] || continue - rm -f "$PART" - echo "Downloading OpenBitFun CLI from $URL" - if {fetch}; then - SIZE=$(wc -c <"$PART" | tr -d '[:space:]') - if [ "$SIZE" -le "$MAX" ] && printf '%s %s\n' "$EXPECTED" "$PART" | {verify}; then - mv -f "$PART" "$ARCHIVE" - INSTALLED=1 - break - fi - fi - echo "Download source failed verification; trying the next source." >&2 -done -[ "$INSTALLED" = "1" ] || {{ echo "ERROR: every OpenBitFun CLI source failed" >&2; exit 1; }} -chmod 600 "$ARCHIVE" -trap - EXIT -"#, - archive = shell_quote_posix(archive_path), - github_url = shell_quote_posix(github_url), - mirror_url = shell_quote_posix(mirror_url), - sha = shell_quote_posix(sha256), - max = MAX_ARCHIVE_BYTES, - healthy_bps = GITHUB_HEALTHY_THROUGHPUT, - ) +pub async fn submit( + manager: &SSHConnectionManager, + connection_id: &str, + request: &Value, +) -> Result { + invoke_json(manager, connection_id, "submit", request).await } -/// Stage the installer scripts and launch the detached body. -/// -/// Kept separate from `install_cli_start` so the token handshake, log -/// truncation, and channel-leak-free launch stay in one place. -#[allow(clippy::too_many_arguments)] -async fn stage_and_launch_installer( - manager: &SSHConnectionManager, - connection_id: &str, - dir: &str, - archive_path: &str, - body_path: &str, - script_path: &str, - body: &str, - driver: &str, - install_token: &str, -) -> Result<()> { - manager - .sftp_write(connection_id, body_path, body.as_bytes()) - .await - .context("stage OpenBitFun CLI install body")?; - manager - .sftp_write(connection_id, script_path, driver.as_bytes()) - .await - .context("stage OpenBitFun CLI install driver")?; - - exec_ok( - manager, - connection_id, - &stage_install_command( - archive_path, - body_path, - script_path, - &format!("{dir}/{INSTALL_STEM}.log"), - &format!("{dir}/{INSTALL_STEM}.pid"), - &format!("{dir}/{INSTALL_STEM}.driver.pid"), - &format!("{dir}/{INSTALL_STEM}.preparing"), - &format!("{dir}/{INSTALL_STEM}.exit"), - install_token, - ), - ) - .await?; - - // The short-lived driver only starts a nohup body and exits, and it must run - // without a PTY. sshd tears a PTY down as soon as the driver exits — about a - // millisecond after the hand-off — and that teardown races the body it just - // spawned. A body still inside bash's startup has not reached its own exit - // trap yet, so losing that race kills it silently: no log, no exit file, and - // a `.pid` the next poll then reaps as stale. The controller sees an empty - // state and reports the install as failed even though nothing went wrong. - // A plain exec channel has no controlling terminal, so the hand-off cannot be - // interrupted; the installer needs no TTY semantics either, since it never - // uses sudo. Draining the channel in the background prevents a server-side - // channel leak while keeping the installer independent of the caller process. - let channel = match manager - .open_exec_channel( - connection_id, - &format!( - "bash {} {}", - shell_quote_posix(script_path), - shell_quote_posix(install_token) - ), - ) - .await - { - Ok(channel) => channel, - Err(error) => { - let _ = install_cli_cancel(manager, connection_id).await; - return Err(error).context("start remote OpenBitFun CLI installer"); - } - }; - tokio::spawn(async move { - let mut channel = channel; - while channel.wait().await.is_some() {} - }); - Ok(()) -} - -fn ensure_confirmed_release( - resolved: &DispatchCliRelease, - expected: &DispatchCliRelease, -) -> Result<()> { - if resolved != expected { - return Err(anyhow!( - "OpenBitFun CLI release metadata changed after confirmation; probe the target and confirm the new asset" - )); - } - Ok(()) -} - -pub async fn install_cli_poll( - manager: &SSHConnectionManager, - connection_id: &str, - cursor: u64, -) -> Result { - ensure_plain_ssh_target(manager, connection_id).await?; - let script = install_poll_script(cursor); - let result = manager - .execute_command_with_options( - connection_id, - &script, - SSHCommandOptions { - timeout_ms: Some(COMMAND_TIMEOUT_MS), - cancellation_token: None, - }, - ) - .await?; - ensure_command_completed(&result, "poll CLI install")?; - if result.exit_code != 0 { - return Err(remote_command_error( - "poll CLI install", - result.exit_code, - &result.stdout, - &result.stderr, - )); - } - let (head, output) = split_metadata_output(&result.stdout); - let value = |key: &str| { - head.lines() - .find_map(|line| { - line.strip_prefix(key) - .and_then(|rest| rest.strip_prefix('=')) - }) - .unwrap_or("") - .trim() - }; - let running = value("running") == "1"; - let preparing = value("preparing") == "1"; - let marker = value("marker") == "1"; - let exit_recorded = value("exit_recorded") == "1"; - let exit_code = value("exit_code").parse::().ok(); - let size = value("size").parse::().unwrap_or(cursor); - let status = if marker { - DispatchInstallStatus::Succeeded - } else if running || preparing { - DispatchInstallStatus::Running - } else if exit_recorded || size > 0 { - DispatchInstallStatus::Failed - } else { - // start seeds the prepare flag before launching the driver, so an empty - // state after an explicit start means the driver never became live. - DispatchInstallStatus::Failed - }; - let mut output = output.to_string(); - if status == DispatchInstallStatus::Failed && exit_code == Some(130) && output.is_empty() { - output.push_str("OpenBitFun CLI installation was cancelled.\n"); - } - Ok(DispatchInstallPoll { - cursor: size, - output, - status, - }) -} - -/// Best-effort process-tree cancellation for an in-flight CLI install. -pub async fn install_cli_cancel(manager: &SSHConnectionManager, connection_id: &str) -> Result<()> { - ensure_plain_ssh_target(manager, connection_id).await?; - let script = install_cancel_script(); - let result = manager - .execute_command_with_options( - connection_id, - &script, - SSHCommandOptions { - timeout_ms: Some(COMMAND_TIMEOUT_MS), - cancellation_token: None, - }, - ) - .await?; - ensure_command_completed(&result, "cancel CLI install")?; - if result.exit_code != 0 { - return Err(remote_command_error( - "cancel CLI install", - result.exit_code, - &result.stdout, - &result.stderr, - )); - } - Ok(()) -} - -/// Read the SSH target's stable, non-secret device identity after verifying -/// that its CLI advertises the account-daemon bootstrap contract. -pub async fn account_daemon_identity( - manager: &SSHConnectionManager, - connection_id: &str, -) -> Result { - let cli_path = account_daemon_cli_path(manager, connection_id).await?; - let command = format!( - "{} daemon __dispatch_identity", - shell_quote_posix(&cli_path) - ); - let result = manager - .execute_command_with_options( - connection_id, - &command, - SSHCommandOptions { - timeout_ms: Some(COMMAND_TIMEOUT_MS), - cancellation_token: None, - }, - ) - .await?; - ensure_command_completed(&result, "read OpenBitFun daemon target identity")?; - if result.exit_code != 0 { - return Err(remote_command_error( - "read OpenBitFun daemon target identity", - result.exit_code, - &result.stdout, - &result.stderr, - )); - } - let identity: DispatchAccountDaemonIdentity = serde_json::from_str(result.stdout.trim()) - .context("OpenBitFun daemon target returned an invalid identity")?; - if identity.device_id.len() != 32 - || !identity - .device_id - .bytes() - .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) - || identity.device_name.trim().is_empty() - || identity.device_name.len() > 256 - || identity.device_name.chars().any(char::is_control) - { - return Err(anyhow!( - "OpenBitFun daemon target returned an unsafe identity" - )); - } - Ok(identity) -} - -/// Stage one secret-bearing account bootstrap document, consume it through the -/// target CLI, and remove it regardless of command outcome. -pub async fn provision_account_daemon( - manager: &SSHConnectionManager, - connection_id: &str, - request: &DispatchAccountDaemonProvisionRequest, -) -> Result { - let cli_path = account_daemon_cli_path(manager, connection_id).await?; - let target = probe_remote_target(manager, connection_id).await?; - let request_dir = product_data_path(&target.home, &["dispatch", "requests"]); - exec_ok( - manager, - connection_id, - &format!( - "mkdir -p {dir} && chmod 700 {root} {dispatch} {dir}", - root = shell_quote_posix(&product_data_path(&target.home, &[])), - dispatch = shell_quote_posix(&product_data_path(&target.home, &["dispatch"])), - dir = shell_quote_posix(&request_dir), - ), - ) - .await?; - let request_path = format!( - "{request_dir}/daemon-provision-{}.json", - uuid::Uuid::new_v4().as_simple() - ); - let request_bytes = - serde_json::to_vec(request).context("encode daemon provisioning request")?; - exec_ok( - manager, - connection_id, - &format!( - "umask 077; : > {request}; chmod 600 {request}", - request = shell_quote_posix(&request_path), - ), - ) - .await?; - if let Err(error) = manager - .sftp_write(connection_id, &request_path, &request_bytes) - .await - .context("stage daemon provisioning request") - { - let _ = manager.sftp_remove(connection_id, &request_path).await; - return Err(error); - } - - let command = format!( - "request={request}; cleanup() {{ rm -f \"$request\"; }}; trap cleanup EXIT; \ - trap 'exit 130' HUP INT TERM; {cli} daemon __dispatch_provision \"$request\"", - request = shell_quote_posix(&request_path), - cli = shell_quote_posix(&cli_path), - ); - let result = manager - .execute_command_with_options( - connection_id, - &command, - SSHCommandOptions { - timeout_ms: Some(ACCOUNT_DAEMON_COMMAND_TIMEOUT_MS), - cancellation_token: None, - }, - ) - .await; - let _ = manager.sftp_remove(connection_id, &request_path).await; - let result = result?; - ensure_command_completed(&result, "provision persistent OpenBitFun daemon")?; - if result.exit_code != 0 { - return Err(remote_command_error( - "provision persistent OpenBitFun daemon", - result.exit_code, - &result.stdout, - &result.stderr, - )); - } - let response: DispatchAccountDaemonProvisionResponse = - serde_json::from_str(result.stdout.trim()) - .context("OpenBitFun daemon provisioning returned invalid JSON")?; - if response.device_id != request.device_id || !response.service_installed { - return Err(anyhow!( - "OpenBitFun daemon provisioning returned an inconsistent result" - )); - } - Ok(response) -} - -/// Best-effort rollback for a bootstrap whose relay-online verification did -/// not complete. The target command refuses to touch a different session. -pub async fn deprovision_account_daemon( - manager: &SSHConnectionManager, - connection_id: &str, - device_id: &str, - user_id: &str, -) -> Result<()> { - let cli_path = account_daemon_cli_path(manager, connection_id).await?; - let command = format!( - "{} daemon __dispatch_deprovision {} {}", - shell_quote_posix(&cli_path), - shell_quote_posix(device_id), - shell_quote_posix(user_id), - ); - let result = manager - .execute_command_with_options( - connection_id, - &command, - SSHCommandOptions { - timeout_ms: Some(ACCOUNT_DAEMON_COMMAND_TIMEOUT_MS), - cancellation_token: None, - }, - ) - .await?; - ensure_command_completed(&result, "roll back OpenBitFun daemon provisioning")?; - if result.exit_code != 0 { - return Err(remote_command_error( - "roll back OpenBitFun daemon provisioning", - result.exit_code, - &result.stdout, - &result.stderr, - )); - } - Ok(()) -} - -async fn account_daemon_cli_path( - manager: &SSHConnectionManager, - connection_id: &str, -) -> Result { - ensure_plain_ssh_target(manager, connection_id).await?; - let probed = probe(manager, connection_id, None).await?; - let protocol = probed - .protocol - .as_ref() - .ok_or_else(|| anyhow!("the SSH target has no compatible OpenBitFun dispatch protocol"))?; - validate_dispatch_protocol(protocol, None)?; - let supports_provisioning = protocol - .get("capabilities") - .and_then(Value::as_array) - .is_some_and(|capabilities| { - capabilities.iter().any(|capability| { - capability.as_str() == Some(DISPATCH_ACCOUNT_DAEMON_PROVISIONING_CAPABILITY) - }) - }); - if !supports_provisioning { - return Err(anyhow!( - "the target OpenBitFun CLI does not support account daemon provisioning" - )); - } - probed - .cli_path - .ok_or_else(|| anyhow!("the SSH target has no OpenBitFun CLI")) -} - -/// Keys of the `ai` config section that make up "model configuration": the -/// model catalog (credentials included) plus every default-selection table the -/// target consults when resolving a ready model. -const MODEL_CONFIG_KEYS: [&str; 5] = [ - "models", - "default_models", - "agent_model_defaults", - "agent_model_selections", - "model_pools", -]; - -/// Write the controller's model configuration into the target's global config -/// so `openbitfun dispatch probe` can report a ready model. -/// -/// `ai_model_config` is the snake_case `ai` slice restricted to -/// [`MODEL_CONFIG_KEYS`], exactly as `app.json` stores it. Everything else in -/// an existing target `app.json` is preserved; a target file that exists but -/// cannot be read or parsed aborts the sync instead of being overwritten. The -/// write is atomic (temp file + rename) and owner-only, because model entries -/// carry API credentials. -pub async fn sync_model_config( - manager: &SSHConnectionManager, - connection_id: &str, - ai_model_config: &Value, -) -> Result<()> { - let payload = validate_model_config_payload(ai_model_config)?; - ensure_plain_ssh_target(manager, connection_id).await?; - - let locate = exec_lines(manager, connection_id, locate_target_config_script()).await?; - let get = |key: &str| { - locate - .lines() - .find_map(|line| { - line.strip_prefix(key) - .and_then(|rest| rest.strip_prefix('=')) - }) - .unwrap_or("") - .trim() - .to_string() - }; - if get("os") == "unsupported" { - return Err(anyhow!( - "model configuration sync supports only Linux and macOS SSH targets" - )); - } - let config_dir = get("dir"); - if config_dir.is_empty() { - return Err(anyhow!( - "could not resolve the target OpenBitFun config directory" - )); - } - let config_path = format!("{config_dir}/app.json"); - - let existing = if get("config") == "1" { - let bytes = manager - .sftp_read(connection_id, &config_path) - .await - .context("read existing target app.json; refusing to overwrite it blindly")?; - Some(String::from_utf8(bytes).context("target app.json is not UTF-8")?) - } else { - None - }; - let merged = merge_model_config(existing.as_deref(), payload)?; - - exec_ok( - manager, - connection_id, - &format!( - "mkdir -p {dir} && chmod 700 \"$(dirname {dir})\" {dir}", - dir = shell_quote_posix(&config_dir), - ), - ) - .await?; - let data_namespace = openbitfun_services_core::product_identity::data_namespace(); - let staging_path = format!("{config_path}.{data_namespace}-sync.tmp"); - manager - .sftp_write(connection_id, &staging_path, merged.as_bytes()) - .await - .context("stage merged target app.json")?; - exec_ok( - manager, - connection_id, - &format!( - "chmod 600 {staged} && mv -f {staged} {config}", - staged = shell_quote_posix(&staging_path), - config = shell_quote_posix(&config_path), - ), - ) - .await -} - -fn validate_model_config_payload( - ai_model_config: &Value, -) -> Result<&serde_json::Map> { - let payload = ai_model_config - .as_object() - .ok_or_else(|| anyhow!("model configuration payload must be a JSON object"))?; - if let Some(unexpected) = payload - .keys() - .find(|key| !MODEL_CONFIG_KEYS.contains(&key.as_str())) - { - return Err(anyhow!( - "model configuration payload has unexpected key '{unexpected}'" - )); - } - if payload - .get("models") - .and_then(Value::as_array) - .is_none_or(|models| models.is_empty()) - { - return Err(anyhow!( - "the controller has no configured AI models to sync" - )); - } - Ok(payload) -} - -/// Graft the model-configuration keys onto an existing target config document, -/// leaving every other setting untouched. -fn merge_model_config( - existing: Option<&str>, - payload: &serde_json::Map, -) -> Result { - let mut root = match existing.map(str::trim).filter(|text| !text.is_empty()) { - Some(text) => serde_json::from_str::(text) - .context("target app.json exists but is not valid JSON; refusing to overwrite it")?, - None => Value::Object(serde_json::Map::new()), - }; - let root_map = root - .as_object_mut() - .ok_or_else(|| anyhow!("target app.json is not a JSON object; refusing to overwrite it"))?; - let ai = root_map - .entry("ai") - .or_insert_with(|| Value::Object(serde_json::Map::new())); - let ai_map = ai.as_object_mut().ok_or_else(|| { - anyhow!("target app.json has a non-object `ai` section; refusing to overwrite it") - })?; - for (key, value) in payload { - ai_map.insert(key.clone(), value.clone()); - } - serde_json::to_string_pretty(&root).context("encode merged target app.json") -} - -/// Where the target CLI reads its global config from, mirroring the -/// `dirs::config_dir()` resolution inside the CLI itself. -fn locate_target_config_script() -> &'static str { - r#" -LC_ALL=C -case "$(uname -s 2>/dev/null)" in - Darwin) CONFIG_DIR="$HOME/Library/Application Support/openbitfun/config" ;; - Linux) CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/openbitfun/config" ;; - *) printf 'os=unsupported\n'; exit 0 ;; -esac -printf 'os=supported\n' -printf 'dir=%s\n' "$CONFIG_DIR" -if [ -f "$CONFIG_DIR/app.json" ]; then printf 'config=1\n'; else printf 'config=0\n'; fi -"# -} - -async fn exec_lines( - manager: &SSHConnectionManager, - connection_id: &str, - script: &str, -) -> Result { - let result = manager - .execute_command_with_options( - connection_id, - script, - SSHCommandOptions { - timeout_ms: Some(COMMAND_TIMEOUT_MS), - cancellation_token: None, - }, - ) - .await?; - ensure_command_completed(&result, "inspect SSH dispatch target")?; - if result.exit_code != 0 { - return Err(remote_command_error( - "inspect SSH dispatch target", - result.exit_code, - &result.stdout, - &result.stderr, - )); - } - Ok(result.stdout) -} - -pub async fn submit( - manager: &SSHConnectionManager, - connection_id: &str, - request: &Value, -) -> Result { - invoke_json(manager, connection_id, "submit", request).await -} - -pub async fn status( +pub async fn status( manager: &SSHConnectionManager, connection_id: &str, request: &Value, @@ -1837,180 +864,6 @@ pub async fn upload_bundle( } } -/// Make sure the target runs a CLI this controller can dispatch to. -/// -/// Installing is automatic because a dispatch is useless without it and the -/// user already authorized this SSH connection. What the confirmation dialog -/// used to guarantee is preserved by other means: the archive is still verified -/// against a signed SHA-256 and a mandatory minisign signature before it is -/// staged, and every step is reported through `progress` so the install is -/// visible in the dispatch session rather than silent. -/// -/// Source builds are deliberately not automatic. They upload the user's own -/// repository and compile it on the target, which is a different kind of act -/// from fetching a signed release. -pub async fn ensure_target_cli( - manager: &SSHConnectionManager, - connection_id: &str, - mut progress: Progress, -) -> Result -where - Progress: FnMut(&str, Value) -> ProgressFuture, - ProgressFuture: Future>, -{ - let probed = probe(manager, connection_id, None).await?; - if let Some(protocol) = probed.protocol.as_ref() { - if validate_dispatch_protocol(protocol, None).is_ok() { - return Ok(probed); - } - } - if !probed.install_supported { - return Err(anyhow!( - "{}", - probed - .install_error - .as_deref() - .or(probed.protocol_error.as_deref()) - .unwrap_or("this SSH target cannot run the OpenBitFun CLI") - )); - } - if let Some(reason) = probed.prebuilt_incompatible.as_deref() { - return Err(anyhow!( - "no published OpenBitFun CLI can run on this target ({reason}); install OpenBitFun there manually and retry" - )); - } - let release = probed.release.clone().ok_or_else(|| { - anyhow!("could not resolve an OpenBitFun CLI release for this target's platform") - })?; - - progress( - "cli-install-started", - serde_json::json!({ - "version": release.version, - "target": release.target, - "url": release.url, - "sha256": release.sha256, - "reason": probed - .protocol_error - .clone() - .unwrap_or_else(|| "the target has no compatible OpenBitFun CLI".to_string()), - }), - ) - .await - .context("persist the CLI install started audit event")?; - if let Err(error) = install_cli_start(manager, connection_id, &release).await { - emit_cli_install_failure(&mut progress, "install-start", &error).await?; - return Err(error); - } - - let deadline = tokio::time::Instant::now() + CLI_INSTALL_WAIT; - let mut cursor = 0_u64; - loop { - let poll = match install_cli_poll(manager, connection_id, cursor).await { - Ok(poll) => poll, - Err(error) => { - emit_cli_install_failure(&mut progress, "install-poll", &error).await?; - return Err(error); - } - }; - cursor = poll.cursor; - match poll.status { - DispatchInstallStatus::Succeeded => break, - DispatchInstallStatus::Failed => { - let error = anyhow!( - "OpenBitFun CLI installation failed on the SSH target: {}", - bounded_detail(&poll.output) - ); - emit_cli_install_failure(&mut progress, "install-status", &error).await?; - return Err(error); - } - _ => {} - } - if tokio::time::Instant::now() >= deadline { - let _ = install_cli_cancel(manager, connection_id).await; - let error = anyhow!( - "OpenBitFun CLI installation did not finish within {} minutes", - CLI_INSTALL_WAIT.as_secs() / 60 - ); - emit_cli_install_failure(&mut progress, "install-timeout", &error).await?; - return Err(error); - } - tokio::time::sleep(CLI_INSTALL_POLL_INTERVAL).await; - } - - let reprobed = match probe(manager, connection_id, None).await { - Ok(probed) => probed, - Err(error) => { - emit_cli_install_failure(&mut progress, "reprobe", &error).await?; - return Err(error); - } - }; - let protocol = match reprobed.protocol.as_ref() { - Some(protocol) => protocol, - None => { - let error = anyhow!( - "{}", - reprobed.protocol_error.as_deref().unwrap_or( - "the installed OpenBitFun CLI still does not answer the dispatch protocol" - ) - ); - emit_cli_install_failure(&mut progress, "protocol-validation", &error).await?; - return Err(error); - } - }; - // Fail closed: an install that "succeeded" but left an incompatible binary - // must not be treated as a usable target. - if let Err(error) = validate_dispatch_protocol(protocol, None) { - emit_cli_install_failure(&mut progress, "protocol-validation", &error).await?; - return Err(error); - } - progress( - "cli-install-succeeded", - serde_json::json!({ - "version": release.version, - "cliPath": reprobed.cli_path, - }), - ) - .await - .context("persist the CLI install succeeded audit event")?; - Ok(reprobed) -} - -async fn emit_cli_install_failure( - progress: &mut Progress, - phase: &str, - error: &anyhow::Error, -) -> Result<()> -where - Progress: FnMut(&str, Value) -> ProgressFuture, - ProgressFuture: Future>, -{ - progress( - "cli-install-failed", - cli_install_failure_details(phase, &error.to_string()), - ) - .await - .map_err(|audit_error| { - anyhow!( - "persist the CLI install failed audit event for phase '{}': {}; original failure: {}", - bounded_detail(phase), - bounded_detail(&audit_error.to_string()), - bounded_detail(&error.to_string()) - ) - }) -} - -fn cli_install_failure_details(phase: &str, error: &str) -> Value { - let error = bounded_detail(error); - serde_json::json!({ - "phase": bounded_detail(phase), - "error": error, - // Keep the existing audit/UI projection useful while `phase` and - // `error` provide the structured durable form. - "output": error, - }) -} - async fn invoke_json( manager: &SSHConnectionManager, connection_id: &str, @@ -2206,23 +1059,6 @@ async fn probe_remote_target( arch: get("arch"), home, cli_path: (!cli_path.is_empty()).then_some(cli_path), - tar_available: get("tar") == "1", - downloader: match get("downloader").as_str() { - "curl" => Some(RemoteDownloader::Curl), - "wget" => Some(RemoteDownloader::Wget), - _ => None, - }, - digest_tool: match get("digest").as_str() { - "sha256sum" => Some(RemoteDigestTool::Sha256Sum), - "shasum" => Some(RemoteDigestTool::Shasum), - _ => None, - }, - libc: match get("libc").as_str() { - "glibc" => Some(RemoteLibc::Glibc), - "musl" => Some(RemoteLibc::Musl), - _ => None, - }, - libc_version: (!get("libcversion").is_empty()).then(|| get("libcversion")), }) } @@ -2232,860 +1068,13 @@ LC_ALL=C printf 'os=%s\n' "$(uname -s 2>/dev/null || true)" printf 'arch=%s\n' "$(uname -m 2>/dev/null || true)" printf 'home=%s\n' "$HOME" -if command -v tar >/dev/null 2>&1; then printf 'tar=1\n'; else printf 'tar=0\n'; fi -if command -v curl >/dev/null 2>&1; then printf 'downloader=curl\n' -elif command -v wget >/dev/null 2>&1; then printf 'downloader=wget\n' -else printf 'downloader=\n'; fi -if command -v sha256sum >/dev/null 2>&1; then printf 'digest=sha256sum\n' -elif command -v shasum >/dev/null 2>&1; then printf 'digest=shasum\n' -else printf 'digest=\n'; fi if [ -x "$HOME/.local/bin/openbitfun" ]; then OPENBITFUN_BIN="$HOME/.local/bin/openbitfun" else OPENBITFUN_BIN="$(command -v openbitfun 2>/dev/null || true)" fi printf 'cli=%s\n' "$OPENBITFUN_BIN" -if [ "$(uname -s 2>/dev/null || true)" = "Linux" ]; then - if ls /lib/ld-musl-* >/dev/null 2>&1 || ldd --version 2>&1 | head -n1 | grep -qi musl; then - printf 'libc=musl\n' - else - printf 'libc=glibc\n' - printf 'libcversion=%s\n' "$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $NF}' || true)" - fi -fi -"# -} - -async fn resolve_release(os: &str, arch: &str) -> Result { - let pubkey = require_release_pubkey()?; - let target = release_target(os, arch)?; - let client = release_http_client()?; - let version = fetch_latest_release_version(&client).await?; - let filename = format!("openbitfun-cli-{version}-{target}.tar.gz"); - let sources = release_sources(&version, &filename); - let (sha256, checksum_signature_verified) = - resolve_release_digest(&client, &sources, pubkey, &filename).await?; - let canonical_url = sources - .iter() - .find(|source| source.origin == ReleaseOrigin::GitHub) - .map(|source| source.url.clone()) - .context("release has no canonical GitHub source")?; - - Ok(ResolvedRelease { - public: DispatchCliRelease { - version, - target: target.to_string(), - url: canonical_url, - sha256, - }, - filename, - sources, - checksum_signature_verified, - }) -} - -fn release_sources(version: &str, filename: &str) -> Vec { - let tag = release_tag_for_version(version); - [ - ( - ReleaseOrigin::GitHub, - format!("{GITHUB_RELEASE_BASE}/download/{tag}"), - ), - ( - ReleaseOrigin::OpenBitFun, - format!("{OPENBITFUN_RELEASE_BASE}/{version}"), - ), - ] - .into_iter() - .map(|(origin, base)| { - let url = format!("{base}/{filename}"); - ReleaseArtifactSource { - origin, - checksum_url: format!("{url}.sha256"), - checksum_signature_url: format!("{url}.sha256.sig"), - archive_signature_url: format!("{url}.sig"), - url, - } - }) - .collect() -} - -async fn fetch_latest_release_version(client: &reqwest::Client) -> Result { - let mut failures = Vec::new(); - for manifest_url in [GITHUB_LATEST_MANIFEST, OPENBITFUN_LATEST_MANIFEST] { - let text = match fetch_required_text(client, manifest_url).await { - Ok(text) => text, - Err(error) => { - failures.push(format!("{manifest_url}: {error:#}")); - continue; - } - }; - match latest_release_version_from_json(&text, manifest_url) { - Ok(version) => return Ok(version), - Err(error) => failures.push(format!("{manifest_url}: {error:#}")), - } - } - Err(anyhow!( - "could not resolve the latest OpenBitFun release: {}", - failures.join("; ") - )) -} - -fn latest_release_version_from_json(text: &str, source: &str) -> Result { - let manifest: LatestReleaseManifest = - serde_json::from_str(text).with_context(|| format!("parse {source}"))?; - let version = manifest.version.trim(); - let parsed = semver::Version::parse(version) - .with_context(|| format!("invalid release version {version}"))?; - if !parsed.pre.is_empty() || !parsed.build.is_empty() { - return Err(anyhow!( - "latest release {version} is not a stable asset version" - )); - } - Ok(version.to_string()) -} - -async fn resolve_release_digest( - client: &reqwest::Client, - sources: &[ReleaseArtifactSource], - pubkey: &str, - filename: &str, -) -> Result<(String, bool)> { - let mut unsigned_digest = None; - let mut failures = Vec::new(); - for source in sources { - let checksum = match fetch_required_text(client, &source.checksum_url).await { - Ok(checksum) => checksum, - Err(error) => { - failures.push(format!("{}: {error:#}", source.checksum_url)); - continue; - } - }; - match fetch_optional_text(client, &source.checksum_signature_url).await { - Ok(Some(signature)) => { - match verify_signed_checksum(&checksum, &signature, pubkey, filename) { - Ok(digest) => return Ok((digest, true)), - Err(error) => { - failures.push(format!("{}: {error:#}", source.checksum_signature_url)) - } - } - } - Ok(None) => match parse_sha256(&checksum, filename) { - Ok(digest) => { - unsigned_digest.get_or_insert(digest); - } - Err(error) => failures.push(format!("{}: {error:#}", source.checksum_url)), - }, - Err(error) => failures.push(format!("{}: {error:#}", source.checksum_signature_url)), - } - } - if let Some(digest) = unsigned_digest { - // Older releases have only an archive signature. They remain usable, - // but must flow through the controller where minisign can be checked. - return Ok((digest, false)); - } - Err(anyhow!( - "no release source published usable checksum metadata for {filename}: {}", - failures.join("; ") - )) -} - -fn release_target(os: &str, arch: &str) -> Result<&'static str> { - match (os.trim(), arch.trim()) { - ("Linux", "x86_64" | "amd64") => Ok("x86_64-unknown-linux-gnu"), - ("Linux", "aarch64" | "arm64") => Ok("aarch64-unknown-linux-gnu"), - ("Darwin", "x86_64" | "amd64") => Ok("x86_64-apple-darwin"), - ("Darwin", "aarch64" | "arm64") => Ok("aarch64-apple-darwin"), - (os, arch) => Err(anyhow!( - "OpenBitFun SSH dispatch CLI install does not support {os} {arch}" - )), - } -} - -fn release_http_client() -> Result { - crate::reqwest_client_builder() - .connect_timeout(Duration::from_secs(10)) - // Per-read rather than whole-request: a genuine slow link may take - // longer than an arbitrary archive deadline, but a stalled source must - // still fail instead of hanging the installer forever. - .read_timeout(Duration::from_secs(RELEASE_READ_TIMEOUT_SECONDS)) - .build() - .context("build OpenBitFun release HTTP client") -} - -async fn fetch_required_text(client: &reqwest::Client, url: &str) -> Result { - client - .get(url) - .send() - .await - .with_context(|| format!("request {url}"))? - .error_for_status() - .with_context(|| format!("download {url}"))? - .text() - .await - .with_context(|| format!("read {url}")) -} - -/// Fetch a release sidecar that older releases legitimately do not have. -/// Only a definite 404 maps to `None`; any other failure stays an error so a -/// flaky network cannot silently downgrade verification. -async fn fetch_optional_text(client: &reqwest::Client, url: &str) -> Result> { - let response = client - .get(url) - .send() - .await - .with_context(|| format!("request {url}"))?; - if response.status() == reqwest::StatusCode::NOT_FOUND { - return Ok(None); - } - let text = response - .error_for_status() - .with_context(|| format!("download {url}"))? - .text() - .await - .with_context(|| format!("read {url}"))?; - Ok(Some(text)) -} - -async fn download_verified_archive(release: &ResolvedRelease) -> Result> { - let pubkey = require_release_pubkey()?; - let client = release_http_client()?; - - // Re-fetch and verify the signed sidecar at install time instead of trusting - // a possibly stale preflight result. - let (expected, _) = - resolve_release_digest(&client, &release.sources, pubkey, &release.filename).await?; - if !expected.eq_ignore_ascii_case(&release.public.sha256) { - return Err(anyhow!( - "release checksum changed after preflight; refusing to install" - )); - } - - let ordered = ordered_release_sources(&client, release).await; - let mut failures = Vec::new(); - for source in &ordered { - let archive = match download_release_bytes(&client, &source.url).await { - Ok(archive) => archive, - Err(error) => { - failures.push(format!("{}: {error:#}", source.url)); - continue; - } - }; - if let Err(error) = verify_sha256(&archive, &expected, &release.filename) { - failures.push(format!("{}: {error:#}", source.url)); - continue; - } - - let mut signature_verified = false; - for signature_source in std::iter::once(source).chain( - ordered - .iter() - .filter(|candidate| candidate.url != source.url), - ) { - let signature = - match fetch_required_text(&client, &signature_source.archive_signature_url).await { - Ok(signature) => signature, - Err(error) => { - failures.push(format!( - "{}: {error:#}", - signature_source.archive_signature_url - )); - continue; - } - }; - match verify_minisign(&archive, &signature, pubkey) { - Ok(()) => { - signature_verified = true; - break; - } - Err(error) => failures.push(format!( - "{}: {error:#}", - signature_source.archive_signature_url - )), - } - } - if signature_verified { - return Ok(archive); - } - } - - Err(anyhow!( - "OpenBitFun CLI archive failed from every source: {}", - failures.join("; ") - )) -} - -async fn ordered_release_sources( - client: &reqwest::Client, - release: &ResolvedRelease, -) -> Vec { - let mut sources = release.sources.clone(); - let Some(github_index) = sources - .iter() - .position(|source| source.origin == ReleaseOrigin::GitHub) - else { - return sources; - }; - let github_speed = probe_release_throughput(client, &sources[github_index].url).await; - log::debug!( - "Dispatch CLI GitHub probe: {} B/s from {}", - github_speed, - sources[github_index].url - ); - order_release_sources_for_speed(&mut sources, github_speed); - sources -} - -fn order_release_sources_for_speed(sources: &mut [ReleaseArtifactSource], github_speed: u64) { - let Some(github_index) = sources - .iter() - .position(|source| source.origin == ReleaseOrigin::GitHub) - else { - return; - }; - if github_speed >= GITHUB_HEALTHY_THROUGHPUT - || !sources - .iter() - .any(|source| source.origin == ReleaseOrigin::OpenBitFun) - { - sources.swap(0, github_index); - } else if let Some(mirror_index) = sources - .iter() - .position(|source| source.origin == ReleaseOrigin::OpenBitFun) - { - sources.swap(0, mirror_index); - } -} - -async fn probe_release_throughput(client: &reqwest::Client, url: &str) -> u64 { - let started = std::time::Instant::now(); - let request = client - .get(url) - .header( - reqwest::header::RANGE, - format!("bytes=0-{}", RELEASE_PROBE_BYTES - 1), - ) - .send(); - let Ok(Ok(mut response)) = tokio::time::timeout(RELEASE_PROBE_WINDOW, request).await else { - return 0; - }; - if !response.status().is_success() { - return 0; - } - let mut received = 0u64; - loop { - let Some(remaining) = RELEASE_PROBE_WINDOW.checked_sub(started.elapsed()) else { - break; - }; - if remaining.is_zero() { - break; - } - match tokio::time::timeout(remaining, response.chunk()).await { - Ok(Ok(Some(chunk))) => received += chunk.len() as u64, - _ => break, - } - if received >= RELEASE_PROBE_BYTES { - break; - } - } - (received as f64 / started.elapsed().as_secs_f64().max(0.001)) as u64 -} - -async fn download_release_bytes(client: &reqwest::Client, url: &str) -> Result> { - let mut response = client - .get(url) - .send() - .await - .with_context(|| format!("request {url}"))? - .error_for_status() - .with_context(|| format!("download {url}"))?; - if response - .content_length() - .is_some_and(|length| length > MAX_ARCHIVE_BYTES as u64) - { - return Err(anyhow!( - "OpenBitFun CLI archive exceeds the {} MB safety limit", - MAX_ARCHIVE_BYTES / (1024 * 1024) - )); - } - let mut archive = Vec::new(); - while let Some(chunk) = response - .chunk() - .await - .with_context(|| format!("read {url}"))? - { - extend_bounded_archive(&mut archive, &chunk, MAX_ARCHIVE_BYTES)?; - } - Ok(archive) -} - -fn extend_bounded_archive(archive: &mut Vec, chunk: &[u8], limit: usize) -> Result<()> { - if archive.len().saturating_add(chunk.len()) > limit { - return Err(anyhow!( - "OpenBitFun CLI archive exceeds the {} MB safety limit", - limit / (1024 * 1024) - )); - } - archive.extend_from_slice(chunk); - Ok(()) -} - -/// State paths, single-binary staging, rollback, and the exit trap shared by -/// every signed release installation. -fn install_preamble_fragment(dir: &str, expected_version: &str) -> String { - let product_home = product_home_shell_path(&[]); - let hidden_data_directory = openbitfun_services_core::product_identity::hidden_data_directory(); - format!( - r#"#!/bin/bash -set -euo pipefail -umask 077 -D={dir} -EXPECTED_VERSION={version} -TOKEN="${{1:-}}" -PIDF="$D/{INSTALL_STEM}.pid" -EXITF="$D/{INSTALL_STEM}.exit" -TMP="$D/unpack.$$" -TARGET="$HOME/.local/bin/openbitfun" -# Stage under the final filename on the same filesystem as the target so the -# publish step is one atomic rename. -STAGE="$HOME/.local/bin/{hidden_data_directory}-dispatch-stage-$$" -NEW="$STAGE/openbitfun" -BACKUP="$STAGE/previous-openbitfun" -HAD_TARGET=0 -TARGET_INSTALLED=0 -COMMITTED=0 -RECOVERY_FAILED=0 -PID_LOCK=0 -rollback_install() {{ - if [ "$TARGET_INSTALLED" = "1" ]; then rm -f "$TARGET" || RECOVERY_FAILED=1; fi - if [ "$HAD_TARGET" = "1" ] && [ -f "$BACKUP" ]; then - mv -f "$BACKUP" "$TARGET" \ - || RECOVERY_FAILED=1 - fi -}} -finish() {{ - code=$? - trap - EXIT HUP INT TERM - set +e - if [ "$code" -ne 0 ] && [ "$COMMITTED" != "1" ]; then rollback_install; fi - if [ "$RECOVERY_FAILED" = "0" ]; then - rm -rf "$STAGE" - else - echo "ERROR: CLI recovery failed; backups retained at $STAGE" >&2 - fi - if [ "$PID_LOCK" = "1" ]; then rm -f "$HOME/.local/bin/.openbitfun-cli-install.lock"; fi - rm -rf "$TMP" - printf '%s\n' "$code" >"$EXITF" - marker_token="$(sed -n '2p' "$PIDF" 2>/dev/null | tr -d '[:space:]')" - if [ -n "$TOKEN" ] && [ "$marker_token" = "$TOKEN" ]; then rm -f "$PIDF"; fi - exit "$code" -}} -trap finish EXIT -trap 'exit 130' HUP INT TERM -rm -f "$EXITF" -mkdir -p "$TMP" "$STAGE" "$HOME/.local/bin" "{product_home}" -chmod 700 "{product_home}" "$STAGE" -if command -v flock >/dev/null 2>&1; then - exec 9>"$HOME/.local/bin/.openbitfun-cli-install.lock" - flock -n 9 || {{ echo 'ERROR: another CLI installation or update is running' >&2; exit 1; }} -elif command -v shlock >/dev/null 2>&1; then - shlock -p "$$" -f "$HOME/.local/bin/.openbitfun-cli-install.lock" || {{ echo 'ERROR: another CLI installation is running' >&2; exit 1; }} - PID_LOCK=1 -else - echo 'ERROR: CLI installation requires flock or shlock' >&2; exit 1 -fi -"#, - dir = shell_quote_posix(dir), - version = shell_quote_posix(expected_version), - ) -} - -/// Stage, smoke-test, and atomically commit the single `openbitfun` binary. -/// -/// `post_commit` runs once the swap has succeeded, for path-specific cleanup. -fn install_commit_fragment(post_commit: &str) -> String { - let product_id = openbitfun_services_core::product_identity::product_id(); - let data_namespace = openbitfun_services_core::product_identity::data_namespace(); - format!( - r#"cp "$BINARY" "$NEW" -chmod 755 "$NEW" -staged="$("$NEW" --version 2>/dev/null || true)" -case "$staged" in - *"$EXPECTED_VERSION"*) ;; - *) echo "ERROR: staged CLI version did not match $EXPECTED_VERSION: $staged" >&2; exit 1 ;; -esac -# This installer exists only to serve dispatch, so a build without the -# subcommand is a failed install, not a successful one. Checking here — before -# anything is replaced — turns "install succeeded but the target is still -# reported incompatible" into one honest error at the point of cause. -if ! staged_dispatch="$("$NEW" dispatch --help 2>&1 >/dev/null)"; then - echo "ERROR: this OpenBitFun build does not provide dispatch support: $staged_dispatch" >&2 - exit 1 -fi -if ! staged_probe="$(printf '{{}}\n' | "$NEW" dispatch probe 2>/dev/null)"; then - echo "ERROR: staged OpenBitFun dispatch probe failed" >&2 - exit 1 -fi -case "$staged_probe" in - *'"productId":"{product_id}",'*) ;; - *) echo "ERROR: staged OpenBitFun CLI returned the wrong product identity" >&2; exit 1 ;; -esac -case "$staged_probe" in - *'"dataNamespace":"{data_namespace}",'*) ;; - *) echo "ERROR: staged OpenBitFun CLI returned the wrong data namespace" >&2; exit 1 ;; -esac -case "$staged_probe" in - *'"protocolVersion":{protocol_version},'*) ;; - *) echo "ERROR: staged OpenBitFun CLI returned an incompatible dispatch protocol" >&2; exit 1 ;; -esac -case "$staged_probe" in - *'"{worker_profile_capability}"'*) ;; - *) echo "ERROR: staged OpenBitFun CLI lacks safe dispatch worker profile selection" >&2; exit 1 ;; -esac -if [ -e "$TARGET" ]; then - mv -f "$TARGET" "$BACKUP" - HAD_TARGET=1 -fi -mv -f "$NEW" "$TARGET" -TARGET_INSTALLED=1 -installed="$("$TARGET" --version 2>/dev/null || true)" -case "$installed" in - *"$EXPECTED_VERSION"*) ;; - *) echo "ERROR: installed CLI version did not match $EXPECTED_VERSION: $installed" >&2; exit 1 ;; -esac -COMMITTED=1 -{post_commit} -echo "Installed $installed at $HOME/.local/bin/openbitfun" -echo {INSTALL_DONE_MARKER} -"#, - product_id = product_id, - data_namespace = data_namespace, - protocol_version = DISPATCH_PROTOCOL_VERSION, - worker_profile_capability = "dispatch_worker_cli_profile", - ) -} - -fn install_body_script( - dir: &str, - archive_path: &str, - expected_version: &str, - archive_source: &ArchiveSource, -) -> String { - // Surfaced in the install output so the topology actually used is visible - // rather than guessed at. - let source_note = match archive_source { - ArchiveSource::TargetDownload => { - "Archive downloaded on the target and verified against the signed checksum.".to_string() - } - ArchiveSource::ControllerPush { reason } => { - format!("Archive uploaded from this device ({reason}).") - } - }; - let extract = format!( - r#"ARCHIVE={archive} -echo {source_note} -tar -xzf "$ARCHIVE" -C "$TMP" -BINARY="" -for candidate in "$TMP"/*/openbitfun; do - [ -f "$candidate" ] || continue - [ -z "$BINARY" ] || {{ echo "ERROR: archive contains multiple openbitfun binaries" >&2; exit 1; }} - BINARY="$candidate" -done -for candidate in "$TMP"/*/openbitfun-cli; do - [ ! -e "$candidate" ] || {{ echo "ERROR: archive contains an unsupported legacy CLI entrypoint" >&2; exit 1; }} -done -[ -n "$BINARY" ] || {{ echo "ERROR: archive contains no openbitfun binary" >&2; exit 1; }} -"#, - archive = shell_quote_posix(archive_path), - source_note = shell_quote_posix(&source_note), - ); - format!( - "{preamble}{extract}{commit}", - preamble = install_preamble_fragment(dir, expected_version), - commit = install_commit_fragment(r#"rm -f "$ARCHIVE""#), - ) -} - -fn install_driver_script(dir: &str, body_path: &str, install_token: &str) -> String { - format!( - r#"#!/bin/bash -set -euo pipefail -umask 077 -D={dir} -BODY={body} -EXPECTED_TOKEN={token} -TOKEN="${{1:-}}" -LOG="$D/{INSTALL_STEM}.log" -PIDF="$D/{INSTALL_STEM}.pid" -PIDF_TMP="$PIDF.$$" -DRIVER_PIDF="$D/{INSTALL_STEM}.driver.pid" -DRIVER_PIDF_TMP="$DRIVER_PIDF.$$" -PREPF="$D/{INSTALL_STEM}.preparing" -EXITF="$D/{INSTALL_STEM}.exit" -body_pid= -[ "$TOKEN" = "$EXPECTED_TOKEN" ] || exit 2 -cleanup_prepare() {{ - if [ -n "$body_pid" ] && [ ! -f "$PIDF" ]; then - kill "$body_pid" 2>/dev/null || true - fi - prepare_token="$(tr -d '[:space:]' < "$PREPF" 2>/dev/null || true)" - if [ "$prepare_token" = "$TOKEN" ]; then rm -f "$PREPF"; fi - driver_marker_token="$(sed -n '2p' "$DRIVER_PIDF" 2>/dev/null | tr -d '[:space:]')" - if [ "$driver_marker_token" = "$TOKEN" ]; then rm -f "$DRIVER_PIDF"; fi - rm -f "$PIDF_TMP" "$DRIVER_PIDF_TMP" -}} -cancel_prepare() {{ cleanup_prepare; exit 130; }} -trap cleanup_prepare EXIT -trap cancel_prepare HUP INT TERM -printf '%s\n%s\n' "$$" "$TOKEN" >"$DRIVER_PIDF_TMP" -mv -f "$DRIVER_PIDF_TMP" "$DRIVER_PIDF" -prepare_token="$(tr -d '[:space:]' < "$PREPF" 2>/dev/null || true)" -[ "$prepare_token" = "$TOKEN" ] || exit 130 -rm -f "$PIDF" "$EXITF" -: >"$LOG" -prepare_token="$(tr -d '[:space:]' < "$PREPF" 2>/dev/null || true)" -[ "$prepare_token" = "$TOKEN" ] || exit 130 -nohup bash "$BODY" "$TOKEN" >"$LOG" 2>&1 < /dev/null & -body_pid=$! -printf '%s\n%s\n' "$body_pid" "$TOKEN" >"$PIDF_TMP" -mv -f "$PIDF_TMP" "$PIDF" -body_pid= -rm -f "$PREPF" "$DRIVER_PIDF" -trap - EXIT HUP INT TERM -exit 0 -"#, - dir = shell_quote_posix(dir), - body = shell_quote_posix(body_path), - token = shell_quote_posix(install_token), - ) -} - -#[allow(clippy::too_many_arguments)] -fn stage_install_command( - archive_path: &str, - body_path: &str, - script_path: &str, - log_path: &str, - pid_path: &str, - driver_pid_path: &str, - prepare_path: &str, - exit_path: &str, - install_token: &str, -) -> String { - format!( - "chmod 600 {archive} && chmod 700 {body} {script} \ - && rm -f {pid} {driver_pid} {exit} \ - && : > {log} && chmod 600 {log} \ - && printf '%s\\n' {token} > {prepare} && chmod 600 {prepare}", - archive = shell_quote_posix(archive_path), - body = shell_quote_posix(body_path), - script = shell_quote_posix(script_path), - pid = shell_quote_posix(pid_path), - driver_pid = shell_quote_posix(driver_pid_path), - exit = shell_quote_posix(exit_path), - log = shell_quote_posix(log_path), - prepare = shell_quote_posix(prepare_path), - token = shell_quote_posix(install_token), - ) -} - -fn install_poll_script(cursor: u64) -> String { - let install_state_dir = install_state_relative_dir(); - format!( - r#" -D="$HOME/{install_state_dir}" -LOG="$D/{INSTALL_STEM}.log" -PIDF="$D/{INSTALL_STEM}.pid" -DRIVER_PIDF="$D/{INSTALL_STEM}.driver.pid" -PREPF="$D/{INSTALL_STEM}.preparing" -EXITF="$D/{INSTALL_STEM}.exit" -BODY="$D/{INSTALL_STEM}-body.sh" -DRIVER="$D/{INSTALL_STEM}.sh" -process_command() {{ - p="$1" - case "$p" in ''|*[!0-9]*) return 1 ;; esac - kill -0 "$p" 2>/dev/null || return 1 - ps -ww -p "$p" -o command= 2>/dev/null -}} -installer_matches() {{ - p="$1" - token="$2" - [ -n "$token" ] || return 1 - command="$(process_command "$p")" || return 1 - case "$command" in - *"$BODY"*"$token"*) return 0 ;; - *) return 1 ;; - esac -}} -driver_matches() {{ - p="$1" - token="$2" - [ -n "$token" ] || return 1 - command="$(process_command "$p")" || return 1 - case "$command" in - *"$DRIVER"*"$token"*) return 0 ;; - *) return 1 ;; - esac -}} -running=0 -if [ -f "$PIDF" ]; then - pid="$(sed -n '1p' "$PIDF" | tr -d '[:space:]')" - token="$(sed -n '2p' "$PIDF" | tr -d '[:space:]')" - if installer_matches "$pid" "$token"; then - running=1 - else - rm -f "$PIDF" - fi -fi -preparing=0 -if [ -f "$PREPF" ]; then - driver_live=0 - prepare_token="$(tr -d '[:space:]' < "$PREPF" 2>/dev/null || true)" - if [ -f "$DRIVER_PIDF" ]; then - driver_pid="$(sed -n '1p' "$DRIVER_PIDF" | tr -d '[:space:]')" - driver_token="$(sed -n '2p' "$DRIVER_PIDF" | tr -d '[:space:]')" - if [ "$driver_token" = "$prepare_token" ] && driver_matches "$driver_pid" "$driver_token"; then - driver_live=1 - else - rm -f "$DRIVER_PIDF" - fi - fi - if [ "$driver_live" = "1" ]; then - preparing=1 - else - now="$(date +%s 2>/dev/null || true)" - mtime="$(stat -c %Y "$PREPF" 2>/dev/null || stat -f %m "$PREPF" 2>/dev/null || true)" - if [ -n "$now" ] && [ -n "$mtime" ] && [ $((now - mtime)) -lt {grace} ]; then - preparing=1 - fi - fi -fi -size=0 -if [ -f "$LOG" ]; then size="$(wc -c < "$LOG" | tr -d ' ')"; fi -marker=0 -if [ -f "$LOG" ] && grep -q {marker} "$LOG"; then marker=1; fi -exit_recorded=0 -exit_code= -if [ -f "$EXITF" ]; then - exit_recorded=1 - exit_code="$(tr -d '[:space:]' < "$EXITF")" -fi -printf 'running=%s\n' "$running" -printf 'preparing=%s\n' "$preparing" -printf 'size=%s\n' "$size" -printf 'marker=%s\n' "$marker" -printf 'exit_recorded=%s\n' "$exit_recorded" -printf 'exit_code=%s\n' "$exit_code" -printf '%s\n' '---' -from={from} -if [ "$from" -gt "$size" ]; then from=1; fi -if [ -f "$LOG" ]; then tail -c +"$from" "$LOG"; fi -"#, - grace = INSTALL_PREPARE_GRACE_SECONDS, - marker = shell_quote_posix(INSTALL_DONE_MARKER), - from = cursor.saturating_add(1), - ) -} - -fn install_cancel_script() -> String { - let install_state_dir = install_state_relative_dir(); - format!( - r#" -set +e -D="$HOME/{install_state_dir}" -LOG="$D/{INSTALL_STEM}.log" -PIDF="$D/{INSTALL_STEM}.pid" -DRIVER_PIDF="$D/{INSTALL_STEM}.driver.pid" -PREPF="$D/{INSTALL_STEM}.preparing" -EXITF="$D/{INSTALL_STEM}.exit" -BODY="$D/{INSTALL_STEM}-body.sh" -DRIVER="$D/{INSTALL_STEM}.sh" -active=0 -[ -f "$PREPF" ] && active=1 -# Invalidate a driver that has not reached its guarded spawn point yet. -rm -f "$PREPF" -installer_matches() {{ - p="$1" - token="$2" - case "$p" in ''|*[!0-9]*) return 1 ;; esac - [ -n "$token" ] || return 1 - kill -0 "$p" 2>/dev/null || return 1 - command="$(ps -ww -p "$p" -o command= 2>/dev/null)" || return 1 - case "$command" in - *"$BODY"*"$token"*) return 0 ;; - *) return 1 ;; - esac -}} -driver_matches() {{ - p="$1" - token="$2" - case "$p" in ''|*[!0-9]*) return 1 ;; esac - [ -n "$token" ] || return 1 - kill -0 "$p" 2>/dev/null || return 1 - command="$(ps -ww -p "$p" -o command= 2>/dev/null)" || return 1 - case "$command" in - *"$DRIVER"*"$token"*) return 0 ;; - *) return 1 ;; - esac -}} -kill_tree() {{ - p="$1" - sig="$2" - case "$p" in ''|*[!0-9]*) return 0 ;; esac - for child in $(pgrep -P "$p" 2>/dev/null); do kill_tree "$child" "$sig"; done - kill "-$sig" "$p" 2>/dev/null || true -}} -if [ -f "$DRIVER_PIDF" ]; then - driver_pid="$(sed -n '1p' "$DRIVER_PIDF" | tr -d '[:space:]')" - driver_token="$(sed -n '2p' "$DRIVER_PIDF" | tr -d '[:space:]')" - if driver_matches "$driver_pid" "$driver_token"; then - active=1 - kill_tree "$driver_pid" TERM - sleep 1 - if driver_matches "$driver_pid" "$driver_token"; then - kill_tree "$driver_pid" KILL - fi - fi -fi -if [ -f "$PIDF" ]; then - pid="$(sed -n '1p' "$PIDF" | tr -d '[:space:]')" - token="$(sed -n '2p' "$PIDF" | tr -d '[:space:]')" - if installer_matches "$pid" "$token"; then - active=1 - kill_tree "$pid" TERM - sleep 1 - if installer_matches "$pid" "$token"; then kill_tree "$pid" KILL; fi - fi -fi -rm -f "$PIDF" "$DRIVER_PIDF" "$PREPF" -if [ "$active" = "1" ]; then - printf '130\n' >"$EXITF" - printf '\nOpenBitFun CLI installation cancelled by client.\n' >>"$LOG" -fi -exit 0 "# - ) -} - -fn to_unix_script(script: &str) -> String { - script.replace("\r\n", "\n") -} - -fn split_metadata_output(stdout: &str) -> (&str, &str) { - if let Some((head, output)) = stdout.split_once("---\r\n") { - return (head, output); - } - if let Some((head, output)) = stdout.split_once("---\n") { - return (head, output); - } - let mut offset = 0usize; - for line in stdout.split_inclusive('\n') { - if line.trim_end_matches(['\r', '\n']) == "---" { - return (&stdout[..offset], &stdout[offset + line.len()..]); - } - offset += line.len(); - } - (stdout, "") } async fn exec_ok(manager: &SSHConnectionManager, connection_id: &str, command: &str) -> Result<()> { @@ -3142,79 +1131,10 @@ fn bounded_detail(value: &str) -> String { value.trim().chars().take(500).collect() } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn generated_install_scripts_are_lf_only_and_never_use_sudo() { - let body = install_body_script( - "/home/user/.openbitfun/dispatch/install", - "/home/user/.openbitfun/dispatch/install/archive.tar.gz", - "1.2.3", - &ArchiveSource::TargetDownload, - ); - let driver = install_driver_script( - "/home/user/.openbitfun/dispatch/install", - "/home/user/.openbitfun/dispatch/install/install-cli-body.sh", - "openbitfun-install-test-token", - ); - for (name, script) in [("body", body), ("driver", driver)] { - let script = to_unix_script(&script); - assert!(!script.contains('\r'), "{name} must be LF-only"); - assert!( - !script.contains("sudo"), - "{name} must never modify privileged paths" - ); - assert!(!script.contains("/usr/")); - } - } - - fn test_release(checksum_signature_verified: bool) -> ResolvedRelease { - let github_url = "https://github.example.invalid/openbitfun-cli.tar.gz"; - let mirror_url = "https://mirror.example.invalid/openbitfun-cli.tar.gz"; - ResolvedRelease { - public: DispatchCliRelease { - version: "1.2.3".to_string(), - target: "x86_64-unknown-linux-gnu".to_string(), - url: github_url.to_string(), - sha256: "a".repeat(64), - }, - filename: "openbitfun-cli.tar.gz".to_string(), - sources: [ - (ReleaseOrigin::GitHub, github_url), - (ReleaseOrigin::OpenBitFun, mirror_url), - ] - .into_iter() - .map(|(origin, url)| ReleaseArtifactSource { - origin, - url: url.to_string(), - checksum_url: format!("{url}.sha256"), - checksum_signature_url: format!("{url}.sha256.sig"), - archive_signature_url: format!("{url}.sig"), - }) - .collect(), - checksum_signature_verified, - } - } - - fn test_target( - downloader: Option, - digest_tool: Option, - ) -> RemoteTarget { - RemoteTarget { - os: "Linux".to_string(), - arch: "x86_64".to_string(), - home: "/home/user".to_string(), - cli_path: None, - tar_available: true, - downloader, - digest_tool, - libc: Some(RemoteLibc::Glibc), - libc_version: Some("2.39".to_string()), - } - } - +#[cfg(test)] +mod tests { + use super::*; + #[test] fn git_worktree_delivery_capabilities_are_required() { for capability in [ @@ -3318,671 +1238,6 @@ mod tests { } } - #[test] - fn glibc_versions_compare_numerically_not_lexicographically() { - use std::cmp::Ordering; - // The reason this needs its own function: as strings, "2.9" sorts above - // "2.35", which would call a too-old host compatible. - assert_eq!(compare_versions("2.9", "2.35"), Ordering::Less); - assert_eq!(compare_versions("2.35", "2.35"), Ordering::Equal); - assert_eq!(compare_versions("2.39", "2.35"), Ordering::Greater); - assert_eq!(compare_versions("3.0", "2.35"), Ordering::Greater); - assert_eq!(compare_versions("2.35.1", "2.35"), Ordering::Greater); - } - - #[test] - fn incompatible_targets_are_named_precisely() { - let mut target = test_target( - Some(RemoteDownloader::Curl), - Some(RemoteDigestTool::Sha256Sum), - ); - - assert!( - prebuilt_incompatibility(&target).is_none(), - "a supported glibc host has no incompatibility" - ); - - target.libc = Some(RemoteLibc::Musl); - assert_eq!( - prebuilt_incompatibility(&target), - Some(PrebuiltIncompatibility::MuslLibc) - ); - - target.libc = Some(RemoteLibc::Glibc); - target.libc_version = Some("2.31".to_string()); - assert_eq!( - prebuilt_incompatibility(&target), - Some(PrebuiltIncompatibility::GlibcTooOld { - found: "2.31".to_string() - }) - ); - - target.libc_version = Some("2.39".to_string()); - target.arch = "riscv64".to_string(); - assert!(matches!( - prebuilt_incompatibility(&target), - Some(PrebuiltIncompatibility::UnsupportedPlatform { .. }) - )); - - // macOS binaries carry no libc floor, so a musl reading must not leak in. - let mut mac = test_target(None, None); - mac.os = "Darwin".to_string(); - mac.arch = "arm64".to_string(); - mac.libc = Some(RemoteLibc::Musl); - assert!(prebuilt_incompatibility(&mac).is_none()); - } - - #[test] - fn the_install_path_uses_the_shared_staging_and_commit_implementation() { - let release = install_body_script( - "/home/user/.openbitfun/dispatch/install", - "/home/user/.openbitfun/dispatch/install/archive.tar.gz", - "1.2.3", - &ArchiveSource::TargetDownload, - ); - // Installing a signed release is the only way a target gets a CLI, so - // its atomic-replace and rollback semantics must come from the shared - // fragment rather than being restated inline. - let commit = install_commit_fragment(r#"rm -f "$ARCHIVE""#); - let shared = commit - .lines() - .find(|line| line.contains("mv -f \"$NEW\"")) - .expect("commit fragment swaps the binary"); - assert!( - release.contains(shared), - "release must use the shared commit" - ); - assert!( - release.contains(r#"NEW="$STAGE/openbitfun""#), - "release must stage under the final filename" - ); - assert!( - release.contains("rollback_install"), - "release must keep rollback" - ); - assert!( - release.contains("dispatch_worker_cli_profile"), - "release must reject a CLI whose detached worker can select the wrong profile" - ); - assert!( - !release.contains("cargo build"), - "no install path may compile OpenBitFun on the target" - ); - } - - #[test] - fn release_compatibility_uses_capability_floor_not_installed_version() { - assert!( - !published_release_supports_required_dispatch_protocol("0.2.15"), - "OpenBitFun releases predate the OpenBitFun product contract" - ); - assert!( - !published_release_supports_required_dispatch_protocol("0.2.16"), - "a previously compatible OpenBitFun release is not an OpenBitFun release" - ); - assert!(!published_release_supports_required_dispatch_protocol( - "0.3.0+build.1" - )); - assert!(!published_release_supports_required_dispatch_protocol( - "1.0.0-nightly.1" - )); - assert!(published_release_supports_required_dispatch_protocol( - "1.0.0" - )); - assert!(published_release_supports_required_dispatch_protocol( - "1.0.1+build.1" - )); - assert!(!published_release_supports_required_dispatch_protocol( - "not-a-version" - )); - } - - #[test] - fn latest_release_manifest_accepts_only_stable_semver() { - assert_eq!( - latest_release_version_from_json(r#"{"version":"1.2.3"}"#, "fixture").unwrap(), - "1.2.3" - ); - assert!( - latest_release_version_from_json(r#"{"version":"1.2.4-nightly.1"}"#, "fixture") - .is_err() - ); - assert!(latest_release_version_from_json(r#"{"version":"latest"}"#, "fixture").is_err()); - } - - #[test] - fn latest_cli_sources_are_github_then_the_versioned_openbitfun_mirror() { - let filename = "openbitfun-cli-1.2.3-x86_64-unknown-linux-gnu.tar.gz"; - let sources = release_sources("1.2.3", filename); - assert_eq!(sources[0].origin, ReleaseOrigin::GitHub); - assert_eq!( - sources[0].url, - format!("https://github.com/openBitFun/OpenBitFun/releases/download/v1.2.3/{filename}") - ); - assert_eq!(sources[1].origin, ReleaseOrigin::OpenBitFun); - assert_eq!( - sources[1].url, - format!("https://openbitfun.com/release/1.2.3/{filename}") - ); - } - - #[test] - fn dispatch_cli_uses_the_mirror_only_below_the_github_speed_floor() { - let mut slow = test_release(true).sources; - order_release_sources_for_speed(&mut slow, GITHUB_HEALTHY_THROUGHPUT - 1); - assert_eq!(slow[0].origin, ReleaseOrigin::OpenBitFun); - - let mut healthy = test_release(true).sources; - healthy.swap(0, 1); - order_release_sources_for_speed(&mut healthy, GITHUB_HEALTHY_THROUGHPUT); - assert_eq!(healthy[0].origin, ReleaseOrigin::GitHub); - } - - #[test] - fn target_download_script_contains_the_same_speed_policy_and_both_sources() { - let script = target_download_script( - RemoteDownloader::Curl, - RemoteDigestTool::Sha256Sum, - "/tmp/openbitfun.tar.gz", - "https://github.example/openbitfun.tar.gz", - "https://mirror.example/openbitfun.tar.gz", - &"a".repeat(64), - ); - assert!(script.contains("524288")); - assert!(script.contains("GITHUB_SPEED")); - assert!(script.contains("https://github.example/openbitfun.tar.gz")); - assert!(script.contains("https://mirror.example/openbitfun.tar.gz")); - } - - #[test] - fn an_unsigned_checksum_never_lets_the_target_fetch_the_release() { - // The target can only check a plain digest. If that digest is not - // provably the publisher's, the archive's own signature is the only - // protection and only this machine can verify it. - let capable = test_target( - Some(RemoteDownloader::Curl), - Some(RemoteDigestTool::Sha256Sum), - ); - let blocker = target_download_blocker(&capable, &test_release(false)); - assert_eq!( - blocker.as_deref(), - Some("release checksum sidecar is unsigned"), - "an unsigned sidecar must force the archive through this machine" - ); - assert!( - target_download_blocker(&capable, &test_release(true)).is_none(), - "a signed sidecar on a capable target should download remotely" - ); - } - - #[test] - fn a_target_missing_its_tools_falls_back_to_the_push_path() { - let signed = test_release(true); - assert!( - target_download_blocker( - &test_target(None, Some(RemoteDigestTool::Sha256Sum)), - &signed - ) - .is_some(), - "no curl or wget must fall back" - ); - assert!( - target_download_blocker(&test_target(Some(RemoteDownloader::Wget), None), &signed) - .is_some(), - "no digest checker must fall back" - ); - } - - #[cfg(unix)] - #[test] - fn target_download_publishes_the_archive_only_when_the_digest_matches() { - let available = |tool: &str| { - std::process::Command::new(tool) - .arg("--version") - .output() - .map(|out| out.status.success()) - .unwrap_or(false) - }; - let Some((digest_command, digest_tool)) = [ - ("sha256sum", RemoteDigestTool::Sha256Sum), - ("shasum -a 256", RemoteDigestTool::Shasum), - ] - .into_iter() - .find(|(command, _)| available(command.split_whitespace().next().unwrap_or(command))) else { - return; // no digest tool on this host - }; - if !available("curl") { - return; // no curl on this host - } - - let temp = tempfile::tempdir().expect("temp dir"); - let source = temp.path().join("release.tar.gz"); - std::fs::write(&source, b"pretend release bytes").expect("write source"); - // Derive the expected digest with the same tool the script will use, - // so this test needs no hashing dependency of its own. - let digest_output = std::process::Command::new("bash") - .args([ - "-c", - &format!( - "{digest_command} {}", - shell_quote_posix(&source.to_string_lossy()) - ), - ]) - .output() - .expect("compute digest"); - assert!(digest_output.status.success(), "digest tool failed"); - let digest = String::from_utf8_lossy(&digest_output.stdout) - .split_whitespace() - .next() - .expect("digest value") - .to_string(); - let url = format!("file://{}", source.display()); - let archive = temp.path().join("staged.tar.gz"); - - let run = |sha: &str| { - let script = target_download_script( - RemoteDownloader::Curl, - digest_tool, - &archive.to_string_lossy(), - &url, - "", - sha, - ); - std::process::Command::new("bash") - .args(["-c", &script]) - .output() - .expect("run target download script") - }; - - let tampered = run(&"b".repeat(64)); - assert!( - !tampered.status.success(), - "a digest mismatch must fail the download" - ); - assert!( - !archive.exists(), - "a mismatched download must never be published to the installer" - ); - - let matched = run(&digest); - assert!( - matched.status.success(), - "a matching digest must succeed:\n{}", - String::from_utf8_lossy(&matched.stderr) - ); - assert_eq!( - std::fs::read(&archive).expect("read staged archive"), - b"pretend release bytes", - "the verified bytes must be published unchanged" - ); - } - - #[test] - fn install_body_stages_only_the_openbitfun_binary_under_its_real_name() { - let body = install_body_script( - "/home/user/.openbitfun/dispatch/install", - "/home/user/.openbitfun/dispatch/install/archive.tar.gz", - "1.2.3", - &ArchiveSource::TargetDownload, - ); - assert!( - body.contains(r#"TARGET="$HOME/.local/bin/openbitfun""#), - "the managed target must use the canonical CLI name" - ); - assert!( - body.contains(r#"NEW="$STAGE/openbitfun""#), - "the binary must stage under its final filename" - ); - assert!( - !body.contains("LEGACY_TARGET") && !body.contains("LEGACY_NEW"), - "the installer must not publish a companion or compatibility entrypoint" - ); - assert!(body.contains(r#""productId":"openbitfun""#)); - assert!(body.contains(r#""dataNamespace":"openbitfun""#)); - } - - fn dispatch_capable_binary(capabilities: &str) -> String { - format!( - "#!/bin/bash\n\ - if [ \"${{1:-}}\" = dispatch ]; then\n\ - if [ \"${{2:-}}\" = probe ]; then\n\ - echo '{{\"productId\":\"{}\",\"dataNamespace\":\"{}\",\"protocolVersion\":{},\"capabilities\":{capabilities}}}'\n\ - fi\n\ - exit 0\n\ - fi\n\ - echo \"openbitfun 1.2.3\"\n", - openbitfun_services_core::product_identity::product_id(), - openbitfun_services_core::product_identity::data_namespace(), - DISPATCH_PROTOCOL_VERSION, - ) - } - - /// Mirrors a release that predates dispatch: the binary is healthy and - /// reports the right version, but clap rejects the subcommand. - const DISPATCH_LESS_PRIMARY: &str = "#!/bin/bash\n\ - if [ \"${1:-}\" = dispatch ]; then\n\ - echo \"error: unrecognized subcommand 'dispatch'\" >&2\n\ - exit 2\n\ - fi\n\ - echo \"openbitfun 1.2.3\"\n"; - - #[cfg(unix)] - #[test] - fn a_build_without_dispatch_fails_the_install_instead_of_looking_healthy() { - // The scenario that motivated this check: a release whose binary runs - // and reports the expected version, but carries no dispatch support. - // Without the guard the install "succeeds" and the target is then - // reported incompatible, inviting an endless reinstall loop. - let (output, temp) = run_install_body_fixture(DISPATCH_LESS_PRIMARY); - let home = temp.path(); - assert!( - !output.status.success(), - "an install that cannot serve dispatch must fail" - ); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("does not provide dispatch support"), - "the failure must name the cause: {stderr}" - ); - assert!( - stderr.contains("unrecognized subcommand"), - "the underlying message must survive: {stderr}" - ); - assert!( - !home.join(".local/bin/openbitfun").exists(), - "nothing may be published when the build cannot serve dispatch" - ); - } - - #[cfg(unix)] - #[test] - fn a_dispatch_build_without_safe_worker_profile_selection_is_not_installed() { - let unsafe_binary = dispatch_capable_binary("[]"); - let (output, temp) = run_install_body_fixture(&unsafe_binary); - assert!( - !output.status.success(), - "a target that accepts jobs but cannot run workers must fail installation" - ); - assert!( - String::from_utf8_lossy(&output.stderr) - .contains("lacks safe dispatch worker profile selection"), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - assert!(!temp.path().join(".local/bin/openbitfun").exists()); - } - - #[cfg(unix)] - fn run_install_body_fixture(primary: &str) -> (std::process::Output, tempfile::TempDir) { - use std::os::unix::fs::PermissionsExt; - - let temp = tempfile::tempdir().expect("temp dir"); - let home = temp.path().to_path_buf(); - let install_dir = home.join(install_state_relative_dir()); - std::fs::create_dir_all(&install_dir).expect("install dir"); - let pkg = temp.path().join("pkg/openbitfun-cli-1.2.3-test"); - std::fs::create_dir_all(&pkg).expect("package dir"); - std::fs::write(pkg.join("openbitfun"), primary).expect("write binary"); - std::fs::set_permissions( - pkg.join("openbitfun"), - std::fs::Permissions::from_mode(0o755), - ) - .expect("chmod package binary"); - let archive = install_dir.join("archive.tar.gz"); - assert!(std::process::Command::new("tar") - .arg("-czf") - .arg(&archive) - .arg("-C") - .arg(temp.path().join("pkg")) - .arg("openbitfun-cli-1.2.3-test") - .status() - .expect("run tar") - .success()); - std::fs::write( - install_dir.join(format!("{INSTALL_STEM}.pid")), - "1\ntest-token\n", - ) - .expect("write pid marker"); - let script = to_unix_script(&install_body_script( - &install_dir.to_string_lossy(), - &archive.to_string_lossy(), - "1.2.3", - &ArchiveSource::TargetDownload, - )); - let output = std::process::Command::new("bash") - .args(["-c", &script, "install-body", "test-token"]) - .env("HOME", &home) - .output() - .expect("run install body"); - (output, temp) - } - - #[cfg(unix)] - #[test] - fn install_body_installs_only_openbitfun_onto_a_bare_host() { - let binary = dispatch_capable_binary("[\"dispatch_worker_cli_profile\"]"); - let (output, temp) = run_install_body_fixture(&binary); - let home = temp.path(); - - assert!( - output.status.success(), - "install must succeed on a host with no pre-existing OpenBitFun CLI:\nstdout: {}\nstderr: {}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - assert!( - String::from_utf8_lossy(&output.stdout).contains(INSTALL_DONE_MARKER), - "install must report completion" - ); - - let installed = home.join(".local/bin/openbitfun"); - let run = std::process::Command::new(&installed) - .arg("--version") - .output() - .expect("run installed binary"); - assert!(run.status.success(), "openbitfun must run after install"); - assert!(String::from_utf8_lossy(&run.stdout).contains("openbitfun 1.2.3")); - let mut installed_entries: Vec<_> = std::fs::read_dir(home.join(".local/bin")) - .expect("read bin dir") - .map(|entry| entry.expect("read installed entry").file_name()) - .collect(); - installed_entries.retain(|name| name != ".openbitfun-cli-install.lock"); - assert_eq!( - installed_entries, - vec![std::ffi::OsString::from("openbitfun")], - "only the canonical CLI may remain; no aliases or staging directories" - ); - } - - #[cfg(unix)] - #[test] - fn generated_install_scripts_parse_as_bash() { - for script in [ - install_body_script( - "/home/user/.openbitfun/dispatch/install", - "/home/user/.openbitfun/dispatch/install/archive.tar.gz", - "1.2.3", - &ArchiveSource::TargetDownload, - ), - install_driver_script( - "/home/user/.openbitfun/dispatch/install", - "/home/user/.openbitfun/dispatch/install/install-cli-body.sh", - "openbitfun-install-test-token", - ), - target_download_script( - RemoteDownloader::Curl, - RemoteDigestTool::Sha256Sum, - "/home/user/.openbitfun/dispatch/install/archive.tar.gz", - "https://example.invalid/archive.tar.gz", - "https://openbitfun.example.invalid/archive.tar.gz", - &"a".repeat(64), - ), - target_download_script( - RemoteDownloader::Wget, - RemoteDigestTool::Shasum, - "/home/user/.openbitfun/dispatch/install/archive.tar.gz", - "https://example.invalid/archive.tar.gz", - "https://openbitfun.example.invalid/archive.tar.gz", - &"a".repeat(64), - ), - install_poll_script(17), - install_cancel_script(), - ] { - let output = std::process::Command::new("bash") - .args(["-n", "-c", &to_unix_script(&script)]) - .output() - .expect("parse generated shell"); - assert!( - output.status.success(), - "generated shell is invalid:\n{}", - String::from_utf8_lossy(&output.stderr) - ); - } - } - - #[cfg(unix)] - #[test] - fn stale_installer_pid_never_signals_an_unrelated_process() { - let temp = tempfile::tempdir().expect("temp dir"); - let state_dir = temp.path().join(install_state_relative_dir()); - std::fs::create_dir_all(&state_dir).expect("install state dir"); - let pid_path = state_dir.join(format!("{INSTALL_STEM}.pid")); - let mut unrelated = std::process::Command::new("sleep") - .arg("30") - .spawn() - .expect("spawn unrelated process"); - - std::fs::write( - &pid_path, - format!("{}\nstale-install-token\n", unrelated.id()), - ) - .expect("stale pid marker"); - let poll = std::process::Command::new("bash") - .args(["-c", &install_poll_script(0)]) - .env("HOME", temp.path()) - .output() - .expect("poll stale installer"); - assert!(poll.status.success()); - assert!( - String::from_utf8_lossy(&poll.stdout).contains("running=0"), - "a reused PID must not be reported as the installer" - ); - assert!(!pid_path.exists(), "poll must clear the stale marker"); - - std::fs::write( - &pid_path, - format!("{}\nstale-install-token\n", unrelated.id()), - ) - .expect("restore stale pid marker"); - std::fs::write( - state_dir.join(format!("{INSTALL_STEM}.driver.pid")), - format!("{}\nstale-driver-token\n", unrelated.id()), - ) - .expect("stale driver pid marker"); - std::fs::write( - state_dir.join(format!("{INSTALL_STEM}.preparing")), - "stale-driver-token\n", - ) - .expect("stale prepare marker"); - let cancel = std::process::Command::new("bash") - .args(["-c", &install_cancel_script()]) - .env("HOME", temp.path()) - .output() - .expect("cancel stale installer"); - assert!(cancel.status.success()); - assert!( - unrelated - .try_wait() - .expect("inspect unrelated process") - .is_none(), - "cancellation must never signal a process that does not match the installer identity" - ); - assert!(!pid_path.exists(), "cancel must clear the stale marker"); - - unrelated.kill().expect("stop unrelated process"); - unrelated.wait().expect("reap unrelated process"); - } - - #[cfg(unix)] - #[test] - fn matching_installer_identity_is_cancelled() { - let temp = tempfile::tempdir().expect("temp dir"); - let state_dir = temp.path().join(install_state_relative_dir()); - std::fs::create_dir_all(&state_dir).expect("install state dir"); - let body_path = state_dir.join(format!("{INSTALL_STEM}-body.sh")); - std::fs::write(&body_path, "sleep 30\n").expect("installer body"); - let token = "openbitfun-install-test-token"; - let mut installer = std::process::Command::new("bash") - .arg(&body_path) - .arg(token) - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - .expect("spawn installer"); - std::fs::write( - state_dir.join(format!("{INSTALL_STEM}.pid")), - format!("{}\n{token}\n", installer.id()), - ) - .expect("installer pid marker"); - - let cancel = std::process::Command::new("bash") - .args(["-c", &install_cancel_script()]) - .env("HOME", temp.path()) - .output() - .expect("cancel installer"); - assert!(cancel.status.success()); - let stopped = installer - .try_wait() - .expect("inspect installer process") - .is_some(); - if !stopped { - installer.kill().expect("cleanup installer process"); - installer.wait().expect("reap installer process"); - } - assert!( - stopped, - "the exact PID/token/body identity must be cancelled" - ); - } - - #[cfg(unix)] - #[test] - fn cancelled_prepare_token_prevents_the_driver_from_spawning() { - let temp = tempfile::tempdir().expect("temp dir"); - let state_dir = temp.path().join(install_state_relative_dir()); - std::fs::create_dir_all(&state_dir).expect("install state dir"); - let body_path = state_dir.join(format!("{INSTALL_STEM}-body.sh")); - let sentinel = temp.path().join("installer-started"); - std::fs::write( - &body_path, - format!("touch {}\n", shell_quote_posix(&sentinel.to_string_lossy())), - ) - .expect("installer body"); - let token = "openbitfun-install-cancelled-before-driver"; - let driver = install_driver_script( - &state_dir.to_string_lossy(), - &body_path.to_string_lossy(), - token, - ); - - let output = std::process::Command::new("bash") - .args(["-c", &driver, "install-driver", token]) - .output() - .expect("run invalidated driver"); - assert_eq!(output.status.code(), Some(130)); - assert!( - !sentinel.exists(), - "a driver whose prepare token was removed must not start the body" - ); - assert!( - !state_dir - .join(format!("{INSTALL_STEM}.driver.pid")) - .exists(), - "the invalidated driver must clean its identity marker" - ); - } - #[cfg(unix)] #[test] fn dispatch_command_round_trips_quoted_paths_and_removes_request() { @@ -4020,19 +1275,6 @@ mod tests { assert!(!temp.path().join("should-not-run").exists()); } - #[test] - fn release_target_accepts_supported_unix_architectures() { - assert_eq!( - release_target("Linux", "amd64").unwrap(), - "x86_64-unknown-linux-gnu" - ); - assert_eq!( - release_target("Darwin", "arm64").unwrap(), - "aarch64-apple-darwin" - ); - assert!(release_target("Windows", "x86_64").is_err()); - } - #[test] fn probe_prefers_the_managed_cli_over_an_incompatible_path_copy() { let script = probe_remote_target_script(); @@ -4043,38 +1285,6 @@ mod tests { assert!(managed < path_lookup); } - #[test] - fn poll_metadata_split_accepts_lf_and_crlf() { - let (head, output) = split_metadata_output("running=1\n---\nhello\n"); - assert_eq!(head, "running=1\n"); - assert_eq!(output, "hello\n"); - let (head, output) = split_metadata_output("running=1\r\n---\r\nhello\r\n"); - assert_eq!(head, "running=1\r\n"); - assert_eq!(output, "hello\r\n"); - } - - #[test] - fn checksum_parser_used_by_dispatch_rejects_malformed_sidecars() { - assert!(crate::remote_ssh::release_verify::parse_sha256( - "not-a-checksum", - "archive.tar.gz" - ) - .is_err()); - } - - #[test] - fn streaming_archive_limit_is_enforced_before_appending_a_chunk() { - let mut archive = vec![1, 2, 3]; - extend_bounded_archive(&mut archive, &[4], 4).unwrap(); - assert_eq!(archive, vec![1, 2, 3, 4]); - assert!(extend_bounded_archive(&mut archive, &[5], 4).is_err()); - assert_eq!( - archive, - vec![1, 2, 3, 4], - "the over-limit chunk must never be buffered" - ); - } - #[test] fn model_config_sync_merges_only_the_ai_keys() { let payload = serde_json::json!({ @@ -4128,47 +1338,6 @@ mod tests { assert!(validate_model_config_payload(&serde_json::json!("models")).is_err()); } - #[test] - fn installation_is_bound_to_the_exact_confirmed_release() { - let confirmed = DispatchCliRelease { - version: "1.2.3".to_string(), - target: "aarch64-apple-darwin".to_string(), - url: "https://example.test/openbitfun.tar.gz".to_string(), - sha256: "a".repeat(64), - }; - ensure_confirmed_release(&confirmed, &confirmed).expect("exact asset"); - - let mut changed = confirmed.clone(); - changed.sha256 = "b".repeat(64); - assert!(ensure_confirmed_release(&changed, &confirmed).is_err()); - } - - #[test] - fn cli_install_failure_audit_details_are_structured_and_bounded() { - let details = cli_install_failure_details(&"p".repeat(700), &"e".repeat(700)); - - assert_eq!( - details - .get("phase") - .and_then(Value::as_str) - .expect("phase") - .chars() - .count(), - 500 - ); - assert_eq!( - details - .get("error") - .and_then(Value::as_str) - .expect("error") - .chars() - .count(), - 500 - ); - assert_eq!(details.get("output"), details.get("error")); - assert_eq!(details.as_object().expect("details").len(), 3); - } - #[test] fn incompatible_dispatch_protocols_require_an_upgrade() { let capabilities = REQUIRED_DISPATCH_CAPABILITIES.clone(); diff --git a/src/crates/services/services-integrations/src/remote_ssh/mod.rs b/src/crates/services/services-integrations/src/remote_ssh/mod.rs index f535e5ef06..b2a29d5d57 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/mod.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/mod.rs @@ -33,8 +33,6 @@ mod port_forward; #[cfg(feature = "remote-ssh-concrete")] mod proxy_command; #[cfg(feature = "remote-ssh-concrete")] -mod release_verify; -#[cfg(feature = "remote-ssh-concrete")] mod remote_exec; #[cfg(feature = "remote-ssh-concrete")] mod remote_exec_runtime_port; diff --git a/src/crates/services/services-integrations/src/remote_ssh/product_paths.rs b/src/crates/services/services-integrations/src/remote_ssh/product_paths.rs index 4db158153a..2dadc03cbf 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/product_paths.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/product_paths.rs @@ -38,10 +38,6 @@ pub(crate) fn product_data_path(base: &str, segments: &[&str]) -> String { } } -pub(crate) fn product_home_shell_path(segments: &[&str]) -> String { - format!("$HOME/{}", product_data_relative_path(segments)) -} - #[cfg(test)] mod tests { use super::*; @@ -49,12 +45,8 @@ mod tests { #[test] fn default_remote_paths_use_the_compiled_product_identity() { assert_eq!( - product_data_path("/home/user", &["dispatch", "install"]), - "/home/user/.openbitfun/dispatch/install" - ); - assert_eq!( - product_home_shell_path(&["relay-deploy", "relay.port"]), - "$HOME/.openbitfun/relay-deploy/relay.port" + product_data_path("/home/user", &["dispatch", "requests"]), + "/home/user/.openbitfun/dispatch/requests" ); } diff --git a/src/crates/services/services-integrations/src/remote_ssh/release_verify.rs b/src/crates/services/services-integrations/src/remote_ssh/release_verify.rs deleted file mode 100644 index 9a95bcca22..0000000000 --- a/src/crates/services/services-integrations/src/remote_ssh/release_verify.rs +++ /dev/null @@ -1,170 +0,0 @@ -//! Shared verification primitives for OpenBitFun release assets. -//! -//! Remote installers must use the same build-time trust root as the CLI -//! self-updater. A SHA256 sidecar detects corruption, while the minisign -//! signature establishes who published that checksum or archive. - -use anyhow::{anyhow, Context, Result}; -use sha2::{Digest, Sha256}; - -/// Ed25519 (minisign) public key injected into official builds from the same -/// `TAURI_UPDATER_PUBKEY` used by the Desktop and CLI updaters. -/// -/// Forks that publish their own releases set this at build time to their own -/// key. When absent, [`OFFICIAL_RELEASE_PUBKEY`] applies. -pub(crate) const RELEASE_PUBKEY: Option<&str> = option_env!("OPENBITFUN_RELEASE_PUBKEY"); - -/// The official OpenBitFun release public key (minisign key ID `50F47CBE6CC0A376`), -/// base64-wrapped the way Tauri wraps `minisign.pub`. This is public data — -/// every release publishes it as the `minisign.pub` asset — so compiling it in -/// lets development builds verify and install official releases instead of -/// failing closed with no trust root. Downloads still come only from the -/// pinned official repository, so trusting the matching official key here does -/// not widen what a build will execute. -pub(crate) const OFFICIAL_RELEASE_PUBKEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDUwRjQ3Q0JFNkNDMEEzNzYKUldSMm84QnN2bnowVU9CYzNOb1RWVzA2d2RpR003cExQM0xwaUw0QTNTcDRueGtCc1dsSlJUeG4K"; - -pub(crate) fn release_pubkey() -> Option<&'static str> { - RELEASE_PUBKEY - .filter(|key| !key.trim().is_empty()) - .or(Some(OFFICIAL_RELEASE_PUBKEY)) -} - -pub(crate) fn require_release_pubkey() -> Result<&'static str> { - release_pubkey().ok_or_else(|| { - anyhow!( - "this build has no OpenBitFun release signing key; refusing to install executable code" - ) - }) -} - -pub(crate) fn release_tag_for_version(version: &str) -> String { - if version.contains("-nightly.") { - "nightly".to_string() - } else { - format!("v{}", version.split('+').next().unwrap_or(version)) - } -} - -/// Parse the first digest from a conventional ` ` SHA256 -/// sidecar. The filename is diagnostic only; release sidecars may use either -/// one or two spaces before it. -pub(crate) fn parse_sha256(checksum_text: &str, filename: &str) -> Result { - checksum_text - .split_whitespace() - .next() - .filter(|value| value.len() == 64 && value.chars().all(|c| c.is_ascii_hexdigit())) - .map(str::to_ascii_lowercase) - .ok_or_else(|| anyhow!("invalid SHA256 file for {filename}")) -} - -pub(crate) fn verify_sha256(data: &[u8], expected: &str, filename: &str) -> Result<()> { - let expected = expected.trim(); - if expected.len() != 64 || !expected.chars().all(|c| c.is_ascii_hexdigit()) { - return Err(anyhow!("invalid expected SHA256 for {filename}")); - } - let actual = format!("{:x}", Sha256::digest(data)); - if !actual.eq_ignore_ascii_case(expected) { - return Err(anyhow!("SHA256 mismatch for {filename}")); - } - Ok(()) -} - -/// Verify a Tauri-format `.sig` (base64 of a complete minisign signature file). -/// The public key may be the raw minisign file accepted by current Tauri CLIs -/// or the legacy base64 wrapper stored by older release configurations. -pub(crate) fn verify_minisign(data: &[u8], signature_b64: &str, pubkey: &str) -> Result<()> { - use base64::Engine as _; - - let public_key = minisign_verify::PublicKey::decode(&decode_public_key(pubkey)?) - .map_err(|error| anyhow!("invalid release public key: {error}"))?; - let signature_bytes = base64::engine::general_purpose::STANDARD - .decode(signature_b64.trim().as_bytes()) - .context("decode release signature")?; - let signature_text = - String::from_utf8(signature_bytes).context("decode release signature as UTF-8")?; - let signature = minisign_verify::Signature::decode(&signature_text) - .map_err(|error| anyhow!("invalid release signature: {error}"))?; - public_key - .verify(data, &signature, false) - .map_err(|error| anyhow!("release signature does not match the signed data: {error}")) -} - -fn decode_public_key(value: &str) -> Result { - use base64::Engine as _; - - let value = value.trim(); - if value.starts_with("untrusted comment:") { - return Ok(value.to_owned()); - } - let bytes = base64::engine::general_purpose::STANDARD - .decode(value.as_bytes()) - .context("decode release public key")?; - String::from_utf8(bytes).context("decode release public key as UTF-8") -} - -/// Verify the minisign signature over a checksum sidecar, then return its -/// normalized digest. This is useful when the eventual target host has only a -/// SHA256 implementation and no copy of the OpenBitFun trust root. -pub(crate) fn verify_signed_checksum( - checksum_text: &str, - signature_b64: &str, - pubkey_b64: &str, - filename: &str, -) -> Result { - verify_minisign(checksum_text.as_bytes(), signature_b64, pubkey_b64)?; - parse_sha256(checksum_text, filename) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Fixture produced with the Tauri signer CLI in its base64-wrapped - /// minisign wire format. - const FIXTURE_PUBKEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IERENTQzQUM5RUY0NTIzRTMKUldUakkwWHZ5VHBVM1NOMXJWMHhLVlljSDBOY2x4YlpxVHA2clN1NEJPMWcyY2Qvd2U4VUR2b3AK"; - const FIXTURE_SIGNATURE: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUakkwWHZ5VHBVM2RVVFdoR3FNZDltSWNUeEQ1K2ZnNWRUSnYxWk5lUkZzd0h0MkdzSUhUSlV6a0haUTdNZm1aemM5QVBQWW50UWgvaWpFcEp1Zkp4SERWdnhIc1g2YUFrPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg4NDg2NTU4CWZpbGU6Lm9wZW5iaXRmdW4tbWluaXNpZ24tZml4dHVyZS50eHQKa1QxdDQ3bWtLVlhaZUdFSjR4R0V5R1Z3REVnUlI0RGJqbHFoZkVHdkdLSlFyTGJ5Z05JRTI5V3dwdXRkSFpZckUrK0RaUVVJYUJod1dzcmVydHZnQXc9PQo="; - const FIXTURE_DATA: &[u8] = b"hello-openbitfun\n"; - - #[test] - fn embedded_trust_root_is_always_available_and_well_formed() { - let pubkey = require_release_pubkey().expect("every build carries a trust root"); - let text = decode_public_key(pubkey).expect("trust root has a supported key format"); - minisign_verify::PublicKey::decode(&text).expect("trust root is a minisign public key"); - } - - #[test] - fn minisign_wire_format_accepts_authentic_data_and_rejects_tampering() { - verify_minisign(FIXTURE_DATA, FIXTURE_SIGNATURE, FIXTURE_PUBKEY) - .expect("fixture signature must verify"); - let raw_pubkey = decode_public_key(FIXTURE_PUBKEY).expect("decode fixture public key"); - verify_minisign(FIXTURE_DATA, FIXTURE_SIGNATURE, &raw_pubkey) - .expect("raw minisign public key must verify"); - assert!(verify_minisign(b"tampered\n", FIXTURE_SIGNATURE, FIXTURE_PUBKEY).is_err()); - assert!(verify_minisign(FIXTURE_DATA, "bm90LWEtc2ln", FIXTURE_PUBKEY).is_err()); - } - - #[test] - fn sha256_sidecar_requires_a_well_formed_digest_and_matching_bytes() { - let digest = format!("{:x}", Sha256::digest(FIXTURE_DATA)); - assert_eq!( - parse_sha256( - &format!("{digest} openbitfun-cli.tar.gz\n"), - "openbitfun-cli.tar.gz" - ) - .unwrap(), - digest - ); - verify_sha256(FIXTURE_DATA, &digest, "openbitfun-cli.tar.gz").unwrap(); - assert!(verify_sha256(FIXTURE_DATA, &"0".repeat(64), "openbitfun-cli.tar.gz").is_err()); - assert!(parse_sha256("not-a-digest", "openbitfun-cli.tar.gz").is_err()); - } - - #[test] - fn release_tags_keep_stable_and_nightly_channels() { - assert_eq!(release_tag_for_version("0.2.13"), "v0.2.13"); - assert_eq!( - release_tag_for_version("0.2.14-nightly.20260724+abc123"), - "nightly" - ); - } -} diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index da4bf3ecb1..a584b23811 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -6399,13 +6399,13 @@ "background host" ], "highlightsZh": [ - "一键列出同账号在线设备与已保存 SSH 主机作为派发目标", + "可选择已配置的 SSH 主机派发任务,智能体也可派发到同账号设备", "提交后控制端可随时断网或休眠,目标机在独立 Git Worktree 自治执行", "断线重连后按游标增量回填完整对话与工具轨迹,支持远程回答权限请求", "任务完成后可将目标端改动安全同步回本机,绝不把本机当成脆弱的文件代理" ], "highlightsEn": [ - "Discover same-account devices and saved SSH hosts as ready-to-run targets", + "Dispatch to a configured SSH host, or ask the Agent to dispatch to a same-account device", "Disconnect or close your laptop freely while the target works in an isolated Git worktree", "Replay missed events incrementally by cursor on reconnect and answer pending permissions remotely", "Sync completed changes back cleanly without turning your controller into a fragile file proxy" @@ -6430,25 +6430,6 @@ "command:account_list_devices" ] }, - { - "id": "provision", - "titleZh": "为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境", - "titleEn": "Provision the target host and install or update the OpenBitFun CLI", - "descriptionZh": "首次向全新的 SSH 服务器派发时,可在向导中一键检测并在远端部署匹配的 CLI 执行端,省去手工登录装环境。", - "descriptionEn": "Preparing a fresh SSH server? Detect its environment and install or update the matching OpenBitFun CLI right from the setup flow.", - "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "「为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境」涉及远端安装进度轮询、网络下载与中途取消控制;智能体会打开目标配置界面,由你确认并观察安装完成。", - "reasonEn": "\"Provision the target host and install or update the OpenBitFun CLI\" involves live remote installation polling and cancellation controls; the Agent opens the target provisioning flow so you can confirm and monitor setup." - }, - "evidence": [ - "command:dispatch_provision_target", - "command:dispatch_install_cli_start", - "command:dispatch_install_cli_poll", - "command:dispatch_install_cli_cancel" - ] - }, { "id": "model-sync", "titleZh": "在派发前按需将任务所选的模型配置同步给目标主机", @@ -6572,15 +6553,15 @@ } ], "stepsZh": [ - "确保目标机器已登录同一账号在线,或已在本地保存好可用的 SSH 连接配置", - "在当前 Git 项目的聊天输入框底部点击「本机」芯片打开「这个任务在哪运行」菜单(或直接对智能体说明要派发到哪台设备),选定目标与权限审批策略", - "发送任务提示词;目标主机会自动准备环境、同步所需模型配置并在独立 Git Worktree 中启动执行", + "先在 SSH 目标上安装兼容的 OpenBitFun CLI,并保存 SSH 连接。", + "在聊天输入框底部点击「本机」,选择 SSH 主机。要派发到同账号设备时,直接告诉智能体目标设备和任务。", + "发送任务后,目标主机会同步所需的模型配置,并在独立的 Git worktree 中执行任务。", "执行期间可随时离线;重新打开会话即可查看最新进度、批复等待中的权限,完成后一键将结果同步回本机工作区" ], "stepsEn": [ - "Make sure your target device is signed in to the same account and online, or save an SSH connection profile first", - "Click the \"This computer\" chip at the bottom of the chat input to open the \"Where this task runs\" menu (or ask the agent explicitly to dispatch to a named device), and pick your target and approval policy", - "Submit your prompt; the target provisions its runtime if needed, syncs model settings, and starts working in a dedicated Git worktree", + "Install a compatible OpenBitFun CLI on the SSH target and save its SSH connection.", + "Select an SSH host from the This computer menu in the composer. To use a same-account device, ask the Agent to dispatch your task to that device.", + "Submit the task. The target syncs the required model configuration and runs the job in a dedicated Git worktree.", "Disconnect anytime; reopen the session later to catch up on streamed events, approve pending permissions, or sync finished changes back locally" ], "agentExamplesZh": [ 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 14366fee78..237a79e7bc 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": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", + "digest": "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c", "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { @@ -187,11 +187,11 @@ "features": 24, "settings": 23, "userFacing": 47, - "documentedItems": 369, + "documentedItems": 368, "controlCoverage": { "direct": 64, "delegated": 74, - "interactive": 231, + "interactive": 230, "unsupported": 0 } }, @@ -10247,7 +10247,6 @@ "capabilityId": "feature.detached-dispatch", "itemIds": [ "targets", - "provision", "model-sync", "submit", "status-list", @@ -10635,55 +10634,6 @@ } } }, - { - "id": "feature.detached-dispatch:open:provision", - "capabilityId": "feature.detached-dispatch", - "itemIds": [ - "provision" - ], - "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": "event", - "eventName": "openbitfun:open-remote-connect", - "detail": { - "group": "account" - } - } - }, { "id": "feature.detached-dispatch:open:model-sync", "capabilityId": "feature.detached-dispatch", @@ -28064,13 +28014,13 @@ "background host" ], "highlightsZh": [ - "一键列出同账号在线设备与已保存 SSH 主机作为派发目标", + "可选择已配置的 SSH 主机派发任务,智能体也可派发到同账号设备", "提交后控制端可随时断网或休眠,目标机在独立 Git Worktree 自治执行", "断线重连后按游标增量回填完整对话与工具轨迹,支持远程回答权限请求", "任务完成后可将目标端改动安全同步回本机,绝不把本机当成脆弱的文件代理" ], "highlightsEn": [ - "Discover same-account devices and saved SSH hosts as ready-to-run targets", + "Dispatch to a configured SSH host, or ask the Agent to dispatch to a same-account device", "Disconnect or close your laptop freely while the target works in an isolated Git worktree", "Replay missed events incrementally by cursor on reconnect and answer pending permissions remotely", "Sync completed changes back cleanly without turning your controller into a fragile file proxy" @@ -28088,17 +28038,6 @@ "options": [] } }, - { - "id": "provision", - "titleZh": "为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境", - "titleEn": "Provision the target host and install or update the OpenBitFun CLI", - "control": { - "kind": "open", - "reasonCode": "unstructuredInteraction", - "reasonZh": "「为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境」涉及远端安装进度轮询、网络下载与中途取消控制;智能体会打开目标配置界面,由你确认并观察安装完成。", - "reasonEn": "\"Provision the target host and install or update the OpenBitFun CLI\" involves live remote installation polling and cancellation controls; the Agent opens the target provisioning flow so you can confirm and monitor setup." - } - }, { "id": "model-sync", "titleZh": "在派发前按需将任务所选的模型配置同步给目标主机", @@ -28182,15 +28121,15 @@ } ], "stepsZh": [ - "确保目标机器已登录同一账号在线,或已在本地保存好可用的 SSH 连接配置", - "在当前 Git 项目的聊天输入框底部点击「本机」芯片打开「这个任务在哪运行」菜单(或直接对智能体说明要派发到哪台设备),选定目标与权限审批策略", - "发送任务提示词;目标主机会自动准备环境、同步所需模型配置并在独立 Git Worktree 中启动执行", + "先在 SSH 目标上安装兼容的 OpenBitFun CLI,并保存 SSH 连接。", + "在聊天输入框底部点击「本机」,选择 SSH 主机。要派发到同账号设备时,直接告诉智能体目标设备和任务。", + "发送任务后,目标主机会同步所需的模型配置,并在独立的 Git worktree 中执行任务。", "执行期间可随时离线;重新打开会话即可查看最新进度、批复等待中的权限,完成后一键将结果同步回本机工作区" ], "stepsEn": [ - "Make sure your target device is signed in to the same account and online, or save an SSH connection profile first", - "Click the \"This computer\" chip at the bottom of the chat input to open the \"Where this task runs\" menu (or ask the agent explicitly to dispatch to a named device), and pick your target and approval policy", - "Submit your prompt; the target provisions its runtime if needed, syncs model settings, and starts working in a dedicated Git worktree", + "Install a compatible OpenBitFun CLI on the SSH target and save its SSH connection.", + "Select an SSH host from the This computer menu in the composer. To use a same-account device, ask the Agent to dispatch your task to that device.", + "Submit the task. The target syncs the required model configuration and runs the job in a dedicated Git worktree.", "Disconnect anytime; reopen the session later to catch up on streamed events, approve pending permissions, or sync finished changes back locally" ], "agentExamplesZh": [ @@ -28382,18 +28321,16 @@ "target host", "offline job", "background host", - "一键列出同账号在线设备与已保存 SSH 主机作为派发目标", + "可选择已配置的 SSH 主机派发任务,智能体也可派发到同账号设备", "提交后控制端可随时断网或休眠,目标机在独立 Git Worktree 自治执行", "断线重连后按游标增量回填完整对话与工具轨迹,支持远程回答权限请求", "任务完成后可将目标端改动安全同步回本机,绝不把本机当成脆弱的文件代理", - "Discover same-account devices and saved SSH hosts as ready-to-run targets", + "Dispatch to a configured SSH host, or ask the Agent to dispatch to a same-account device", "Disconnect or close your laptop freely while the target works in an isolated Git worktree", "Replay missed events incrementally by cursor on reconnect and answer pending permissions remotely", "Sync completed changes back cleanly without turning your controller into a fragile file proxy", "列出同账号下的所有设备与本机已保存的 SSH 目标", "List same-account devices and saved SSH dispatch targets", - "为目标主机自动检测、安装或更新 OpenBitFun CLI 运行环境", - "Provision the target host and install or update the OpenBitFun CLI", "在派发前按需将任务所选的模型配置同步给目标主机", "Sync required model configuration to the target before job submission", "从当前 Git 工作区向设备或 SSH 目标提交可离线运行的持久任务", diff --git a/src/web-ui/src/features/dispatch/DispatchInstallDialog.tsx b/src/web-ui/src/features/dispatch/DispatchInstallDialog.tsx deleted file mode 100644 index dd2e2bc3c4..0000000000 --- a/src/web-ui/src/features/dispatch/DispatchInstallDialog.tsx +++ /dev/null @@ -1,678 +0,0 @@ -import { useDeviceDirectory, resolveDeviceName } from '@/infrastructure/account/deviceDirectory'; -import { - Alert, - Button, - Checkbox, - Icon, - Input, - Dialog, - DialogBody, - DialogClose, - DialogDescription, - DialogFooter, - DialogHeader, - DialogHeading, - DialogTitle, - Disclosure, -} from '@openbitfun/ui'; -import React, { useCallback, useEffect, useRef, useState } from 'react'; -import { useI18n } from '@/infrastructure/i18n'; -import { createLogger } from '@/shared/utils/logger'; -import { Loader2 } from 'lucide-react'; -import { dispatchApi } from './dispatchApi'; -import type { - DispatchSelection, - DispatchSshProbe, - DispatchTargetOption, -} from './types'; -import { - BASE_DISPATCH_CAPABILITIES, - DISPATCH_PROTOCOL_VERSION, -} from './dispatchPreflight'; -import { configAPI } from '@/infrastructure/api/service-api/ConfigAPI'; -import { gitAPI } from '@/infrastructure/api/service-api/GitAPI'; -import type { WorktreeSettings } from '@/infrastructure/api/service-api/WorktreeAPI'; -import './DispatchInstallDialog.scss'; - -const log = createLogger('DispatchInstallDialog'); -const DIALOG_TITLE_ID = 'dispatch-install-dialog-title'; -type TargetPreparationPhase = 'installing' | 'provisioning' | 'cancelling'; - - -interface DispatchInstallDialogProps { - open: boolean; - target: DispatchTargetOption | null; - sourceWorkspacePath?: string; - sourceWorkspaceId?: string; - onClose: () => void; - onReady: (selection: DispatchSelection) => void; -} - -export const DispatchInstallDialog: React.FC = ({ - open, - target, - sourceWorkspacePath, - sourceWorkspaceId, - onClose, - onReady, -}) => { - useDeviceDirectory(); - const { t } = useI18n('common'); - const [includeUncommitted, setIncludeUncommitted] = useState(false); - const [baseRef, setBaseRef] = useState('HEAD'); - const [baseRefError, setBaseRefError] = useState(null); - const [validatingBaseRef, setValidatingBaseRef] = useState(false); - const [worktreeSettingsLoading, setWorktreeSettingsLoading] = useState(true); - const [probe, setProbe] = useState(null); - const [probing, setProbing] = useState(false); - const [probeError, setProbeError] = useState(false); - const [preparationPhase, setPreparationPhase] = useState(null); - const [preparationOutcome, setPreparationOutcome] = useState<'synced' | 'cli-only' | null>(null); - const [provisionRetryAvailable, setProvisionRetryAvailable] = useState(false); - const [error, setError] = useState(null); - const generationRef = useRef(0); - const installActiveRef = useRef(false); - const includeUncommittedTouchedRef = useRef(false); - - const connectionId = target?.connectionId?.trim() ?? ''; - const deviceId = target?.deviceId?.trim() ?? ''; - const targetId = target?.kind === 'device' ? deviceId : connectionId; - - const runProbe = useCallback(async () => { - if (!targetId || !target || target.kind === 'local') return; - // The target's own directories are irrelevant now: dispatch checks out its - // own worktree there, so the probe only reports CLI and model readiness. - const path = ''; - const generation = ++generationRef.current; - setProbing(true); - setProbeError(false); - try { - const result = await dispatchApi.probeTarget( - target.kind === 'device' - ? { kind: 'device', deviceId: targetId, workspacePath: path } - : { kind: 'ssh', connectionId: targetId, workspacePath: path }, - ); - if (generation === generationRef.current) { - setProbe(result); - } - } catch (nextError) { - if (generation === generationRef.current) { - setProbe(null); - setProbeError(true); - log.warn('Failed to check dispatch target readiness', { - targetKind: target.kind, - targetId, - error: nextError, - }); - } - } finally { - if (generation === generationRef.current) { - setProbing(false); - } - } - }, [target, targetId]); - - useEffect(() => { - if (!open || !targetId) return; - includeUncommittedTouchedRef.current = false; - setIncludeUncommitted(false); - setBaseRef('HEAD'); - setBaseRefError(null); - setValidatingBaseRef(false); - setWorktreeSettingsLoading(true); - setProbe(null); - setProbeError(false); - setPreparationPhase(null); - setPreparationOutcome(null); - setProvisionRetryAvailable(false); - installActiveRef.current = false; - setError(null); - void runProbe(); - }, [open, runProbe, targetId]); - - // Dispatch uses the same baseline creation path as the regular worktree - // control, so its initial copy-local-changes choice follows that setting. - useEffect(() => { - if (!open) return; - let cancelled = false; - setWorktreeSettingsLoading(true); - void configAPI.getConfig('app.worktrees', { skipRetryOnNotFound: true }) - .then(settings => { - if (!cancelled && !includeUncommittedTouchedRef.current) { - const configured = settings as Partial | undefined; - setIncludeUncommitted(configured?.copyLocalChanges === true); - } - }) - .catch(nextError => { - log.warn('Failed to read worktree settings for dispatch', { - error: nextError, - }); - if (!cancelled && !includeUncommittedTouchedRef.current) { - setIncludeUncommitted(false); - } - }) - .finally(() => { - if (!cancelled) setWorktreeSettingsLoading(false); - }); - return () => { - cancelled = true; - }; - }, [open, targetId]); - - // Retires every in-flight probe, model sync, and revision check, so a result - // that lands after the dialog moved on cannot write to a closed dialog. - const invalidatePendingWork = useCallback(() => { - generationRef.current += 1; - }, []); - - useEffect(() => { - if (!open || !targetId) return; - return () => { - invalidatePendingWork(); - if (installActiveRef.current && connectionId) { - void dispatchApi.installCliCancel(connectionId).catch(nextError => { - log.warn('Failed to cancel target preparation during dialog cleanup', { - connectionId, - error: nextError, - }); - }); - } - }; - }, [connectionId, invalidatePendingWork, open, targetId]); - - const prepareTarget = useCallback(async () => { - if (!connectionId || !probe?.release || preparationPhase) return; - const generation = ++generationRef.current; - setPreparationPhase('installing'); - setPreparationOutcome(null); - setProvisionRetryAvailable(false); - setError(null); - let installStarted = false; - let installCompleted = false; - try { - await dispatchApi.installCliStart(connectionId, probe.release); - installStarted = true; - installActiveRef.current = true; - let cursor = 0; - for (;;) { - if (generation !== generationRef.current) return; - const poll = await dispatchApi.installCliPoll(connectionId, cursor); - cursor = poll.cursor; - if (poll.status === 'succeeded') break; - if (poll.status === 'failed') { - // Carry the installer's own tail into the error: without it the only - // record of the failure is a generic message, and the remote state - // that would explain it is cleaned up before anyone can look. - const detail = poll.output.trim(); - throw new Error( - detail - ? `Target CLI installation failed: ${detail}` - : 'Target CLI installation failed with no installer output', - ); - } - await new Promise(resolve => globalThis.setTimeout(resolve, 750)); - } - installCompleted = true; - installActiveRef.current = false; - if (generation !== generationRef.current) return; - setPreparationPhase('provisioning'); - const result = await dispatchApi.provisionTarget(connectionId); - if (generation !== generationRef.current) return; - setPreparationOutcome( - result.accountStatus === 'synced' && result.daemonInstalled ? 'synced' : 'cli-only', - ); - setProvisionRetryAvailable(false); - } catch (nextError) { - installActiveRef.current = false; - if (generation !== generationRef.current) return; - setProvisionRetryAvailable(installCompleted); - setError(t('dispatch.prepareFailed')); - log.warn('Failed to prepare SSH dispatch target', { - connectionId, - installStarted, - error: nextError, - }); - } finally { - if (generation === generationRef.current) { - setPreparationPhase(null); - await runProbe(); - } - } - }, [connectionId, preparationPhase, probe?.release, runProbe, t]); - - const retryProvisioning = useCallback(async () => { - if (!connectionId || preparationPhase) return; - const generation = ++generationRef.current; - setPreparationPhase('provisioning'); - setPreparationOutcome(null); - setProvisionRetryAvailable(false); - setError(null); - try { - const result = await dispatchApi.provisionTarget(connectionId); - if (generation !== generationRef.current) return; - setPreparationOutcome( - result.accountStatus === 'synced' && result.daemonInstalled ? 'synced' : 'cli-only', - ); - } catch (nextError) { - if (generation !== generationRef.current) return; - setProvisionRetryAvailable(true); - setError(t('dispatch.prepareFailed')); - log.warn('Failed to retry SSH target account provisioning', { - connectionId, - error: nextError, - }); - } finally { - if (generation === generationRef.current) { - setPreparationPhase(null); - await runProbe(); - } - } - }, [connectionId, preparationPhase, runProbe, t]); - - const cancelPreparation = useCallback(async () => { - if (!connectionId || preparationPhase !== 'installing') return; - ++generationRef.current; - setPreparationPhase('cancelling'); - try { - await dispatchApi.installCliCancel(connectionId); - setError(t('dispatch.prepareCancelled')); - } catch (nextError) { - setError(t('dispatch.prepareCancelFailed')); - log.warn('Failed to cancel SSH target preparation', { - connectionId, - error: nextError, - }); - } finally { - installActiveRef.current = false; - setPreparationPhase(null); - await runProbe(); - } - }, [connectionId, preparationPhase, runProbe, t]); - - const closeDialog = useCallback(() => { - if (preparationPhase) return; - invalidatePendingWork(); - onClose(); - }, [invalidatePendingWork, onClose, preparationPhase]); - - const handleModalClose = useCallback(() => { - // Keep Escape, the close button, and backdrop clicks from silently - // abandoning a target mutation that is already under way. - if (preparationPhase) return; - closeDialog(); - }, [closeDialog, preparationPhase]); - - const protocol = probe?.protocol; - const requiredCapabilities = [...BASE_DISPATCH_CAPABILITIES]; - const missingCapabilities = protocol - ? requiredCapabilities.filter(capability => !protocol.capabilities.includes(capability)) - : requiredCapabilities; - const protocolCompatible = - protocol?.protocolVersion === DISPATCH_PROTOCOL_VERSION && - missingCapabilities.length === 0; - const cliReady = - !!probe?.cliInstalled && - !!protocol && - !probe.protocolError && - protocolCompatible; - // The source workspace is owned by ID; the path only labels its checkout. - const workspaceReady = !!sourceWorkspaceId?.trim() || !!sourceWorkspacePath?.trim(); - /** A compatible signed release makes one-click preparation available. */ - const installPending = - !cliReady - && target?.kind === 'ssh' - && !!probe?.installSupported - && !probe?.prebuiltIncompatible; - /** - * The published binary is the only way a target gets a CLI. When none fits, - * say so here rather than letting submit fail on an unusable target. - */ - const installUnavailable = !cliReady && target?.kind === 'ssh' && !!probe && !installPending; - /** - * Model readiness is deliberately absent: the model is chosen in the - * composer like any local session, and submission pushes this device's model - * configuration to a target that cannot serve the choice. Gating here would - * ask the user to solve a problem the backend already solves. - */ - const ready = workspaceReady && cliReady; - const targetMutationInProgress = preparationPhase !== null; - - const confirmTarget = async () => { - if ( - !target - || target.kind === 'local' - || !targetId - || !ready - ) return; - const normalizedSourcePath = sourceWorkspacePath?.trim() || ''; - const normalizedBaseRef = baseRef.trim() || 'HEAD'; - const generation = generationRef.current; - setValidatingBaseRef(true); - setBaseRefError(null); - try { - await gitAPI.resolveRevision({ workspaceId: sourceWorkspaceId ?? '', repositoryPath: normalizedSourcePath }, normalizedBaseRef); - } catch (nextError) { - if (generation === generationRef.current) { - log.warn('Failed to resolve dispatch base revision', { - repositoryPath: normalizedSourcePath, - revision: normalizedBaseRef, - error: nextError, - }); - setBaseRefError(t('dispatch.baseRefInvalid', { ref: normalizedBaseRef })); - } - return; - } finally { - if (generation === generationRef.current) { - setValidatingBaseRef(false); - } - } - if (generation !== generationRef.current) return; - // The target chooses where its worktree lands, so nothing is sent here. - const normalizedPath = ''; - const request = target.kind === 'device' - ? { - kind: 'device' as const, - deviceId: targetId, - workspacePath: normalizedPath, - } - : { - kind: 'ssh' as const, - connectionId: targetId, - workspacePath: normalizedPath, - }; - onReady({ - request, - target: { - ...request, - workspacePath: normalizedPath, - displayName: target.displayName, - }, - includeUncommitted, - baseRef: normalizedBaseRef, - modelCatalog: protocol?.modelCatalog, - availableModels: protocol?.availableModels, - defaultModel: protocol?.defaultModel, - }); - }; - - return ( - { if (!nextOpen) handleModalClose(); }} - size="md" - closeOnPointerOutside={!targetMutationInProgress} - aria-labelledby={DIALOG_TITLE_ID} - data-testid="dispatch-install-dialog" - > -
- - - - {t('dispatch.configureTitle', { target: target?.kind === 'device' && target.deviceId ? resolveDeviceName(target.deviceId, target.displayName) : target?.displayName ?? '' })} - - {t('dispatch.configureSubtitle')} - - {!targetMutationInProgress && } - - - - {error ? ( - setError(null)} /> - ) : null} - {preparationOutcome ? ( - - ) : null} - {baseRefError ? ( - setBaseRefError(null)} - /> - ) : null} - -
-

- {t('dispatch.readinessTitle')} -

- {probing || (!probe && !probeError) ? ( -
- - {t('dispatch.checkingTarget')} -
- ) : null} - {probeError ? ( -
- - {t('dispatch.probeFailed')} - - -
- ) : null} - {probe ? ( -
-
- {t('dispatch.cliStatus')} - - {preparationPhase === 'installing' - ? t('dispatch.installingCli') - : preparationPhase === 'provisioning' - ? t('dispatch.provisioningDaemon') - : preparationPhase === 'cancelling' - ? t('dispatch.cancellingPreparation') - : cliReady - ? t('dispatch.cliReady', { version: protocol?.cliVersion }) - : installPending - ? t('dispatch.cliCanDeploy') - : probe.cliInstalled - ? t('dispatch.cliUpdateRequired') - : t('dispatch.cliUnavailable')} - -
-
- ) : null} - {installPending && probe?.release ? ( - <> -
- - {t('dispatch.oneClickDeployDescription')} - - -
- -
-
{t('dispatch.version')}
{probe.release.version}
-
{t('dispatch.downloadUrl')}
{probe.release.url}
-
{t('dispatch.integrity')}
{probe.release.sha256}
-
-
- - ) : null} - {installUnavailable ? ( - - ) : null} - {cliReady && provisionRetryAvailable ? ( -
- - {t('dispatch.retryProvisionDescription')} - - -
- ) : null} - {target?.kind === 'device' && probe && !cliReady ? ( -
- - {t('dispatch.deviceUpdateRequired')} - - -
- ) : null} -
- -
-

- {t('dispatch.deliveryTitle')} -

-
- - {t('dispatch.baselineSource')} - - {sourceWorkspacePath} -
- - {t('dispatch.baselineDescription')} - - - { - includeUncommittedTouchedRef.current = true; - setIncludeUncommitted(checked); - }} - label={t('dispatch.includeUncommitted')} - description={t('dispatch.includeUncommittedHint')} - /> -
-
- -
- - - - -
-
-
- ); -}; diff --git a/src/web-ui/src/features/dispatch/DispatchInstallDialog.scss b/src/web-ui/src/features/dispatch/DispatchTargetDialog.scss similarity index 88% rename from src/web-ui/src/features/dispatch/DispatchInstallDialog.scss rename to src/web-ui/src/features/dispatch/DispatchTargetDialog.scss index b6693c3061..52109ef07d 100644 --- a/src/web-ui/src/features/dispatch/DispatchInstallDialog.scss +++ b/src/web-ui/src/features/dispatch/DispatchTargetDialog.scss @@ -156,36 +156,6 @@ } } - &__details { - width: 100%; - color: var(--openbitfun-color-content-secondary); - font-size: var(--openbitfun-type-label-sm-font-size); - - dl { - display: grid; - gap: var(--openbitfun-space-1); - width: 100%; - margin: 0; - } - - dl > div { - display: grid; - grid-template-columns: 84px minmax(0, 1fr); - gap: var(--openbitfun-space-2); - } - - dt { - color: var(--openbitfun-color-content-muted); - } - - dd { - min-width: 0; - margin: 0; - overflow-wrap: anywhere; - font-family:var(--openbitfun-type-code-md-font-family); - } - } - &__actions { flex-shrink: 0; } diff --git a/src/web-ui/src/features/dispatch/DispatchInstallDialog.test.tsx b/src/web-ui/src/features/dispatch/DispatchTargetDialog.test.tsx similarity index 66% rename from src/web-ui/src/features/dispatch/DispatchInstallDialog.test.tsx rename to src/web-ui/src/features/dispatch/DispatchTargetDialog.test.tsx index d82bf88d3e..7f8c3e763f 100644 --- a/src/web-ui/src/features/dispatch/DispatchInstallDialog.test.tsx +++ b/src/web-ui/src/features/dispatch/DispatchTargetDialog.test.tsx @@ -8,7 +8,7 @@ import { import React, { act } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { DispatchInstallDialog } from './DispatchInstallDialog'; +import { DispatchTargetDialog } from './DispatchTargetDialog'; globalThis.IS_REACT_ACT_ENVIRONMENT = true; @@ -26,10 +26,6 @@ const READY_CAPABILITIES = [ const mocks = vi.hoisted(() => ({ probeTarget: vi.fn(), - installCliStart: vi.fn(), - installCliPoll: vi.fn(), - installCliCancel: vi.fn(), - provisionTarget: vi.fn(), getFreshConfig: vi.fn(), resolveRevision: vi.fn(), dialogOnOpenChange: null as ((open: boolean) => void) | null, @@ -42,10 +38,6 @@ const mocks = vi.hoisted(() => ({ vi.mock('./dispatchApi', () => ({ dispatchApi: { probeTarget: mocks.probeTarget, - installCliStart: mocks.installCliStart, - installCliPoll: mocks.installCliPoll, - installCliCancel: mocks.installCliCancel, - provisionTarget: mocks.provisionTarget, }, })); @@ -148,7 +140,7 @@ function createDeferred() { return { promise, reject, resolve }; } -describe('DispatchInstallDialog target preparation', () => { +describe('DispatchTargetDialog target preparation', () => { let container: HTMLDivElement; let root: Root; @@ -168,23 +160,6 @@ describe('DispatchInstallDialog target preparation', () => { sha256: 'abc123', }, }); - mocks.installCliStart.mockResolvedValue({ - scriptPath: '/tmp/install.sh', - version: '1.2.3', - target: 'x86_64-unknown-linux-gnu', - url: 'https://example.test/openbitfun', - sha256: 'abc123', - }); - mocks.installCliPoll.mockResolvedValue({ - cursor: 1, - output: '', - status: 'succeeded', - }); - mocks.installCliCancel.mockResolvedValue(undefined); - mocks.provisionTarget.mockResolvedValue({ - accountStatus: 'skipped_not_logged_in', - daemonInstalled: false, - }); mocks.getFreshConfig.mockResolvedValue(undefined); mocks.resolveRevision.mockResolvedValue('a'.repeat(40)); container = document.createElement('div'); @@ -197,211 +172,13 @@ describe('DispatchInstallDialog target preparation', () => { container.remove(); }); - it('deploys the verified release with one click and follows the worktree copy setting', async () => { - const onReady = vi.fn(); - mocks.getFreshConfig.mockResolvedValue({ copyLocalChanges: true }); - let installed = false; - mocks.installCliPoll.mockImplementation(async () => { - installed = true; - return { cursor: 1, output: '', status: 'succeeded' }; - }); - mocks.probeTarget.mockImplementation(async () => installed - ? { - cliInstalled: true, - os: 'linux', - arch: 'x86_64', - installSupported: false, - protocol: { - productId: 'openbitfun', - dataNamespace: 'openbitfun', - protocolVersion: DISPATCH_PROTOCOL_VERSION, - cliVersion: '1.2.3', - os: 'linux', - arch: 'x86_64', - capabilities: READY_CAPABILITIES, - modelConfigured: true, - availableModels: ['model-a'], - }, - } - : { - cliInstalled: false, - os: 'linux', - arch: 'x86_64', - installSupported: true, - release: { - version: '1.2.3', - target: 'x86_64-unknown-linux-gnu', - url: 'https://example.test/openbitfun', - sha256: 'abc123', - }, - }); - - await act(async () => { - root.render( - , - ); - await Promise.resolve(); - await Promise.resolve(); - }); - - expect(container.textContent).toContain('dispatch.oneClickDeployDescription'); - expect(container.textContent).toContain('dispatch.oneClickDeploy'); - expect(container.textContent).toContain('1.2.3'); - expect(container.textContent).toContain('abc123'); - expect(container.querySelector('[data-openbitfun-component="disclosure"] button[aria-expanded]')?.getAttribute('aria-expanded')).toBe('false'); - expect(container.textContent).not.toContain('dispatch.installAutomaticDescription'); - expect(mocks.dialogLifecycleProps).toEqual({ - closeOnPointerOutside: true, - showCloseButton: true, - }); - const includeUncommitted = container.querySelector('input[type="checkbox"]'); - expect(includeUncommitted?.checked).toBe(true); - - const useTargetBeforeSetup = Array.from(container.querySelectorAll('button')) - .find(button => button.textContent?.includes('dispatch.useTarget')); - expect(useTargetBeforeSetup?.disabled).toBe(true); - - await act(async () => { - Array.from(container.querySelectorAll('button')) - .find(button => button.textContent?.includes('dispatch.oneClickDeploy')) - ?.click(); - await Promise.resolve(); - await Promise.resolve(); - await Promise.resolve(); - await Promise.resolve(); - }); - - expect(mocks.installCliStart).toHaveBeenCalledWith( - 'ssh-1', - expect.objectContaining({ version: '1.2.3', sha256: 'abc123' }), - ); - expect(mocks.installCliPoll).toHaveBeenCalledWith('ssh-1', 0); - expect(mocks.provisionTarget).toHaveBeenCalledWith('ssh-1'); - expect(container.textContent).toContain('dispatch.prepareSucceededCliOnly'); - - await act(async () => { - Array.from(container.querySelectorAll('button')) - .find(button => button.textContent?.includes('dispatch.useTarget')) - ?.click(); - await Promise.resolve(); - await Promise.resolve(); - }); - - expect(mocks.getFreshConfig).toHaveBeenCalledWith('app.worktrees', { - skipRetryOnNotFound: true, - }); - expect(mocks.resolveRevision).toHaveBeenCalledWith( - { workspaceId: 'workspace-source', repositoryPath: '/home/me/project' }, - 'HEAD', - ); - expect(onReady).toHaveBeenCalledWith(expect.objectContaining({ - baseRef: 'HEAD', - includeUncommitted: true, - request: { kind: 'ssh', connectionId: 'ssh-1', workspacePath: '' }, - })); - expect(onReady.mock.calls[0][0]).not.toHaveProperty('approvalPolicy'); - }); - - it('retries only account and service provisioning after the CLI is installed', async () => { - let installed = false; - mocks.installCliPoll.mockImplementation(async () => { - installed = true; - return { cursor: 1, output: '', status: 'succeeded' }; - }); - mocks.probeTarget.mockImplementation(async () => installed - ? { - cliInstalled: true, - os: 'linux', - arch: 'x86_64', - installSupported: false, - protocol: { - productId: 'openbitfun', - dataNamespace: 'openbitfun', - protocolVersion: DISPATCH_PROTOCOL_VERSION, - cliVersion: '1.2.3', - os: 'linux', - arch: 'x86_64', - capabilities: READY_CAPABILITIES, - modelConfigured: true, - availableModels: ['model-a'], - }, - } - : { - cliInstalled: false, - os: 'linux', - arch: 'x86_64', - installSupported: true, - release: { - version: '1.2.3', - target: 'x86_64-unknown-linux-gnu', - url: 'https://example.test/openbitfun', - sha256: 'abc123', - }, - }); - mocks.provisionTarget - .mockRejectedValueOnce(new Error('relay temporarily unavailable')) - .mockResolvedValueOnce({ accountStatus: 'synced', daemonInstalled: true }); - - await act(async () => { - root.render( - , - ); - await Promise.resolve(); - await Promise.resolve(); - }); - - await act(async () => { - Array.from(container.querySelectorAll('button')) - .find(button => button.textContent?.includes('dispatch.oneClickDeploy')) - ?.click(); - await Promise.resolve(); - await Promise.resolve(); - await Promise.resolve(); - await Promise.resolve(); - }); - - expect(mocks.installCliStart).toHaveBeenCalledTimes(1); - expect(container.textContent).toContain('dispatch.retryProvisionDescription'); - - await act(async () => { - Array.from(container.querySelectorAll('button')) - .find(button => button.textContent?.includes('dispatch.retryProvision')) - ?.click(); - await Promise.resolve(); - await Promise.resolve(); - await Promise.resolve(); - }); - - expect(mocks.installCliStart).toHaveBeenCalledTimes(1); - expect(mocks.provisionTarget).toHaveBeenCalledTimes(2); - expect(container.textContent).toContain('dispatch.prepareSucceededWithAccount'); - }); - it('does not overwrite a user choice when the worktree default resolves late', async () => { const worktreeSettings = createDeferred<{ copyLocalChanges: boolean }>(); mocks.getFreshConfig.mockReturnValue(worktreeSettings.promise); await act(async () => { root.render( - { await act(async () => { root.render( - { expect(container.querySelector('.dispatch-install-dialog')).not.toBeNull(); }); - it('never offers to compile on the target and explains why it cannot be prepared', async () => { - // A target no published binary fits. Preparing it is not something this - // controller can do, so the dialog says so instead of offering to build - // OpenBitFun on someone else's machine. + it('blocks a missing CLI even when an older host advertises one-click setup', async () => { mocks.probeTarget.mockResolvedValue({ cliInstalled: false, os: 'linux', arch: 'x86_64', - installSupported: false, + installSupported: true, prebuiltIncompatible: 'target uses musl libc', }); await act(async () => { root.render( - { await Promise.resolve(); }); - expect(container.textContent).toContain('dispatch.installUnavailable'); + expect(container.textContent).toContain('dispatch.cliUnavailable'); expect(container.textContent).not.toContain('target uses musl libc'); expect(container.textContent).not.toContain('sourceBuild'); - expect(container.textContent).not.toContain('dispatch.installAutomaticDescription'); + expect(container.textContent).not.toContain('dispatch.oneClickDeploy'); const useTarget = Array.from(container.querySelectorAll('button')) .find(button => button.textContent?.includes('dispatch.useTarget')); @@ -561,7 +335,7 @@ describe('DispatchInstallDialog target preparation', () => { await act(async () => { root.render( - { ); await act(async () => { root.render( - { it('explains the Git baseline and never offers a snapshot delivery mode', async () => { await act(async () => { root.render( - { await act(async () => { root.render( - { await act(async () => { root.render( - { await act(async () => { root.render( - void; + onReady: (selection: DispatchSelection) => void; +} + +export const DispatchTargetDialog: React.FC = ({ + open, + target, + sourceWorkspacePath, + sourceWorkspaceId, + onClose, + onReady, +}) => { + const { t } = useI18n('common'); + const [includeUncommitted, setIncludeUncommitted] = useState(false); + const [baseRef, setBaseRef] = useState('HEAD'); + const [baseRefError, setBaseRefError] = useState(null); + const [validatingBaseRef, setValidatingBaseRef] = useState(false); + const [worktreeSettingsLoading, setWorktreeSettingsLoading] = useState(true); + const [probe, setProbe] = useState(null); + const [probing, setProbing] = useState(false); + const [probeError, setProbeError] = useState(false); + const generationRef = useRef(0); + const includeUncommittedTouchedRef = useRef(false); + + const targetId = target?.connectionId?.trim() ?? ''; + + const runProbe = useCallback(async () => { + if (!targetId || !target || target.kind !== 'ssh') return; + // The target's own directories are irrelevant now: dispatch checks out its + // own worktree there, so the probe only reports CLI and model readiness. + const path = ''; + const generation = ++generationRef.current; + setProbing(true); + setProbeError(false); + try { + const result = await dispatchApi.probeTarget({ kind: 'ssh', connectionId: targetId, workspacePath: path }); + if (generation === generationRef.current) { + setProbe(result); + } + } catch (nextError) { + if (generation === generationRef.current) { + setProbe(null); + setProbeError(true); + log.warn('Failed to check dispatch target readiness', { + targetKind: target.kind, + targetId, + error: nextError, + }); + } + } finally { + if (generation === generationRef.current) { + setProbing(false); + } + } + }, [target, targetId]); + + useEffect(() => { + if (!open || !targetId) return; + includeUncommittedTouchedRef.current = false; + setIncludeUncommitted(false); + setBaseRef('HEAD'); + setBaseRefError(null); + setValidatingBaseRef(false); + setWorktreeSettingsLoading(true); + setProbe(null); + setProbeError(false); + void runProbe(); + }, [open, runProbe, targetId]); + + // Dispatch uses the same baseline creation path as the regular worktree + // control, so its initial copy-local-changes choice follows that setting. + useEffect(() => { + if (!open) return; + let cancelled = false; + setWorktreeSettingsLoading(true); + void configAPI.getConfig('app.worktrees', { skipRetryOnNotFound: true }) + .then(settings => { + if (!cancelled && !includeUncommittedTouchedRef.current) { + const configured = settings as Partial | undefined; + setIncludeUncommitted(configured?.copyLocalChanges === true); + } + }) + .catch(nextError => { + log.warn('Failed to read worktree settings for dispatch', { + error: nextError, + }); + if (!cancelled && !includeUncommittedTouchedRef.current) { + setIncludeUncommitted(false); + } + }) + .finally(() => { + if (!cancelled) setWorktreeSettingsLoading(false); + }); + return () => { + cancelled = true; + }; + }, [open, targetId]); + + // Retires every in-flight probe, model sync, and revision check, so a result + // that lands after the dialog moved on cannot write to a closed dialog. + const invalidatePendingWork = useCallback(() => { + generationRef.current += 1; + }, []); + + useEffect(() => { + if (!open || !targetId) return; + return () => { + invalidatePendingWork(); + }; + }, [invalidatePendingWork, open, targetId]); + + const closeDialog = useCallback(() => { + invalidatePendingWork(); + onClose(); + }, [invalidatePendingWork, onClose]); + + const protocol = probe?.protocol; + const requiredCapabilities = [...BASE_DISPATCH_CAPABILITIES]; + const missingCapabilities = protocol + ? requiredCapabilities.filter(capability => !protocol.capabilities.includes(capability)) + : requiredCapabilities; + const protocolCompatible = + protocol?.protocolVersion === DISPATCH_PROTOCOL_VERSION && + missingCapabilities.length === 0; + const cliReady = + !!probe?.cliInstalled && + !!protocol && + !probe.protocolError && + protocolCompatible; + // The source workspace is owned by ID; the path only labels its checkout. + const workspaceReady = !!sourceWorkspaceId?.trim() || !!sourceWorkspacePath?.trim(); + /** + * Model readiness is deliberately absent: the model is chosen in the + * composer like any local session, and submission pushes this device's model + * configuration to a target that cannot serve the choice. Gating here would + * ask the user to solve a problem the backend already solves. + */ + const ready = workspaceReady && cliReady; + + const confirmTarget = async () => { + if ( + !target + || target.kind !== 'ssh' + || !targetId + || !ready + ) return; + const normalizedSourcePath = sourceWorkspacePath?.trim() || ''; + const normalizedBaseRef = baseRef.trim() || 'HEAD'; + const generation = generationRef.current; + setValidatingBaseRef(true); + setBaseRefError(null); + try { + await gitAPI.resolveRevision({ workspaceId: sourceWorkspaceId ?? '', repositoryPath: normalizedSourcePath }, normalizedBaseRef); + } catch (nextError) { + if (generation === generationRef.current) { + log.warn('Failed to resolve dispatch base revision', { + repositoryPath: normalizedSourcePath, + revision: normalizedBaseRef, + error: nextError, + }); + setBaseRefError(t('dispatch.baseRefInvalid', { ref: normalizedBaseRef })); + } + return; + } finally { + if (generation === generationRef.current) { + setValidatingBaseRef(false); + } + } + if (generation !== generationRef.current) return; + // The target chooses where its worktree lands, so nothing is sent here. + const normalizedPath = ''; + const request = { + kind: 'ssh' as const, + connectionId: targetId, + workspacePath: normalizedPath, + }; + onReady({ + request, + target: { + ...request, + workspacePath: normalizedPath, + displayName: target.displayName, + }, + includeUncommitted, + baseRef: normalizedBaseRef, + modelCatalog: protocol?.modelCatalog, + availableModels: protocol?.availableModels, + defaultModel: protocol?.defaultModel, + }); + }; + + return ( + { if (!nextOpen) closeDialog(); }} + size="md" + aria-labelledby={DIALOG_TITLE_ID} + data-testid="dispatch-install-dialog" + > +
+ + + + {t('dispatch.configureTitle', { target: target?.displayName ?? '' })} + + {t('dispatch.configureSubtitle')} + + + + + + {baseRefError ? ( + setBaseRefError(null)} + /> + ) : null} + +
+

+ {t('dispatch.readinessTitle')} +

+ {probing || (!probe && !probeError) ? ( +
+ + {t('dispatch.checkingTarget')} +
+ ) : null} + {probeError ? ( +
+ + {t('dispatch.probeFailed')} + + +
+ ) : null} + {probe ? ( +
+
+ {t('dispatch.cliStatus')} + + {cliReady + ? t('dispatch.cliReady', { version: protocol?.cliVersion }) + : t(probe.cliInstalled ? 'dispatch.cliUpdateRequired' : 'dispatch.cliUnavailable')} + +
+
+ ) : null} +
+ +
+

+ {t('dispatch.deliveryTitle')} +

+
+ + {t('dispatch.baselineSource')} + + {sourceWorkspacePath} +
+ + {t('dispatch.baselineDescription')} + + + { + includeUncommittedTouchedRef.current = true; + setIncludeUncommitted(checked); + }} + label={t('dispatch.includeUncommitted')} + description={t('dispatch.includeUncommittedHint')} + /> +
+
+ +
+ + + + +
+
+
+ ); +}; diff --git a/src/web-ui/src/features/dispatch/DispatchTargetPicker.test.tsx b/src/web-ui/src/features/dispatch/DispatchTargetPicker.test.tsx index 26ed70a1b1..db202316db 100644 --- a/src/web-ui/src/features/dispatch/DispatchTargetPicker.test.tsx +++ b/src/web-ui/src/features/dispatch/DispatchTargetPicker.test.tsx @@ -40,8 +40,8 @@ vi.mock('@/features/ssh-remote/SSHConnectionDialog', () => ({ SSHConnectionDialog: () => null, })); -vi.mock('./DispatchInstallDialog', () => ({ - DispatchInstallDialog: () => null, +vi.mock('./DispatchTargetDialog', () => ({ + DispatchTargetDialog: () => null, })); const rect = ( @@ -191,10 +191,10 @@ describe('DispatchTargetPicker overlay', () => { expect(onWorktreeChange).toHaveBeenLastCalledWith(false); }); - it('lists a confirmed-incompatible device but never offers it as a target', async () => { + it('omits account devices from the manual dispatch menu', async () => { pickerState.loggedIn = true; pickerState.targets = [ - { kind: 'device', deviceId: 'peer', displayName: 'Old build', online: true, incompatible: true }, + { kind: 'device', deviceId: 'peer', displayName: 'Old build', online: true }, ]; await act(async () => { @@ -215,11 +215,6 @@ describe('DispatchTargetPicker overlay', () => { const option = Array.from( document.querySelectorAll('[data-openbitfun-menu-item]'), ).find(node => node.textContent?.includes('Old build')); - expect(option).toBeDefined(); - // The device is visible with its reason but cannot be selected. - expect(option?.textContent).toContain('accountLogin.deviceClientIncompatibleTag'); - expect(option?.querySelector('[data-openbitfun-component="status-pill"]')?.getAttribute('aria-label')) - .toBe('chatInput.dispatch.deviceIncompatible'); - expect(option?.disabled).toBe(true); + expect(option).toBeUndefined(); }); }); diff --git a/src/web-ui/src/features/dispatch/DispatchTargetPicker.tsx b/src/web-ui/src/features/dispatch/DispatchTargetPicker.tsx index 3379c4961d..7ec490a465 100644 --- a/src/web-ui/src/features/dispatch/DispatchTargetPicker.tsx +++ b/src/web-ui/src/features/dispatch/DispatchTargetPicker.tsx @@ -1,7 +1,5 @@ -import { lazyWithRecovery } from '@/shared/utils/lazyWithRecovery'; import { useDeviceDirectory, resolveDeviceName } from '@/infrastructure/account/deviceDirectory'; import React, { - Suspense, useEffect, useMemo, useRef, @@ -9,13 +7,12 @@ import React, { } from 'react'; import { FolderGit2, Laptop, Loader2, MonitorSmartphone, Server } from 'lucide-react'; -import { subscribeOverlayInteraction, createOverlayPortal, OverflowText, Icon, Menu, MenuItem, MenuSection, MenuSeparator, StatusPill, Tooltip } from '@openbitfun/ui'; +import { subscribeOverlayInteraction, createOverlayPortal, OverflowText, Icon, Menu, MenuItem, MenuSection, MenuSeparator, Tooltip } from '@openbitfun/ui'; import { SSHConnectionDialog } from '@/features/ssh-remote/SSHConnectionDialog'; -import { useAccountLoginState } from '@/infrastructure/account/useAccountLoginState'; import { getAppearanceOverlayHost } from '@/infrastructure/appearance/runtime/AppearanceOverlayHost'; import { useI18n } from '@/infrastructure/i18n'; import { useAnchoredPopoverPosition } from '@/shared/utils/useAnchoredPopoverPosition'; -import { DispatchInstallDialog } from './DispatchInstallDialog'; +import { DispatchTargetDialog } from './DispatchTargetDialog'; import { DispatchTransportStatus } from './DispatchTransportStatus'; import { useActiveDispatchJobId } from './useDispatchTransportStatus'; import type { @@ -48,10 +45,6 @@ interface DispatchTargetPickerProps { jobId?: string; } -const RemoteConnectDialog = lazyWithRecovery( - () => import('@/app/components/RemoteConnectDialog'), -); - export const DispatchTargetPicker: React.FC = ({ target, sourceWorkspacePath, @@ -67,15 +60,12 @@ export const DispatchTargetPicker: React.FC = ({ const activeJobId = useActiveDispatchJobId(target); const transportJobId = target.kind === 'local' ? undefined : jobId ?? activeJobId; const { t } = useI18n('flow-chat'); - const { t: tCommon } = useI18n('common'); const rootRef = useRef(null); const triggerRef = useRef(null); const menuRef = useRef(null); const [open, setOpen] = useState(false); const [configureTarget, setConfigureTarget] = useState(null); const [sshDialogOpen, setSshDialogOpen] = useState(false); - const [accountDialogOpen, setAccountDialogOpen] = useState(false); - const { loggedIn } = useAccountLoginState(); const { targets, loading, error, refresh } = useDispatchTargets(open); const menuLayout = useAnchoredPopoverPosition({ open, @@ -126,13 +116,6 @@ export const DispatchTargetPicker: React.FC = ({ ), [targets], ); - const deviceTargets = useMemo( - () => targets.filter( - (item): item is DispatchTargetOption & { kind: 'device'; deviceId: string } => - item.kind === 'device' && !!item.deviceId, - ), - [targets], - ); const selectLocalMode = (worktreeEnabled: boolean) => { setOpen(false); @@ -210,74 +193,6 @@ export const DispatchTargetPicker: React.FC = ({ ) : null} - - - {!loggedIn ? ( - } - onClick={() => { - setOpen(false); - setAccountDialogOpen(true); - }} - > - {t('chatInput.dispatch.signInDevices')} - - ) : null} - {loggedIn && !loading && deviceTargets.length === 0 ? ( -
- {t('chatInput.dispatch.noDeviceTargets')} -
- ) : null} - {deviceTargets.map(option => { - const selected = target.kind === 'device' && target.deviceId === option.deviceId; - const online = option.online !== false; - // A confirmed-incompatible device stays listed so the reason is legible, - // but it is never offered as a selectable dispatch target. - const incompatible = option.incompatible === true; - return ( - } - metadata={selected ? : null} - onClick={() => { - if (incompatible) return; - setOpen(false); - setConfigureTarget(option); - }} - > - - - {option.displayName} - {incompatible ? ( - - - {tCommon('accountLogin.deviceClientIncompatibleTag')} - - - ) : !online ? ( - - {t('chatInput.dispatch.deviceOffline')} - - ) : null} - - {online && !incompatible ? ( - {t('chatInput.dispatch.deviceDescription')} - ) : null} - - - ); - })} -
- {loading ? ( @@ -376,7 +291,7 @@ export const DispatchTargetPicker: React.FC = ({ {menu && createOverlayPortal(menu, getAppearanceOverlayHost())} - = ({ void refresh(); }} /> - {accountDialogOpen ? ( - - { - setAccountDialogOpen(false); - void refresh(); - }} - /> - - ) : null} ); }; diff --git a/src/web-ui/src/features/dispatch/README.md b/src/web-ui/src/features/dispatch/README.md index e98f37cc1c..0457c3f835 100644 --- a/src/web-ui/src/features/dispatch/README.md +++ b/src/web-ui/src/features/dispatch/README.md @@ -1,7 +1,6 @@ # Dispatch Web UI -The Web UI supports local execution plus detached SSH and same-account device -dispatch. +Users can select local execution or an SSH target with a compatible CLI. The Agent can also submit to same-account devices. Existing jobs remain available in the observer. ## Invariants @@ -59,19 +58,7 @@ dispatch. `includeUncommitted` copies and commits Git-visible controller changes only inside the managed baseline. The user's checkout is never changed, and ignored runtime inputs are not sent to the target. -11. SSH submission automatically installs or upgrades a compatible signed - prebuilt `openbitfun` release when the target runner is missing or incompatible. - The resolved version, URL, and SHA-256 remain visible, integrity checks stay - mandatory, installation has a bounded deadline, and submission probes the - installed runner again before provisioning. Each `cli-install` audit - transition is durably written to the preparation journal; the started event - is persisted before remote installer mutation, and an audit write failure - stops submission. The events are projected into the pending Dispatch turn - and cached with the transcript, so the automatic action remains visible - after replay or controller restart. -12. The signed prebuilt release is the only way a target gets a runner. The - controller never compiles OpenBitFun on someone else's machine, so a target no - published binary fits is reported as unusable rather than offered a build. +11. SSH submission probes the installed runner before provisioning the workspace. A missing or incompatible CLI blocks submission. 13. Account devices use encrypted request/response RPC and distinct `dispatch_target_*` commands. They never attach Peer Device Mode and an offline or incompatible target never falls back to local execution. Device @@ -119,8 +106,7 @@ dispatch. that cannot serve the submission's model, before creating any baseline, and re-probes. Choosing the target is the consent: it is the same credential write the manual command performs, and it stays visible as `model-sync` - rows in the preparation journal and the projected transcript, exactly like - `cli-install`. It merges only the `ai` model keys into the target's + rows in the preparation journal and the projected transcript. It merges only the `ai` model keys into the target's `app.json`, preserves every other target setting, aborts rather than overwrite an unreadable or unparseable target config, and writes owner-only via a temp-file rename. A failed push is not fatal by itself: diff --git a/src/web-ui/src/features/dispatch/dispatch.contract.test.ts b/src/web-ui/src/features/dispatch/dispatch.contract.test.ts index cea9de36cb..2ac22de854 100644 --- a/src/web-ui/src/features/dispatch/dispatch.contract.test.ts +++ b/src/web-ui/src/features/dispatch/dispatch.contract.test.ts @@ -10,10 +10,6 @@ import { PEER_CONTROLLER_LOCAL_COMMANDS } from '@/infrastructure/api/generated/r const OUTBOUND_DISPATCH_COMMANDS = [ 'dispatch_list_targets', 'dispatch_probe_target', - 'dispatch_install_cli_start', - 'dispatch_install_cli_poll', - 'dispatch_install_cli_cancel', - 'dispatch_provision_target', 'dispatch_sync_model_config', 'dispatch_submit', 'dispatch_status', diff --git a/src/web-ui/src/features/dispatch/dispatchApi.test.ts b/src/web-ui/src/features/dispatch/dispatchApi.test.ts index d26cb4e319..483e1b8fd4 100644 --- a/src/web-ui/src/features/dispatch/dispatchApi.test.ts +++ b/src/web-ui/src/features/dispatch/dispatchApi.test.ts @@ -16,14 +16,20 @@ describe('dispatchApi', () => { mocks.invoke.mockReset().mockResolvedValue([]); }); - it('wraps the target list command in the structured Tauri request contract', async () => { + it('lists SSH targets without querying account devices', async () => { await dispatchApi.listTargets(); expect(mocks.invoke).toHaveBeenCalledWith('dispatch_list_targets', { - request: {}, + request: { sshOnly: true }, }); }); + it('can list targets on older hosts that reject the SSH filter', async () => { + mocks.invoke.mockRejectedValueOnce(new Error('unknown field `sshOnly`')); + await dispatchApi.listTargets(); + expect(mocks.invoke).toHaveBeenNthCalledWith(2, 'dispatch_list_targets', { request: {} }); + }); + it('carries the selected reasoning preset when submitting a job', async () => { await dispatchApi.submit({ target: { diff --git a/src/web-ui/src/features/dispatch/dispatchApi.ts b/src/web-ui/src/features/dispatch/dispatchApi.ts index 1b227349e0..76030f142f 100644 --- a/src/web-ui/src/features/dispatch/dispatchApi.ts +++ b/src/web-ui/src/features/dispatch/dispatchApi.ts @@ -2,10 +2,6 @@ import { api } from '@/infrastructure/api/service-api/ApiClient'; import type { DispatchApprovalPolicy, DispatchCancelResponse, - DispatchCliRelease, - DispatchInstallPoll, - DispatchInstallStart, - DispatchProvisionTargetResult, DispatchContinueResponse, DispatchJobListEntry, DispatchSshProbe, @@ -28,9 +24,15 @@ export interface DispatchInlineAttachment { export const dispatchApi = { async listTargets(): Promise { - return api.invoke('dispatch_list_targets', { - request: {}, - }); + const list = (request: { sshOnly?: boolean }) => + api.invoke('dispatch_list_targets', { request }); + try { + return await list({ sshOnly: true }); + } catch (error) { + // Older hosts reject new request fields. The picker filters their response. + if (!/unknown field [`'"]sshOnly[`'"]/i.test(String(error))) throw error; + return list({}); + } }, async probeTarget(target: DispatchTargetRequest): Promise { @@ -39,33 +41,6 @@ export const dispatchApi = { }); }, - async installCliStart( - connectionId: string, - release: DispatchCliRelease, - ): Promise { - return api.invoke('dispatch_install_cli_start', { - request: { connectionId, release }, - }); - }, - - async installCliPoll(connectionId: string, cursor: number): Promise { - return api.invoke('dispatch_install_cli_poll', { - request: { connectionId, cursor }, - }); - }, - - async installCliCancel(connectionId: string): Promise { - return api.invoke('dispatch_install_cli_cancel', { - request: { connectionId }, - }); - }, - - async provisionTarget(connectionId: string): Promise { - return api.invoke('dispatch_provision_target', { - request: { connectionId }, - }); - }, - /** * Bring a job's work back into this controller's baseline worktree. * diff --git a/src/web-ui/src/features/dispatch/types.ts b/src/web-ui/src/features/dispatch/types.ts index 6f21a9c90d..8601f35b8e 100644 --- a/src/web-ui/src/features/dispatch/types.ts +++ b/src/web-ui/src/features/dispatch/types.ts @@ -144,25 +144,6 @@ export interface DispatchSyncResult { syncedHeadCommit?: string; } -export interface DispatchInstallStart { - scriptPath: string; - version: string; - target: string; - url: string; - sha256: string; -} - -export interface DispatchInstallPoll { - cursor: number; - output: string; - status: 'running' | 'succeeded' | 'failed'; -} - -export interface DispatchProvisionTargetResult { - accountStatus: 'synced' | 'skipped_not_logged_in'; - daemonInstalled: boolean; -} - export type DispatchEvent = | { type: 'audit'; diff --git a/src/web-ui/src/features/dispatch/useDispatchTargets.ts b/src/web-ui/src/features/dispatch/useDispatchTargets.ts index 2cd44634de..27642fe010 100644 --- a/src/web-ui/src/features/dispatch/useDispatchTargets.ts +++ b/src/web-ui/src/features/dispatch/useDispatchTargets.ts @@ -1,5 +1,4 @@ -import { useDeviceDirectory, resolveDeviceName, isDeviceControllable } from '@/infrastructure/account/deviceDirectory'; -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; import { createLogger } from '@/shared/utils/logger'; import { dispatchApi } from './dispatchApi'; import type { DispatchTargetOption } from './types'; @@ -12,7 +11,6 @@ export function useDispatchTargets(enabled = true): { error: boolean; refresh: () => Promise; } { - const directory = useDeviceDirectory(); const [targets, setTargets] = useState([]); const [loading, setLoading] = useState(false); const [loaded, setLoaded] = useState(false); @@ -25,7 +23,7 @@ export function useDispatchTargets(enabled = true): { try { const nextTargets = await dispatchApi.listTargets(); setTargets(nextTargets.filter( - target => target.kind === 'local' || target.kind === 'ssh' || target.kind === 'device', + target => target.kind === 'local' || target.kind === 'ssh', )); } catch (nextError) { log.warn('Failed to list dispatch targets', { error: nextError }); @@ -41,24 +39,11 @@ export function useDispatchTargets(enabled = true): { void refresh(); }, [refresh]); - /** Devices the Relay confirmed cannot be controlled from this build. */ - const incompatibleDeviceIds = useMemo(() => new Set( - directory.devices - .filter(device => !isDeviceControllable(device)) - .map(device => device.device_id), - ), [directory.devices]); - // Opening the picker enables this hook one render before the effect starts // the request. Treat that first render as loading so users never see a // misleading empty-target message flash before saved SSH targets arrive. return { - targets: targets.map(target => target.kind === 'device' && target.deviceId - ? { - ...target, - displayName: resolveDeviceName(target.deviceId, target.displayName), - incompatible: incompatibleDeviceIds.has(target.deviceId), - } - : target), + targets, loading: loading || (enabled && !loaded), error, refresh, diff --git a/src/web-ui/src/infrastructure/api/generated/productControl.ts b/src/web-ui/src/infrastructure/api/generated/productControl.ts index 42c2f21b37..31d57a13f7 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 = "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b" as const; +export const PRODUCT_CONTROL_GRAPH_DIGEST = "82954fefebb8251023c36bd1f83f9e740c4889da4e22712089e80e3234c6267c" 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.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 3a9455290d..79b5b461ff 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:67a20e107dd93ffd" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:1457e10fcdbf7a86" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -56,14 +56,10 @@ export const PEER_CONTROLLER_LOCAL_COMMANDS: ReadonlySet = new Set([ "dispatch_append", "dispatch_cancel", "dispatch_continue", - "dispatch_install_cli_cancel", - "dispatch_install_cli_poll", - "dispatch_install_cli_start", "dispatch_list_jobs", "dispatch_list_targets", "dispatch_load_transcript", "dispatch_probe_target", - "dispatch_provision_target", "dispatch_query", "dispatch_save_transcript", "dispatch_status", diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index ddea38852a..b57216d702 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -2225,28 +2225,10 @@ "includeUncommittedHint": "Only Git-visible changes are sent. Ignored files, including local .env files and build output, stay on this device.", "cliStatus": "$t(shared:product.name)", "cliReady": "Ready ({{version}})", - "cliCanDeploy": "Ready for one-click setup", - "installingCli": "Installing OpenBitFun CLI…", - "provisioningDaemon": "Syncing the account and starting the service…", - "cancellingPreparation": "Cancelling setup…", "cliUpdateRequired": "Needs an update before it can run tasks", "cliUnavailable": "OpenBitFun is not installed on this target", "deviceUpdateRequired": "Update OpenBitFun on this device, then check again.", - "oneClickDeploy": "Set up OpenBitFun", - "oneClickDeployDescription": "Installs the signature-verified OpenBitFun CLI. If this device is signed in, it also syncs the current account and starts an auto-start service.", - "prepareSucceededWithAccount": "OpenBitFun CLI is installed, the account was synced securely, and the persistent service is connected.", - "prepareSucceededCliOnly": "OpenBitFun CLI is installed. Account sync was skipped because this device is signed out; SSH Dispatch tasks still run as persistent background processes.", - "prepareFailed": "OpenBitFun setup did not complete. Failed account and service changes are cleaned up on a best-effort basis; check the target connection or service manager and try again.", - "prepareCancelled": "Setup was cancelled.", - "prepareCancelFailed": "Setup could not be cancelled. Check the target status again shortly.", - "cancelPreparation": "Cancel setup", - "retryProvision": "Retry account service", - "retryProvisionDescription": "The CLI is ready. Retry only the secure account sync and persistent service setup.", - "installUnavailable": "No compatible OpenBitFun package is available for this target, so it cannot run tasks. Pick another target, or install OpenBitFun on it yourself and check again.", - "installDetails": "Installation details", "version": "Version", - "downloadUrl": "Source", - "integrity": "Integrity check", "useTarget": "Use this target", "cancel": "Cancel", "eventHistoryIncomplete": "Some task history is no longer available. The visible conversation may be incomplete.", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index dfa95e3cc9..896932c8a6 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -2225,28 +2225,10 @@ "includeUncommittedHint": "只会发送 Git 可见的改动;.env、构建产物等忽略文件会保留在本机。", "cliStatus": "$t(shared:product.name)", "cliReady": "就绪({{version}})", - "cliCanDeploy": "可一键部署", - "installingCli": "正在安装 OpenBitFun CLI…", - "provisioningDaemon": "正在同步账号并启动常驻服务…", - "cancellingPreparation": "正在取消部署…", "cliUpdateRequired": "需要更新后才能运行任务", "cliUnavailable": "此目标尚未安装 OpenBitFun", "deviceUpdateRequired": "请在此设备上更新 OpenBitFun,然后重新检查。", - "oneClickDeploy": "一键部署 OpenBitFun", - "oneClickDeployDescription": "安装经过签名校验的 OpenBitFun CLI;若本机已登录,还会为目标同步当前账号并启动开机常驻服务。", - "prepareSucceededWithAccount": "OpenBitFun CLI 已安装,账号已安全同步,常驻服务已启动并连接。", - "prepareSucceededCliOnly": "OpenBitFun CLI 已安装。本机未登录,已跳过账号同步;SSH Dispatch 任务仍会以独立后台进程持久运行。", - "prepareFailed": "未能完整部署 OpenBitFun。失败的账号和服务变更会尽力自动清理;请检查目标连接或服务管理器后重试。", - "prepareCancelled": "部署已取消。", - "prepareCancelFailed": "无法取消部署,请稍后重新检查目标状态。", - "cancelPreparation": "取消部署", - "retryProvision": "重试账号常驻服务", - "retryProvisionDescription": "CLI 已就绪,可单独重试安全账号同步和常驻服务部署。", - "installUnavailable": "此目标没有可用的 OpenBitFun 安装包,无法运行任务。请换一个目标,或先在该设备上自行安装 OpenBitFun 后重新检查。", - "installDetails": "安装详情", "version": "版本", - "downloadUrl": "下载来源", - "integrity": "完整性校验", "useTarget": "使用此目标", "cancel": "取消", "eventHistoryIncomplete": "部分任务记录已无法加载,当前内容可能不完整。", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index fb41501ae4..d5b1723632 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -2225,28 +2225,10 @@ "includeUncommittedHint": "只會傳送 Git 可見的變更;.env、建置產物等忽略檔案會保留在本機。", "cliStatus": "$t(shared:product.name)", "cliReady": "就緒({{version}})", - "cliCanDeploy": "可一鍵部署", - "installingCli": "正在安裝 OpenBitFun CLI…", - "provisioningDaemon": "正在同步帳號並啟動常駐服務…", - "cancellingPreparation": "正在取消部署…", "cliUpdateRequired": "需要更新後才能執行任務", "cliUnavailable": "此目標尚未安裝 OpenBitFun", "deviceUpdateRequired": "請在此裝置上更新 OpenBitFun,然後重新檢查。", - "oneClickDeploy": "一鍵部署 OpenBitFun", - "oneClickDeployDescription": "安裝經過簽章驗證的 OpenBitFun CLI;若本機已登入,還會為目標同步目前帳號並啟動開機常駐服務。", - "prepareSucceededWithAccount": "OpenBitFun CLI 已安裝,帳號已安全同步,常駐服務已啟動並連線。", - "prepareSucceededCliOnly": "OpenBitFun CLI 已安裝。本機未登入,已略過帳號同步;SSH Dispatch 任務仍會以獨立背景程序持續執行。", - "prepareFailed": "未能完整部署 OpenBitFun。失敗的帳號和服務變更會盡力自動清理;請檢查目標連線或服務管理器後重試。", - "prepareCancelled": "部署已取消。", - "prepareCancelFailed": "無法取消部署,請稍後重新檢查目標狀態。", - "cancelPreparation": "取消部署", - "retryProvision": "重試帳號常駐服務", - "retryProvisionDescription": "CLI 已就緒,可單獨重試安全帳號同步和常駐服務部署。", - "installUnavailable": "此目標沒有可用的 OpenBitFun 安裝套件,無法執行任務。請換一個目標,或先在該裝置上自行安裝 OpenBitFun 後重新檢查。", - "installDetails": "安裝詳情", "version": "版本", - "downloadUrl": "下載來源", - "integrity": "完整性驗證", "useTarget": "使用此目標", "cancel": "取消", "eventHistoryIncomplete": "部分任務記錄已無法載入,目前內容可能不完整。", diff --git a/src/web-ui/src/shared/utils/logger.test.ts b/src/web-ui/src/shared/utils/logger.test.ts index b244f799e5..d531e38f40 100644 --- a/src/web-ui/src/shared/utils/logger.test.ts +++ b/src/web-ui/src/shared/utils/logger.test.ts @@ -31,7 +31,7 @@ describe('error formatting', () => { const error = new Error('Target CLI installation failed'); error.stack = '@tauri://localhost/assets/ChatPane.js:96:14836'; - createLogger('DispatchInstallDialog').warn('Failed to prepare SSH dispatch target', { + createLogger('DispatchTargetDialog').warn('Failed to prepare SSH dispatch target', { connectionId: 'ssh-a', error, }); From 12260fce4e5613ebd0e1c7962b8bc2ff11e66999 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Wed, 18 Nov 2026 21:09:59 +0800 Subject: [PATCH 2/6] fix(remote-connect): renew device and bot credentials on client hosts --- src/apps/cli/README.md | 10 + src/apps/cli/src/account.rs | 16 +- src/apps/cli/src/remote_control.rs | 7 +- src/apps/desktop/README.md | 3 +- .../desktop/src/api/remote_connect_api.rs | 68 +++- .../service/remote_connect/account_runtime.rs | 85 ++++- .../remote_connect/bot/command_router.rs | 69 ++-- .../src/remote_connect/account.rs | 38 +- .../src/remote_connect/bot/delegation.rs | 201 ++++++++++ .../src/remote_connect/bot/mod.rs | 1 + .../src/remote_connect/bot/remote_turn.rs | 7 +- .../src/remote_connect/bot/state.rs | 6 +- .../src/remote_connect/session_store.rs | 348 ++++++++++++++++-- .../src/remote_persistence.rs | 7 + 14 files changed, 755 insertions(+), 111 deletions(-) create mode 100644 src/crates/services/services-integrations/src/remote_connect/bot/delegation.rs diff --git a/src/apps/cli/README.md b/src/apps/cli/README.md index aeab570f54..a5d0a95270 100644 --- a/src/apps/cli/README.md +++ b/src/apps/cli/README.md @@ -393,6 +393,16 @@ currently install an auto-start service; use `openbitfun daemon run` under a supervisor instead. Run `openbitfun daemon --help` for lifecycle commands and platform diagnostics. +The CLI and Desktop check the 30-day Relay device credential on startup and +then every seven days. When fewer than 15 days remain, the host uses its +signed-in OpenBitFun account to request a fresh credential. It retries a +failed check after an hour. If the Relay rejects the device credential or the +host has lost its account login, sign in on that host again (`/login` in the CLI). + +Bot chats share their 24-hour delegation with their running remote turns and +renew it on use after 12 hours. A device-list request rejected with HTTP 401 +gets one retry with a fresh delegation. + ### Bots and Mobile Web from Claw In Claw chat, ask to start a WeChat, Telegram, or Feishu bot, inspect Remote diff --git a/src/apps/cli/src/account.rs b/src/apps/cli/src/account.rs index ee5dd1e23e..aea56a0069 100644 --- a/src/apps/cli/src/account.rs +++ b/src/apps/cli/src/account.rs @@ -397,7 +397,7 @@ impl CliAccountRoutingHost { tracing::warn!("Failed to adopt AuthOk device_id: {error}"); return; } - if let Ok((session, relay_url)) = runtime + if let Ok((session, _)) = runtime .read_account_context_for_generation(account_generation) .await { @@ -425,13 +425,9 @@ impl CliAccountRoutingHost { if let Some(old) = self.host_stream_hub.write().await.replace(hub) { old.close(); } - if let Err(error) = session_store::save_session_with_device( - &session.token, - &session.user_id, - &session.master_key, - &relay_url, - Some(device_id.as_str()), - ) { + if let Err(error) = + session_store::record_authenticated_device(&session.token, &device_id) + { tracing::warn!("Failed to persist AuthOk device_id: {error}"); } } @@ -729,6 +725,10 @@ impl AccountRuntimeHost for CliAccountRoutingHost { self.stop_routing().await; } + async fn device_routing_is_active(&self) -> bool { + self.relay_client.read().await.is_some() + } + async fn device_routing_is_standby(&self) -> bool { self.connection_state().await == ConnectionState::Standby } diff --git a/src/apps/cli/src/remote_control.rs b/src/apps/cli/src/remote_control.rs index d40888fdeb..7238700e46 100644 --- a/src/apps/cli/src/remote_control.rs +++ b/src/apps/cli/src/remote_control.rs @@ -68,8 +68,11 @@ pub(crate) async fn activate_daemon( .ok()?; account.account_context_is_current(generation).then_some(( relay_url, - delegated.token, - delegated.device_secret.to_vec(), + openbitfun_core::service::remote_connect::AccountSession::new( + delegated.token, + delegated.user_id, + delegated.device_secret, + ), )) } }); diff --git a/src/apps/desktop/README.md b/src/apps/desktop/README.md index aa2f0ddf11..79524538be 100644 --- a/src/apps/desktop/README.md +++ b/src/apps/desktop/README.md @@ -125,7 +125,8 @@ use the official Relay. Starting or stopping the LAN Relay does not switch their account or endpoint. LAN invitations advertise the selected network interface; select it again and create a new invitation after changing networks. -The official device session is restored on restart. The embedded LAN connection +Desktop restores the official device session on restart and uses the shared +[device credential renewal schedule](../cli/README.md#always-on-account-device-host). The embedded LAN connection is temporary and starts when requested. Builds that previously saved a temporary LAN session in the account slot attempt to restore the official Relay from the shared identity; failed sign-in leaves the previous credential on disk. Signing diff --git a/src/apps/desktop/src/api/remote_connect_api.rs b/src/apps/desktop/src/api/remote_connect_api.rs index 716945c5b3..467bcac78a 100644 --- a/src/apps/desktop/src/api/remote_connect_api.rs +++ b/src/apps/desktop/src/api/remote_connect_api.rs @@ -705,6 +705,9 @@ async fn send_rpc_error( .await; } +static RENEWAL_WAKE: std::sync::LazyLock> = + std::sync::LazyLock::new(|| Arc::new(tokio::sync::Notify::new())); + /// Global flag set when the relay returns HTTP 401 (token expired). The /// frontend checks this via `account_token_expired` and prompts re-login. static TOKEN_EXPIRED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -732,6 +735,12 @@ async fn invalidate_local_account_session_if_current( log::info!("Ignored auth failure from a stale account generation"); return false; } + if let Ok((session, relay)) = read_account_context_for_generation(expected_generation).await { + if session_store::has_saved_replacement(&session, &relay) { + RENEWAL_WAKE.notify_one(); + return false; + } + } let Some(_transition_guard) = begin_account_transition_if_current(expected_generation).await else { log::info!("Ignored auth failure from a stale account generation"); @@ -753,7 +762,9 @@ async fn invalidate_local_account_session_if_current( service.clear_bot_delegated_identities().await; } *get_account_context().write().await = None; - session_store::clear_session(); + if let Err(error) = session_store::clear_rejected_session(expected_token) { + log::warn!("Failed to clear rejected session: {error}"); + } emit_account_event( "account://login-state", serde_json::json!({ "logged_in": false, "reason": "session_expired" }), @@ -1373,8 +1384,11 @@ async fn register_delegated_identity_providers() { { Ok(delegated) if account_context_is_current(generation) => Some(( context.relay_url, - delegated.token, - delegated.device_secret.to_vec(), + openbitfun_core::service::remote_connect::AccountSession::new( + delegated.token, + delegated.user_id, + delegated.device_secret, + ), )), Ok(_) => None, Err(e) => { @@ -1392,10 +1406,47 @@ fn register_page_tool_hosts() { register_page_publish_host(); } +async fn maintain_device_session() -> anyhow::Result { + let generation = account_context_generation(); + let Ok((old, relay_url)) = read_account_context_for_generation(generation).await else { + return Ok(true); + }; + let Some(saved) = session_store::renew_session_if_due(false).await? else { + return Ok(true); + }; + if !saved.replaces(&old, &relay_url) { + return Ok(true); + } + let Some(transition) = begin_account_transition_if_current(generation).await else { + return Ok(true); + }; + let reconnect = device_routing_owner_for_account(generation, &old.token).is_some(); + *get_account_context().write().await = Some(AccountContextState { + session: AccountSession::new(saved.token, saved.user_id, saved.master_key), + relay_url, + }); + drop(transition); + if reconnect { + account_connect_devices_with_retry() + .await + .map_err(anyhow::Error::msg)?; + } + Ok(true) +} + pub fn init_on_startup() { register_page_tool_hosts(); tokio::spawn(async { let startup_generation = account_context_generation(); + let error = session_store::renew_session_if_due(false).await.err(); + if let Some(error) = &error { + log::warn!("Startup device credential maintenance failed: {error}"); + } + session_store::schedule_renewal_checks( + RENEWAL_WAKE.clone(), + error.is_some(), + maintain_device_session, + ); // Restore persisted account session (if any) before anything else // so that device routing and bot delegation work on restart. match session_store::load_session_detailed() { @@ -2309,7 +2360,7 @@ async fn persist_account_session(device_id: Option<&str>) -> Result<(), String> // Login installs the context while its transition permit is still held; // this internal persistence step intentionally reads that staged value. let (session, relay_url) = read_account_context_raw().await?; - session_store::save_session_with_device( + session_store::save_issued_session( &session.token, &session.user_id, &session.master_key, @@ -2678,13 +2729,8 @@ async fn connect_route_devices(route: RelayRoute) -> Result bool { + false + } + /// Whether started routing is standing by because another host on this /// machine serves the shared device on the Relay. async fn device_routing_is_standby(&self) -> bool { @@ -130,6 +134,8 @@ pub struct AccountRuntime { account_context_transitions: AtomicUsize, account_login_lock: Mutex<()>, account_context_transition_lock: Mutex<()>, + renewal_started: AtomicBool, + renewal_wake: Arc, routing_recovery_generation: AtomicU64, token_expired: AtomicBool, } @@ -143,6 +149,8 @@ impl AccountRuntime { account_context_transitions: AtomicUsize::new(0), account_login_lock: Mutex::new(()), account_context_transition_lock: Mutex::new(()), + renewal_started: AtomicBool::new(false), + renewal_wake: Arc::new(tokio::sync::Notify::new()), routing_recovery_generation: AtomicU64::new(0), token_expired: AtomicBool::new(false), }) @@ -229,7 +237,66 @@ impl AccountRuntime { self.read_account_context().await.is_ok() } + async fn maintain_device_session(&self) -> Result<()> { + let generation = self.account_context_generation(); + let Ok((old, relay_url)) = self.read_account_context_for_generation(generation).await + else { + return Ok(()); + }; + let Some(saved) = session_store::renew_session_if_due(self.host.is_cli_host()).await? + else { + return Ok(()); + }; + if !saved.replaces(&old, &relay_url) { + return Ok(()); + } + let Some(transition) = self.begin_account_transition_if_current(generation).await else { + return Ok(()); + }; + let reconnect = self.host.device_routing_is_active().await; + let session = AccountSession::new(saved.token, saved.user_id, saved.master_key); + *self.account_context.write().await = Some(AccountContextState { + session: session.clone(), + relay_url: relay_url.clone(), + }); + let generation = transition.finish(); + if reconnect { + self.host + .start_device_routing(AccountRoutingStartRequest { + session, + relay_url, + device_name: current_device_identity()?.device_name, + account_generation: generation, + }) + .await?; + } + Ok(()) + } + pub async fn try_restore_session(self: &Arc) -> Option { + if !self.renewal_started.swap(true, Ordering::AcqRel) { + let error = session_store::renew_session_if_due(self.host.is_cli_host()) + .await + .err(); + if let Some(error) = &error { + log::warn!("Startup device credential maintenance failed: {error}"); + } + let weak = Arc::downgrade(self); + session_store::schedule_renewal_checks( + self.renewal_wake.clone(), + error.is_some(), + move || { + let runtime = weak.upgrade(); + async move { + let Some(runtime) = runtime else { + return Ok(false); + }; + runtime.maintain_device_session().await?; + Ok(true) + } + }, + ); + } if let Ok(Some(loaded)) = session_store::load_session_detailed() { if openbitfun_services_integrations::remote_connect::account::persisted_relay_requires_migration( &loaded.relay_url, @@ -418,7 +485,7 @@ impl AccountRuntime { session_store::save_credential_hint(&profile.login, &relay_url); self.token_expired.store(false, Ordering::Relaxed); - if let Err(error) = session_store::save_session_with_device( + if let Err(error) = session_store::save_issued_session( &token, &user_id, &master_key, @@ -495,6 +562,18 @@ impl AccountRuntime { account_generation: u64, expected_token: &str, ) -> bool { + if let Ok((session, relay)) = self + .read_account_context_for_generation(account_generation) + .await + { + if session.token != expected_token { + return false; + } + if session_store::has_saved_replacement(&session, &relay) { + self.renewal_wake.notify_one(); + return false; + } + } let Some(transition) = self .begin_account_transition_if_current(account_generation) .await @@ -523,7 +602,9 @@ impl AccountRuntime { } } self.token_expired.store(true, Ordering::Relaxed); - session_store::clear_session(); + if let Err(error) = session_store::clear_rejected_session(expected_token) { + log::warn!("Failed to clear rejected session: {error}"); + } transition.finish(); true } diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs index 7dd492997e..1f736ca4f5 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs @@ -19,7 +19,8 @@ use crate::service_agent_runtime::{ }; use log::{error, info, warn}; use serde_json::Value; -use std::sync::{Arc, OnceLock}; +#[cfg(test)] +use std::sync::Arc; pub use super::locale::{current_bot_language, BotLanguage}; use super::locale::{fmt_count, strings_for, BotStrings}; @@ -60,35 +61,8 @@ const REMOTE_POLL_MAX_BACKOFF: std::time::Duration = std::time::Duration::from_s // ── Global delegated identity provider (set by desktop layer) ───── -/// Returns `(relay_url, token, master_key)` if the desktop is logged into an -/// account. Set by the desktop layer via `set_delegated_identity_provider` so -/// the bot can inherit the account identity when pairing succeeds, enabling -/// multi-device control without going through the room channel. -type DelegateFn = Arc< - dyn Fn() -> std::pin::Pin< - Box)>> + Send>, - > + Send - + Sync, ->; - -static DELEGATE_PROVIDER: OnceLock = OnceLock::new(); - -/// Called by the desktop layer after account login. Installs a closure that -/// returns `(relay_url, delegated_token, master_key_bytes)` on demand. -pub fn set_delegated_identity_provider(f: F) -where - F: Fn() -> Fut + Send + Sync + 'static, - Fut: std::future::Future)>> + Send + 'static, -{ - let _ = DELEGATE_PROVIDER.set(Arc::new(move || Box::pin(f()))); -} - -/// Try to obtain the delegated identity from the global provider. Returns -/// `None` if the desktop is not logged in or the provider is not set. -async fn try_get_delegated_identity() -> Option<(String, String, Vec)> { - let provider = DELEGATE_PROVIDER.get()?; - provider().await -} +use openbitfun_services_integrations::remote_connect::bot::delegation; +pub use openbitfun_services_integrations::remote_connect::bot::delegation::set_delegated_identity_provider; // ── Per-chat state ───────────────────────────────────────────────── @@ -667,9 +641,9 @@ pub async fn complete_im_bot_pairing(state: &mut BotChatState) -> HandleResult { // If the desktop is logged into an account, inject the delegated // identity + relay_url so the bot can use /devices and remote RPC. if state.relay_url.is_none() || !state.has_delegated_identity() { - if let Some((relay_url, token, master_key)) = try_get_delegated_identity().await { + if let Some((relay_url, account)) = delegation::issue().await { state.relay_url = Some(relay_url); - state.set_delegated_identity(token, master_key); + state.delegated_account = Some(account); info!("Bot inherited account identity for multi-device control"); } } @@ -997,11 +971,10 @@ fn devices_unavailable_view(s: &'static BotStrings) -> MenuView { } async fn list_devices(state: &mut BotChatState, s: &'static BotStrings) -> HandleResult { - // Lazy-inject delegated identity if not yet set (e.g. after restart restore). - if state.relay_url.is_none() { - if let Some((relay_url, token, master_key)) = try_get_delegated_identity().await { - state.relay_url = Some(relay_url); - state.set_delegated_identity(token, master_key); + if !state.has_delegated_identity() || state.relay_url.is_none() { + if let Some((relay, account)) = delegation::issue().await { + state.relay_url = Some(relay); + state.delegated_account = Some(account); } } let Some(relay_url) = state.relay_url.clone() else { @@ -1011,8 +984,7 @@ async fn list_devices(state: &mut BotChatState, s: &'static BotStrings) -> Handl return result_from_menu(state, devices_unavailable_view(s)); }; - let client = crate::service::remote_connect::AccountClient::new(); - let devices = match client.list_devices(&relay_url, session).await { + let devices = match session.list_devices(&relay_url).await { Ok(d) => d, Err(e) => { error!("Bot list_devices failed: {e}"); @@ -1120,10 +1092,13 @@ async fn exec_remote_rpc(state: &BotChatState, command_json: &str) -> Result bool { .is_some_and(|ip| ip.is_private() || ip.is_loopback() || ip.is_link_local()) } +#[derive(Debug, thiserror::Error)] +#[error("{0}")] +pub struct RelayUnauthorized(String); + /// Check whether an account/relay error message indicates an invalid or /// expired account token (relay auth failure). Shared by Desktop, CLI, and /// account surfaces so they all react to the same relay wording. @@ -459,9 +463,9 @@ pub fn validate_relay_base_url(relay_url: &str) -> Result { (Some(version), None) if !version.is_empty() && version.len() <= 32 - && version - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-')) => + && version.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-') + }) => { true } @@ -566,6 +570,20 @@ impl AccountClient { ) -> Result<( AccountSession, openbitfun_product_domains::account::GitHubUser, + )> { + self.exchange_identity(relay_url, device, device_kind, None) + .await + } + + pub(super) async fn exchange_identity( + &self, + relay_url: &str, + device: &DeviceIdentity, + device_kind: &str, + previous: Option<&super::session_store::LoadedSession>, + ) -> Result<( + AccountSession, + openbitfun_product_domains::account::GitHubUser, )> { let mut identity = crate::account_identity::AccountIdentityClient::from_environment().await?; @@ -581,8 +599,11 @@ impl AccountClient { .user .identity_id() .ok_or_else(|| anyhow!("Unsupported account identity"))?; - let device_secret = - super::session_store::device_secret(relay_url, &account_id, &device.device_id)?; + let device_secret = match previous { + Some(saved) if saved.user_id == account_id => saved.master_key, + Some(_) => return Err(anyhow!("Sign in with the original device account to renew")), + None => super::session_store::device_secret(relay_url, &account_id, &device.device_id)?, + }; let body = login_request_body( &access_token, device, @@ -654,7 +675,7 @@ impl AccountClient { "relay returned HTTP 507 Insufficient Storage (the configured account or asset quota is full)" ); } - match serde_json::from_slice::(body) { + let error = match serde_json::from_slice::(body) { Ok(body) => { let msg = body.error; if let Some(retry) = body.retry_after_secs { @@ -664,6 +685,11 @@ impl AccountClient { } } Err(_) => anyhow!("relay returned HTTP {status}"), + }; + if status == reqwest::StatusCode::UNAUTHORIZED { + RelayUnauthorized(error.to_string()).into() + } else { + error } } diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/delegation.rs b/src/crates/services/services-integrations/src/remote_connect/bot/delegation.rs new file mode 100644 index 0000000000..a9b60a88d1 --- /dev/null +++ b/src/crates/services/services-integrations/src/remote_connect/bot/delegation.rs @@ -0,0 +1,201 @@ +//! A chat and its in-flight turns share the same renewable control credential. +use crate::remote_connect::account::{ + AccountClient, AccountSession, DeviceInfo, RelayUnauthorized, +}; +use anyhow::{anyhow, Result}; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, OnceLock}; +use tokio::sync::Mutex; + +type Issued = (String, AccountSession); +type Provider = Arc Pin> + Send>> + Send + Sync>; +static PROVIDER: OnceLock = OnceLock::new(); +const LIFETIME: i64 = 24 * 3600; + +pub fn set_delegated_identity_provider(f: F) +where + F: Fn() -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, +{ + let _ = PROVIDER.set(Arc::new(move || Box::pin(f()))); +} + +pub async fn issue() -> Option<(String, Delegation)> { + let (url, session) = PROVIDER.get()?().await?; + Some((url, session.into())) +} + +#[derive(Debug, Clone)] +pub struct Delegation(Arc>); + +#[derive(Debug)] +struct Credential { + session: AccountSession, + issued_at: i64, + retry_at: i64, +} + +impl From for Delegation { + fn from(session: AccountSession) -> Self { + Self(Arc::new(Mutex::new(Credential { + session, + issued_at: chrono::Utc::now().timestamp(), + retry_at: 0, + }))) + } +} + +impl Delegation { + pub async fn session(&self, url: &str) -> Result { + self.refresh(url, None, PROVIDER.get()).await + } + + async fn refresh( + &self, + url: &str, + rejected: Option<&str>, + provider: Option<&Provider>, + ) -> Result { + let mut current = self.0.lock().await; + let now = chrono::Utc::now().timestamp(); + let age = now.saturating_sub(current.issued_at); + let rejected_here = rejected == Some(current.session.token.as_str()); + if !rejected_here && (0..LIFETIME / 2).contains(&age) { + return Ok(current.session.clone()); + } + if now >= current.retry_at { + if let Some(provider) = provider { + if let Some((relay, session)) = provider().await { + if !openbitfun_product_domains::account::same_relay_deployment(&relay, url) + || session.user_id != current.session.user_id + { + anyhow::bail!("Bot account changed during credential renewal"); + } + *current = Credential { + session, + issued_at: now, + retry_at: 0, + }; + return Ok(current.session.clone()); + } + } + current.retry_at = now + 60; + } + if !rejected_here && (0..LIFETIME).contains(&age) { + return Ok(current.session.clone()); + } + Err(anyhow!( + "Could not renew the bot credential. Check the host account and Relay connection." + )) + } + + pub async fn list_devices(&self, relay: &str) -> Result> { + self.list_devices_with(relay, PROVIDER.get()).await + } + + async fn list_devices_with( + &self, + relay: &str, + provider: Option<&Provider>, + ) -> Result> { + let client = AccountClient::new(); + let session = self.refresh(relay, None, provider).await?; + match client.list_devices(relay, &session).await { + Err(error) if error.is::() => { + let replacement = self.refresh(relay, Some(&session.token), provider).await?; + client.list_devices(relay, &replacement).await + } + result => result, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn session(token: &str, user: &str) -> AccountSession { + AccountSession::new(token.into(), user.into(), [1; 32]) + } + + fn issuer(url: String, user: &'static str) -> Provider { + Arc::new(move || { + Box::pin(std::future::ready(Some(( + url.clone(), + session("replacement", user), + )))) + }) + } + + #[tokio::test] + async fn a_remote_turn_and_its_chat_share_renewal_and_keep_their_original_owner() { + let relay = "http://localhost"; + let chat = Delegation::from(session("original", "alice")); + let turn = chat.clone(); + let provider = issuer(relay.into(), "alice"); + assert_eq!( + chat.refresh(relay, None, Some(&provider)) + .await + .unwrap() + .token, + "original" + ); + chat.0.lock().await.issued_at -= LIFETIME / 2; + assert!(turn + .refresh(relay, None, Some(&issuer(relay.into(), "bob"))) + .await + .is_err()); + assert_eq!( + turn.refresh(relay, None, Some(&provider)) + .await + .unwrap() + .token, + "replacement" + ); + assert_eq!( + chat.refresh(relay, Some("original"), None) + .await + .unwrap() + .token, + "replacement" + ); + } + + #[tokio::test] + async fn device_list_retries_once_with_a_fresh_delegation_after_401() { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + for second_status in ["200 OK", "401 Unauthorized"] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + for (token, status) in [ + ("original", "401 Unauthorized"), + ("replacement", second_status), + ] { + let (socket, _) = listener.accept().await.unwrap(); + let mut stream = BufReader::new(socket); + let mut headers = String::new(); + while !headers.ends_with("\r\n\r\n") { + assert!(stream.read_line(&mut headers).await.unwrap() > 0); + } + assert!(headers.starts_with("GET /api/devices ")); + assert!(headers + .to_ascii_lowercase() + .contains(&format!("authorization: bearer {token}"))); + let reply = format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n[]"); + stream.get_mut().write_all(reply.as_bytes()).await.unwrap(); + } + }); + let account = Delegation::from(session("original", "alice")); + let provider = issuer(url.clone(), "alice"); + let result = account.list_devices_with(&url, Some(&provider)).await; + server.await.unwrap(); + if second_status == "200 OK" { + assert!(result.unwrap().is_empty()); + } else { + assert!(result.unwrap_err().is::()); + } + } + } +} diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs b/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs index 6d062e3511..6bd44dac46 100644 --- a/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs +++ b/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs @@ -4,6 +4,7 @@ //! concrete session/runtime dependencies are reduced to service ports. mod command; +pub mod delegation; pub mod delivery; pub mod feishu; pub mod inbound_files; diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/remote_turn.rs b/src/crates/services/services-integrations/src/remote_connect/bot/remote_turn.rs index 483dce7bc1..13124b204f 100644 --- a/src/crates/services/services-integrations/src/remote_connect/bot/remote_turn.rs +++ b/src/crates/services/services-integrations/src/remote_connect/bot/remote_turn.rs @@ -47,10 +47,15 @@ impl RemoteBotTarget { } async fn rpc_response(&self, command: Value) -> Result { + let session = self + .account + .session(&self.relay_url) + .await + .map_err(|e| e.to_string())?; let reply = AccountClient::new() .device_rpc( &self.relay_url, - &self.account, + &session, &self.device_id, &command.to_string(), ) diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/state.rs b/src/crates/services/services-integrations/src/remote_connect/bot/state.rs index 0cb3fc5833..7836f622d2 100644 --- a/src/crates/services/services-integrations/src/remote_connect/bot/state.rs +++ b/src/crates/services/services-integrations/src/remote_connect/bot/state.rs @@ -189,7 +189,7 @@ pub struct BotChatState { /// A chat's in-memory controller identity. Clones for submitted turns /// share its connection and per-peer encoding offers. #[serde(skip)] - pub delegated_account: Option, + pub delegated_account: Option, /// When Some, the bot operates on a remote device via HTTP RPC instead /// of the local desktop. Set by `/devices` → pick a device. /// Cleared by `/devices` → pick "local" or selecting an offline device. @@ -220,7 +220,7 @@ pub struct RemoteBotTarget { pub device_id: String, pub device_name: String, pub session_id: String, - pub account: crate::remote_connect::account::AccountSession, + pub account: super::delegation::Delegation, } impl BotChatState { @@ -305,7 +305,7 @@ impl BotChatState { /// The master key is kept in memory only; callers must never persist it. pub fn set_delegated_identity(&mut self, token: String, master_key: Vec) { self.delegated_account = match <[u8; MASTER_KEY_LEN]>::try_from(master_key) { - Ok(key) => Some(AccountSession::new(token, String::new(), key)), + Ok(key) => Some(AccountSession::new(token, String::new(), key).into()), Err(key) => { log::warn!("Invalid delegated device key length: {}", key.len()); None diff --git a/src/crates/services/services-integrations/src/remote_connect/session_store.rs b/src/crates/services/services-integrations/src/remote_connect/session_store.rs index 4cd44f5022..7d01ecaea4 100644 --- a/src/crates/services/services-integrations/src/remote_connect/session_store.rs +++ b/src/crates/services/services-integrations/src/remote_connect/session_store.rs @@ -31,7 +31,14 @@ pub fn set_session_store_directory_for_test(path: PathBuf) { *override_path = Some(path); } +#[cfg(test)] +thread_local! { static TEST_STORE: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } + fn session_store_directory() -> Result { + #[cfg(test)] + if let Some(dir) = TEST_STORE.with(|dir| dir.borrow().clone()) { + return Ok(dir); + } let override_path = session_store_directory_override() .read() .unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -71,7 +78,53 @@ pub fn save_session( save_session_with_device(token, user_id, master_key, relay_url, None) } -/// Persist the session including the account-bound `device_id`. +pub use crate::remote_persistence::AccountSessionRecord as LoadedSession; + +pub const WEEK: std::time::Duration = std::time::Duration::from_secs(7 * 86400); +pub const RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(3600); +const DEVICE_TOKEN_LIFETIME: i64 = 30 * 86400; + +impl LoadedSession { + pub fn replaces(&self, session: &super::account::AccountSession, relay: &str) -> bool { + self.token != session.token + && self.user_id == session.user_id + && self.master_key == session.master_key + && openbitfun_product_domains::account::same_relay_deployment(&self.relay_url, relay) + } +} + +fn renewal_due(issued_at: Option, now: i64) -> bool { + issued_at + .is_none_or(|issued| issued > now || now.saturating_sub(issued) > DEVICE_TOKEN_LIFETIME / 2) +} + +fn lock_file(name: &str) -> Result { + let directory = session_store_directory()?; + std::fs::create_dir_all(&directory)?; + Ok(std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(directory.join(name))?) +} + +// Held only for the synchronous compare-and-write, including across Desktop/CLI. +fn state_lock() -> Result { + let file = lock_file("account_session.lock")?; + fs2::FileExt::lock_exclusive(&file)?; + Ok(file) +} + +fn write_record(session: &LoadedSession) -> Result<()> { + crate::remote_persistence::write_current_account_session( + &session_store_directory()?, + &crate::remote_persistence::MachineBinding::current(), + session, + ) +} + +/// Import a relay credential without inferring when it was issued. pub fn save_session_with_device( token: &str, user_id: &str, @@ -79,31 +132,155 @@ pub fn save_session_with_device( relay_url: &str, device_id: Option<&str>, ) -> Result<()> { - let payload = crate::remote_persistence::AccountSessionRecord { - token: token.to_string(), - user_id: user_id.to_string(), + save_record(token, user_id, master_key, relay_url, device_id, None) +} + +/// Store the issue time only after a successful identity exchange. +pub fn save_issued_session( + token: &str, + user_id: &str, + master_key: &[u8; 32], + relay_url: &str, + device_id: Option<&str>, +) -> Result<()> { + save_record( + token, + user_id, + master_key, + relay_url, + device_id, + Some(chrono::Utc::now().timestamp()), + ) +} + +fn save_record( + token: &str, + user_id: &str, + master_key: &[u8; 32], + relay_url: &str, + device_id: Option<&str>, + issued_at: Option, +) -> Result<()> { + let _guard = state_lock()?; + write_record(&LoadedSession { + token: token.to_owned(), + user_id: user_id.to_owned(), master_key: *master_key, - relay_url: relay_url.to_string(), - device_id: device_id - .map(str::trim) - .filter(|id| !id.is_empty()) - .map(str::to_string), + relay_url: relay_url.to_owned(), + device_id: device_id.map(str::to_owned), + issued_at, + }) +} + +/// AuthOk can arrive long after issuance and after another host rotated the token. +pub fn record_authenticated_device(token: &str, device_id: &str) -> Result<()> { + let _guard = state_lock()?; + if let Some(mut saved) = load_session_detailed()? { + if saved.token == token && saved.device_id.as_deref() != Some(device_id) { + saved.device_id = Some(device_id.to_owned()); + write_record(&saved)?; + } + } + Ok(()) +} + +/// Refresh a persisted device using the host's existing signed-in account. +pub async fn renew_session_if_due(host_is_cli: bool) -> Result> { + use super::account::{persisted_relay_requires_migration, AccountClient, AccountSession}; + let Some(saved) = load_session_detailed()? else { + return Ok(None); }; - crate::remote_persistence::write_current_account_session( - &session_store_directory()?, - &crate::remote_persistence::MachineBinding::current(), - &payload, - ) + if persisted_relay_requires_migration(&saved.relay_url) + || !renewal_due(saved.issued_at, chrono::Utc::now().timestamp()) + { + return Ok(Some(saved)); + } + let renewing = lock_file("account_renewal.lock")?; + fs2::FileExt::try_lock_exclusive(&renewing)?; + // Another host may have completed renewal since our first read. + let current = load_session_detailed()?; + if !current + .as_ref() + .is_some_and(|record| record.token == saved.token) + { + return Ok(current); + } + let client = AccountClient::new(); + let session = AccountSession::new(saved.token.clone(), saved.user_id.clone(), saved.master_key); + // Never silently re-register a device whose credential has been revoked. + client.list_devices(&saved.relay_url, &session).await?; + let mut device = super::DeviceIdentity::from_current_machine()?; + if let Some(id) = saved.device_id.as_ref() { + device.device_id.clone_from(id); + } + let kind = client + .reported_device_kind(&saved.relay_url, host_is_cli) + .await; + let issued_at = chrono::Utc::now().timestamp(); + let (new_session, _) = client + .exchange_identity(&saved.relay_url, &device, kind, Some(&saved)) + .await?; + let committed = replace_renewed_session( + &saved.token, + &new_session.token, + &device.device_id, + issued_at, + ); + if !matches!(&committed, Ok(Some(current)) if current.token == new_session.token) { + if let Err(error) = client.revoke_token(&saved.relay_url, &new_session).await { + log::warn!("Failed to revoke unused renewal credential: {error}"); + } + } + committed +} + +fn replace_renewed_session( + previous: &str, + token: &str, + device: &str, + issued_at: i64, +) -> Result> { + let _guard = state_lock()?; + let mut current = load_session_detailed()?; + if let Some(saved) = current.as_mut().filter(|saved| saved.token == previous) { + saved.token = token.to_owned(); + saved.device_id = Some(device.to_owned()); + saved.issued_at = Some(issued_at); + write_record(saved)?; + } + Ok(current) +} + +/// A different process may already have replaced a locally rejected credential. +pub fn has_saved_replacement(session: &super::account::AccountSession, relay: &str) -> bool { + matches!(load_session_detailed(), Ok(Some(saved)) if saved.replaces(session, relay)) } -/// Loaded account session fields from disk. -#[derive(Debug, Clone)] -pub struct LoadedSession { - pub token: String, - pub user_id: String, - pub master_key: [u8; 32], - pub relay_url: String, - pub device_id: Option, +/// Start a single maintenance loop for an owning host. A dropped host exits on its next tick. +pub fn schedule_renewal_checks( + wake: std::sync::Arc, + mut retry: bool, + mut check: F, +) where + F: FnMut() -> Fut + Send + 'static, + Fut: std::future::Future> + Send, +{ + tokio::spawn(async move { + loop { + tokio::select! { + _ = tokio::time::sleep(if retry { RETRY_DELAY } else { WEEK }) => {}, + _ = wake.notified() => {}, + } + match check().await { + Ok(false) => break, + Ok(true) => retry = false, + Err(error) => { + log::warn!("Device credential maintenance failed: {error}"); + retry = true; + } + } + } + }); } /// Load and decrypt the session from disk. @@ -114,26 +291,27 @@ pub fn load_session() -> Result> { /// Load and decrypt the session, including optional account-bound `device_id`. pub fn load_session_detailed() -> Result> { - Ok(crate::remote_persistence::read_current_account_session( + crate::remote_persistence::read_current_account_session( &session_store_directory()?, &crate::remote_persistence::MachineBinding::current(), - )? - .map(|payload| LoadedSession { - token: payload.token, - user_id: payload.user_id, - master_key: payload.master_key, - relay_url: payload.relay_url, - device_id: payload.device_id, - })) + ) } /// Remove the persisted session file (called on logout). pub fn clear_session() { - if let Ok(path) = session_file_path() { + if let (Ok(_guard), Ok(path)) = (state_lock(), session_file_path()) { let _ = std::fs::remove_file(&path); } } +pub fn clear_rejected_session(token: &str) -> Result<()> { + let _guard = state_lock()?; + if load_session_detailed()?.is_some_and(|saved| saved.token == token) { + std::fs::remove_file(session_file_path()?)?; + } + Ok(()) +} + // ── Credential hint (non-secret: username + relay_url) ───────────────── // Shared by Desktop and CLI so login forms pre-fill the same values. @@ -169,6 +347,112 @@ pub fn clear_credential_hint() { } } +#[cfg(test)] +mod renewal_tests { + use super::*; + + #[test] + fn device_renewal_uses_the_issue_time_across_weekly_checks() { + let day = 86400; + assert_eq!(WEEK.as_secs(), 7 * day as u64); + assert!(RETRY_DELAY < WEEK); + for age in [0, 7 * day, 14 * day, 15 * day] { + assert!(!renewal_due(Some(0), age)); + } + for age in [15 * day + 1, 21 * day, 30 * day] { + assert!(renewal_due(Some(0), age)); + } + assert!(renewal_due(None, day)); + assert!(renewal_due(Some(day + 1), day)); + } + + #[tokio::test] + async fn a_stale_host_can_wake_the_weekly_check_immediately() { + let wake = std::sync::Arc::new(tokio::sync::Notify::new()); + let completed = std::sync::Arc::new(tokio::sync::Notify::new()); + let signal = completed.clone(); + schedule_renewal_checks(wake.clone(), false, move || { + signal.notify_one(); + std::future::ready(Ok(false)) + }); + wake.notify_one(); + tokio::time::timeout(std::time::Duration::from_secs(3), completed.notified()) + .await + .unwrap(); + } + + #[tokio::test] + async fn startup_skips_fresh_credentials_and_preserves_a_legacy_record_on_rejection() { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + let temp = tempfile::tempdir().unwrap(); + TEST_STORE.with(|dir| *dir.borrow_mut() = Some(temp.path().to_owned())); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + let id = "0123456789abcdef0123456789abcdef"; + save_issued_session("fresh", "me", &[2; 32], &relay, Some(id)).unwrap(); + assert_eq!( + renew_session_if_due(true).await.unwrap().unwrap().token, + "fresh" + ); + save_session_with_device("legacy", "me", &[2; 32], &relay, Some(id)).unwrap(); + let before = load_session_detailed().unwrap(); + let server = tokio::spawn(async move { + let (socket, _) = listener.accept().await.unwrap(); + let mut stream = BufReader::new(socket); + let mut request = String::new(); + while !request.ends_with("\r\n\r\n") { + assert!(stream.read_line(&mut request).await.unwrap() > 0); + } + assert!(request.starts_with("GET /api/devices ")); + stream + .get_mut() + .write_all( + b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + }); + assert!(renew_session_if_due(false) + .await + .unwrap_err() + .is::()); + server.await.unwrap(); + assert_eq!(load_session_detailed().unwrap(), before); + TEST_STORE.with(|dir| *dir.borrow_mut() = None); + } + + #[test] + fn auth_ok_and_stale_hosts_cannot_overwrite_a_renewal_or_logout() { + let temp = tempfile::tempdir().unwrap(); + // Scope this test's store to its own thread, independently of API fixtures. + TEST_STORE.with(|dir| *dir.borrow_mut() = Some(temp.path().to_owned())); + let id = "0123456789abcdef0123456789abcdef"; + let relay = openbitfun_product_domains::account::DEFAULT_RELAY_URL; + save_session("old", "account", &[1; 32], relay).unwrap(); + record_authenticated_device("old", id).unwrap(); + assert_eq!(load_session_detailed().unwrap().unwrap().issued_at, None); + let renewed = replace_renewed_session("old", "new", id, 1234) + .unwrap() + .unwrap(); + assert!(renewed.replaces( + &super::super::account::AccountSession::new("old".into(), "account".into(), [1; 32]), + relay.split('?').next().unwrap() + )); + record_authenticated_device("old", "wrong-id").unwrap(); + record_authenticated_device("new", id).unwrap(); + clear_rejected_session("old").unwrap(); + assert_eq!( + replace_renewed_session("old", "stale", id, 9999).unwrap(), + Some(renewed) + ); + clear_session(); + assert!(replace_renewed_session("new", "stale", id, 9999) + .unwrap() + .is_none()); + TEST_STORE.with(|dir| *dir.borrow_mut() = None); + } +} + #[cfg(all(test, unix))] mod tests { use std::os::unix::fs::PermissionsExt; diff --git a/src/crates/services/services-integrations/src/remote_persistence.rs b/src/crates/services/services-integrations/src/remote_persistence.rs index 89493b51ce..9b4e066b3f 100644 --- a/src/crates/services/services-integrations/src/remote_persistence.rs +++ b/src/crates/services/services-integrations/src/remote_persistence.rs @@ -57,6 +57,7 @@ pub struct AccountSessionRecord { pub master_key: [u8; 32], pub relay_url: String, pub device_id: Option, + pub issued_at: Option, } impl std::fmt::Debug for AccountSessionRecord { @@ -110,6 +111,8 @@ struct AccountSessionPayload { relay_url: String, #[serde(default, skip_serializing_if = "Option::is_none")] device_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + issued_at: Option, } /// Whether a stored account session belongs to the same deployed Relay. @@ -234,6 +237,7 @@ pub fn write_current_account_session( master_key_b64: BASE64.encode(session.master_key), relay_url: session.relay_url.clone(), device_id: session.device_id.clone(), + issued_at: session.issued_at, }; let plaintext = serde_json::to_vec(&payload).context("serialize account session payload")?; let key = derive_current_key(binding, &secret); @@ -282,6 +286,7 @@ fn decode_account_session_payload(bytes: &[u8]) -> Result master_key, relay_url: payload.relay_url, device_id: payload.device_id, + issued_at: payload.issued_at, }; validate_account_session(&session)?; Ok(session) @@ -1132,6 +1137,7 @@ mod tests { v2: b"|retired-product::session_store::v2|", }; let session = AccountSessionRecord { + issued_at: None, token: "synthetic-token".to_string(), user_id: "fixture-account".to_string(), master_key: [0x42; 32], @@ -1264,6 +1270,7 @@ mod tests { master_key_b64: BASE64.encode(session.master_key), relay_url: session.relay_url.clone(), device_id: session.device_id.clone(), + issued_at: session.issued_at, }; let plaintext = serde_json::to_vec(&payload).unwrap(); let key = derive_legacy_v2_key(binding, local_secret, domains); From 72fecf3e90c7d5add0d9af0de22080f7e3a02495 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Wed, 18 Nov 2026 21:22:54 +0800 Subject: [PATCH 3/6] fix(dispatch): allow rechecking externally installed SSH targets --- scripts/release-channel.test.mjs | 18 ++++---- .../dispatch/DispatchTargetDialog.test.tsx | 1 + .../dispatch/DispatchTargetDialog.tsx | 46 +++++++++---------- 3 files changed, 32 insertions(+), 33 deletions(-) diff --git a/scripts/release-channel.test.mjs b/scripts/release-channel.test.mjs index 5330f71014..405c31b6b5 100644 --- a/scripts/release-channel.test.mjs +++ b/scripts/release-channel.test.mjs @@ -191,17 +191,15 @@ function writeFixture(root, relative, content) { } -test('Desktop, CLI and SSH dispatch consume only the versioned stable feeds', () => { +test('Desktop and CLI updaters consume the versioned stable feeds', () => { const stable = resolveReleaseChannel('stable'); - for (const file of [ - 'src/apps/desktop/src/api/system_api.rs', - 'src/crates/services/services-integrations/src/remote_ssh/dispatch_ssh.rs', - ]) { - const source = readFileSync(new URL(`../${file}`, import.meta.url), 'utf8'); - assert.ok(source.includes(stable.primaryUpdaterEndpoint), file); - assert.ok(source.includes(stable.fallbackUpdaterEndpoint), file); - assert.doesNotMatch(source, /https:[^"\s]+\/latest\.json/); - } + const desktop = readFileSync(new URL('../src/apps/desktop/src/api/system_api.rs', import.meta.url), 'utf8'); + assert.ok(desktop.includes(stable.primaryUpdaterEndpoint)); + assert.ok(desktop.includes(stable.fallbackUpdaterEndpoint)); + assert.doesNotMatch(desktop, /https:[^"\s]+\/latest\.json/); + const dispatch = readFileSync(new URL('../src/crates/services/services-integrations/src/remote_ssh/dispatch_ssh.rs', import.meta.url), 'utf8'); + assert.ok(!dispatch.includes(stable.primaryUpdaterEndpoint)); + assert.ok(!dispatch.includes(stable.fallbackUpdaterEndpoint)); const cli = readFileSync(new URL('../src/apps/cli/src/self_update.rs', import.meta.url), 'utf8'); assert.ok(cli.includes(new URL('linux-binaries-v1.json', stable.primaryUpdaterEndpoint).href)); assert.ok(cli.includes('https://openbitfun.com/release/linux-binaries-v1.json')); diff --git a/src/web-ui/src/features/dispatch/DispatchTargetDialog.test.tsx b/src/web-ui/src/features/dispatch/DispatchTargetDialog.test.tsx index 7f8c3e763f..127b6ab182 100644 --- a/src/web-ui/src/features/dispatch/DispatchTargetDialog.test.tsx +++ b/src/web-ui/src/features/dispatch/DispatchTargetDialog.test.tsx @@ -300,6 +300,7 @@ describe('DispatchTargetDialog target preparation', () => { }); expect(container.textContent).toContain('dispatch.cliUnavailable'); + expect(container.textContent).toContain('dispatch.retryCheck'); expect(container.textContent).not.toContain('target uses musl libc'); expect(container.textContent).not.toContain('sourceBuild'); expect(container.textContent).not.toContain('dispatch.oneClickDeploy'); diff --git a/src/web-ui/src/features/dispatch/DispatchTargetDialog.tsx b/src/web-ui/src/features/dispatch/DispatchTargetDialog.tsx index 13deb328cb..250cea61e0 100644 --- a/src/web-ui/src/features/dispatch/DispatchTargetDialog.tsx +++ b/src/web-ui/src/features/dispatch/DispatchTargetDialog.tsx @@ -137,7 +137,7 @@ export const DispatchTargetDialog: React.FC = ({ }; }, [open, targetId]); - // Retires every in-flight probe, model sync, and revision check, so a result + // Retires every in-flight probe and revision check, so a result // that lands after the dialog moved on cannot write to a closed dialog. const invalidatePendingWork = useCallback(() => { generationRef.current += 1; @@ -209,17 +209,15 @@ export const DispatchTargetDialog: React.FC = ({ } if (generation !== generationRef.current) return; // The target chooses where its worktree lands, so nothing is sent here. - const normalizedPath = ''; const request = { - kind: 'ssh' as const, - connectionId: targetId, - workspacePath: normalizedPath, - }; + kind: 'ssh' as const, + connectionId: targetId, + workspacePath: '', + }; onReady({ request, target: { ...request, - workspacePath: normalizedPath, displayName: target.displayName, }, includeUncommitted, @@ -280,22 +278,6 @@ export const DispatchTargetDialog: React.FC = ({ {t('dispatch.checkingTarget')} ) : null} - {probeError ? ( -
- - {t('dispatch.probeFailed')} - - -
- ) : null} {probe ? (
= ({
) : null} + {probeError || (probe && !cliReady) ? ( +
+ {probeError && ( + + {t('dispatch.probeFailed')} + + )} + +
+ ) : null}
From 6dde60fc7b60b0a3c24bf428ada2579ece2e1480 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Wed, 18 Nov 2026 21:23:07 +0800 Subject: [PATCH 4/6] fix(remote-connect): preserve routing and revoke rotated credentials on logout --- src/apps/cli/src/account.rs | 13 +- .../desktop/src/api/remote_connect_api.rs | 111 ++++--- .../service/remote_connect/account_runtime.rs | 74 +++-- .../src/remote_connect/account.rs | 46 +++ .../src/remote_connect/session_store.rs | 283 +++++++++++++++--- .../src/remote_persistence.rs | 14 + 6 files changed, 429 insertions(+), 112 deletions(-) diff --git a/src/apps/cli/src/account.rs b/src/apps/cli/src/account.rs index aea56a0069..aaccedbc35 100644 --- a/src/apps/cli/src/account.rs +++ b/src/apps/cli/src/account.rs @@ -20,7 +20,7 @@ use openbitfun_core::service::remote_connect::account_runtime::{ use openbitfun_core::service::remote_connect::{ self, encryption, relay_client::{ConnectionState, DeviceRoutingPriority, RelayClient, RelayEvent}, - session_store, DeviceIdentity, RemoteServer, + DeviceIdentity, RemoteServer, }; pub(crate) struct CliAccountRuntimeParts { @@ -174,7 +174,7 @@ impl CliAccountRoutingHost { async fn start_routing(&self, request: AccountRoutingStartRequest) -> Result<()> { let runtime = self.runtime()?; - if !runtime.account_context_is_current(request.account_generation) { + if !runtime.device_routing_requested(request.account_generation) { return Err(anyhow!("account context changed")); } self.stop_routing().await; @@ -195,13 +195,13 @@ impl CliAccountRoutingHost { let client = Arc::new(client); { let _routing_guard = self.lifecycle.write().await; - if !runtime.account_context_is_current(request.account_generation) { + if !runtime.device_routing_requested(request.account_generation) { client.disconnect().await; return Err(anyhow!("account context changed")); } *self.relay_client.write().await = Some(client.clone()); } - if !runtime.account_context_is_current(request.account_generation) { + if !runtime.device_routing_requested(request.account_generation) { self.retire_routing_client_if_same(&client).await; client.disconnect().await; return Err(anyhow!("account context changed")); @@ -267,6 +267,9 @@ impl CliAccountRoutingHost { } pub(crate) async fn stop_device_routing(&self) { + if let Ok(runtime) = self.runtime() { + runtime.cancel_device_routing(); + } self.stop_routing().await; } @@ -426,7 +429,7 @@ impl CliAccountRoutingHost { old.close(); } if let Err(error) = - session_store::record_authenticated_device(&session.token, &device_id) + runtime.record_authenticated_device(&session.token, &device_id) { tracing::warn!("Failed to persist AuthOk device_id: {error}"); } diff --git a/src/apps/desktop/src/api/remote_connect_api.rs b/src/apps/desktop/src/api/remote_connect_api.rs index 467bcac78a..35d8f86f66 100644 --- a/src/apps/desktop/src/api/remote_connect_api.rs +++ b/src/apps/desktop/src/api/remote_connect_api.rs @@ -15,7 +15,7 @@ use openbitfun_core::service::remote_connect::{ }; use openbitfun_events::AI_MODEL_CATALOG_UPDATED_EVENT; use openbitfun_services_integrations::remote_connect::account::{ - error_indicates_expired_token, validate_relay_base_url, DEVICE_KIND_DESKTOP, + error_indicates_expired_token, validate_relay_base_url, RoutingIntent, DEVICE_KIND_DESKTOP, }; use openbitfun_services_integrations::remote_connect::{ deploy_page_version_on_relay, join_relay_url, list_pages_from_relay, @@ -294,6 +294,9 @@ async fn stop_and_clear_device_routing(reason: &'static str) { } async fn stop_route_device_routing(route: RelayRoute, reason: &'static str) { + if route == RelayRoute::Official { + ROUTING_INTENT.cancel(); + } route.cancel(); let _lifecycle = route.lifecycle().write().await; clear_device_routing_state_on_route(route); @@ -705,6 +708,7 @@ async fn send_rpc_error( .await; } +static ROUTING_INTENT: RoutingIntent = RoutingIntent::new(); static RENEWAL_WAKE: std::sync::LazyLock> = std::sync::LazyLock::new(|| Arc::new(tokio::sync::Notify::new())); @@ -1414,20 +1418,27 @@ async fn maintain_device_session() -> anyhow::Result { let Some(saved) = session_store::renew_session_if_due(false).await? else { return Ok(true); }; - if !saved.replaces(&old, &relay_url) { - return Ok(true); - } - let Some(transition) = begin_account_transition_if_current(generation).await else { + let generation = if saved.replaces(&old, &relay_url) { + let Some(mut transition) = begin_account_transition_if_current(generation).await else { + return Ok(true); + }; + *get_account_context().write().await = Some(AccountContextState { + session: AccountSession::new(saved.token, saved.user_id, saved.master_key), + relay_url, + }); + transition.make_context_observable(); + let next = account_context_generation(); + ROUTING_INTENT.rotated(generation, next); + next + } else if saved.token == old.token + && device_routing_owner_for_account(generation, &old.token).is_none() + { + generation + } else { return Ok(true); }; - let reconnect = device_routing_owner_for_account(generation, &old.token).is_some(); - *get_account_context().write().await = Some(AccountContextState { - session: AccountSession::new(saved.token, saved.user_id, saved.master_key), - relay_url, - }); - drop(transition); - if reconnect { - account_connect_devices_with_retry() + if ROUTING_INTENT.requested(generation) { + reconnect_requested_devices(generation) .await .map_err(anyhow::Error::msg)?; } @@ -2356,18 +2367,16 @@ fn current_device_identity() -> Result { } /// Persist the in-memory account session so restart restores login. -async fn persist_account_session(device_id: Option<&str>) -> Result<(), String> { +async fn persist_account_session( + device_id: Option<&str>, + previous_host_token: Option<&str>, +) -> Result<(), String> { // Login installs the context while its transition permit is still held; // this internal persistence step intentionally reads that staged value. let (session, relay_url) = read_account_context_raw().await?; - session_store::save_issued_session( - &session.token, - &session.user_id, - &session.master_key, - &relay_url, - device_id, - ) - .map_err(|e| format!("persist session: {e}")) + session_store::save_issued_session(&session, &relay_url, device_id, previous_host_token) + .await + .map_err(|e| format!("persist session: {e}")) } #[tauri::command] @@ -2472,7 +2481,14 @@ async fn login_account_on_relay_for_generation( // Reset the token-expired flag on fresh login TOKEN_EXPIRED.store(false, std::sync::atomic::Ordering::Relaxed); - if let Err(e) = persist_account_session(Some(device.device_id.as_str())).await { + if let Err(e) = persist_account_session( + Some(device.device_id.as_str()), + replaced_account + .as_ref() + .map(|context| context.session.token.as_str()), + ) + .await + { log::warn!("Failed to persist session: {e}"); } register_delegated_identity_providers().await; @@ -2565,17 +2581,10 @@ async fn clear_account_login_state(revoke_relay_token: bool) { if let Some(service) = get_service_holder().read().await.as_ref() { service.clear_bot_delegated_identities().await; } - if revoke_relay_token { - // Best-effort relay revocation must not prevent local logout. - if let Ok((session, relay_url)) = read_account_context_raw().await { - let _ = AccountClient::new() - .revoke_token(&relay_url, &session) - .await; - } - } + let active = read_account_context_raw().await.ok(); *get_account_context().write().await = None; clear_credential_hint(); - session_store::clear_session(); + session_store::logout_session(active, revoke_relay_token).await; TOKEN_EXPIRED.store(false, std::sync::atomic::Ordering::Relaxed); emit_account_event( "account://login-state", @@ -2601,12 +2610,22 @@ pub use openbitfun_core::service::remote_connect::relay_client::DevicePresenceEn const STARTUP_DEVICE_CONNECT_MAX_ATTEMPTS: usize = 5; async fn account_connect_devices_with_retry() -> Result, String> { - let expected_generation = account_context_generation(); + let generation = account_context_generation(); + ROUTING_INTENT.request(generation); + reconnect_requested_devices(generation).await +} + +async fn reconnect_requested_devices( + expected_generation: u64, +) -> Result, String> { for attempt in 1..=STARTUP_DEVICE_CONNECT_MAX_ATTEMPTS { - if !account_context_is_current(expected_generation) { + if !account_context_is_current(expected_generation) + || !ROUTING_INTENT.requested(expected_generation) + { return Err("account context changed".to_string()); } - match account_connect_devices().await { + match connect_route_devices_for_generation(RelayRoute::Official, expected_generation).await + { Ok(devices) => return Ok(devices), Err(error) => { if error_indicates_expired_token(&error) @@ -2636,8 +2655,21 @@ pub async fn account_connect_devices() -> Result, String> } async fn connect_route_devices(route: RelayRoute) -> Result, String> { - let account_generation = route.generation(); + let generation = route.generation(); + if route == RelayRoute::Official { + ROUTING_INTENT.request(generation); + } + connect_route_devices_for_generation(route, generation).await +} + +async fn connect_route_devices_for_generation( + route: RelayRoute, + account_generation: u64, +) -> Result, String> { let operation_guard = route.lock_operation(account_generation).await?; + if route == RelayRoute::Official && !ROUTING_INTENT.requested(account_generation) { + return Err("device routing stopped".to_string()); + } let (session, relay_url) = route.context(account_generation).await?; let identity = current_device_identity()?; let device_name = identity.device_name.clone(); @@ -2729,9 +2761,10 @@ async fn connect_route_devices(route: RelayRoute) -> Result RENEWAL_WAKE.notify_one(), + Ok(false) => {} + Err(error) => log::warn!("Failed to persist AuthOk device_id into session: {error}"), } } diff --git a/src/crates/assembly/core/src/service/remote_connect/account_runtime.rs b/src/crates/assembly/core/src/service/remote_connect/account_runtime.rs index 7570155fd3..f4f7306491 100644 --- a/src/crates/assembly/core/src/service/remote_connect/account_runtime.rs +++ b/src/crates/assembly/core/src/service/remote_connect/account_runtime.rs @@ -13,7 +13,9 @@ use anyhow::{anyhow, Result}; use async_trait::async_trait; use tokio::sync::{Mutex, MutexGuard, RwLock}; -use openbitfun_services_integrations::remote_connect::account::{AccountClient, AccountSession}; +use openbitfun_services_integrations::remote_connect::account::{ + AccountClient, AccountSession, RoutingIntent, +}; use openbitfun_services_integrations::remote_connect::{session_store, DeviceIdentity}; use super::validate_relay_base_url; @@ -134,6 +136,7 @@ pub struct AccountRuntime { account_context_transitions: AtomicUsize, account_login_lock: Mutex<()>, account_context_transition_lock: Mutex<()>, + routing_intent: RoutingIntent, renewal_started: AtomicBool, renewal_wake: Arc, routing_recovery_generation: AtomicU64, @@ -149,6 +152,7 @@ impl AccountRuntime { account_context_transitions: AtomicUsize::new(0), account_login_lock: Mutex::new(()), account_context_transition_lock: Mutex::new(()), + routing_intent: RoutingIntent::new(), renewal_started: AtomicBool::new(false), renewal_wake: Arc::new(tokio::sync::Notify::new()), routing_recovery_generation: AtomicU64::new(0), @@ -237,6 +241,13 @@ impl AccountRuntime { self.read_account_context().await.is_ok() } + pub fn record_authenticated_device(&self, token: &str, device_id: &str) -> Result<()> { + if session_store::record_authenticated_device(token, device_id)? { + self.renewal_wake.notify_one(); + } + Ok(()) + } + async fn maintain_device_session(&self) -> Result<()> { let generation = self.account_context_generation(); let Ok((old, relay_url)) = self.read_account_context_for_generation(generation).await @@ -247,20 +258,25 @@ impl AccountRuntime { else { return Ok(()); }; - if !saved.replaces(&old, &relay_url) { - return Ok(()); - } - let Some(transition) = self.begin_account_transition_if_current(generation).await else { + let (session, generation) = if saved.replaces(&old, &relay_url) { + let Some(transition) = self.begin_account_transition_if_current(generation).await + else { + return Ok(()); + }; + let session = AccountSession::new(saved.token, saved.user_id, saved.master_key); + *self.account_context.write().await = Some(AccountContextState { + session: session.clone(), + relay_url: relay_url.clone(), + }); + let next = transition.finish(); + self.routing_intent.rotated(generation, next); + (session, next) + } else if saved.token == old.token && !self.host.device_routing_is_active().await { + (old, generation) + } else { return Ok(()); }; - let reconnect = self.host.device_routing_is_active().await; - let session = AccountSession::new(saved.token, saved.user_id, saved.master_key); - *self.account_context.write().await = Some(AccountContextState { - session: session.clone(), - relay_url: relay_url.clone(), - }); - let generation = transition.finish(); - if reconnect { + if self.device_routing_requested(generation) { self.host .start_device_routing(AccountRoutingStartRequest { session, @@ -477,7 +493,6 @@ impl AccountRuntime { let user_id = session.user_id.clone(); let token = session.token.clone(); - let master_key = session.master_key; *self.account_context.write().await = Some(AccountContextState { session: session.clone(), relay_url: relay_url.clone(), @@ -486,15 +501,19 @@ impl AccountRuntime { self.token_expired.store(false, Ordering::Relaxed); if let Err(error) = session_store::save_issued_session( - &token, - &user_id, - &master_key, + &session, &relay_url, - Some(device.device_id.as_str()), - ) { + Some(&device.device_id), + previous_account_context + .as_ref() + .map(|context| context.session.token.as_str()), + ) + .await + { log::warn!("Failed to persist session: {error}"); } let generation = transition.finish(); + self.routing_intent.request(generation); let routing = self .host .start_device_routing(AccountRoutingStartRequest { @@ -518,9 +537,18 @@ impl AccountRuntime { }) } + pub fn cancel_device_routing(&self) { + self.routing_intent.cancel(); + } + + pub fn device_routing_requested(&self, generation: u64) -> bool { + self.account_context_is_current(generation) && self.routing_intent.requested(generation) + } + pub async fn restore_device_routing(self: &Arc, device_name: &str) -> Result<()> { let generation = self.account_context_generation(); let (session, relay_url) = self.read_account_context_for_generation(generation).await?; + self.routing_intent.request(generation); self.host .start_device_routing(AccountRoutingStartRequest { session, @@ -539,18 +567,16 @@ impl AccountRuntime { if self.host.request_background_routing_owner_shutdown() { log::info!("Signalled the background account routing owner to shut down"); } - if let Ok((session, relay_url)) = self.read_account_context_raw().await { + let active = self.read_account_context_raw().await.ok(); + if let Some((session, _)) = &active { if let Err(error) = crate::service::filesystem::upload::retire_account_uploads(&session.user_id).await { log::warn!("Failed to clean up retired account uploads: {error}"); } - let _ = AccountClient::new() - .revoke_token(&relay_url, &session) - .await; } *self.account_context.write().await = None; - session_store::clear_session(); + session_store::logout_session(active, true).await; session_store::clear_credential_hint(); self.token_expired.store(false, Ordering::Relaxed); transition.finish(); diff --git a/src/crates/services/services-integrations/src/remote_connect/account.rs b/src/crates/services/services-integrations/src/remote_connect/account.rs index 3c2503b342..9c80524a4d 100644 --- a/src/crates/services/services-integrations/src/remote_connect/account.rs +++ b/src/crates/services/services-integrations/src/remote_connect/account.rs @@ -12,6 +12,35 @@ use crate::remote_connect::relay_http::{ relay_http_client, send_with_retry, BufferedRelayResponse, RelayHttpRetry, }; +/// An explicit routing request follows credential rotation for this account. +/// A user stop or a later login invalidates pending connection retries. +#[derive(Default)] +pub struct RoutingIntent(AtomicU64); + +impl RoutingIntent { + pub const fn new() -> Self { + Self(AtomicU64::new(0)) + } + + pub fn request(&self, generation: u64) { + self.0.store(generation, Ordering::SeqCst); + } + + pub fn cancel(&self) { + self.request(0); + } + + pub fn requested(&self, generation: u64) -> bool { + generation != 0 && self.0.load(Ordering::SeqCst) == generation + } + + pub fn rotated(&self, previous: u64, current: u64) { + let _ = self + .0 + .compare_exchange(previous, current, Ordering::SeqCst, Ordering::SeqCst); + } +} + pub const MASTER_KEY_LEN: usize = 32; /// A retired official deployment has its own credential database. Authenticate @@ -1111,6 +1140,23 @@ fn project_device_list_entry(entry: DeviceListEntry) -> DeviceInfo { mod tests { use super::*; + #[test] + fn only_requested_routing_follows_credential_rotation() { + let intent = RoutingIntent::new(); + intent.rotated(1, 3); + assert!(!intent.requested(3)); + intent.request(3); + intent.rotated(3, 5); + assert!(intent.requested(5)); + assert!(!intent.requested(3)); + intent.cancel(); + intent.rotated(5, 7); + assert!(!intent.requested(7)); + intent.request(9); + intent.rotated(5, 7); + assert!(intent.requested(9)); + } + #[test] fn legacy_embedded_session_migrates_without_capturing_other_private_relays() { for url in [ diff --git a/src/crates/services/services-integrations/src/remote_connect/session_store.rs b/src/crates/services/services-integrations/src/remote_connect/session_store.rs index 7d01ecaea4..d087419bff 100644 --- a/src/crates/services/services-integrations/src/remote_connect/session_store.rs +++ b/src/crates/services/services-integrations/src/remote_connect/session_store.rs @@ -78,6 +78,7 @@ pub fn save_session( save_session_with_device(token, user_id, master_key, relay_url, None) } +use super::account::{AccountClient, AccountSession}; pub use crate::remote_persistence::AccountSessionRecord as LoadedSession; pub const WEEK: std::time::Duration = std::time::Duration::from_secs(7 * 86400); @@ -86,8 +87,11 @@ const DEVICE_TOKEN_LIFETIME: i64 = 30 * 86400; impl LoadedSession { pub fn replaces(&self, session: &super::account::AccountSession, relay: &str) -> bool { - self.token != session.token - && self.user_id == session.user_id + self.token != session.token && self.same_device(session, relay) + } + + fn same_device(&self, session: &AccountSession, relay: &str) -> bool { + self.user_id == session.user_id && self.master_key == session.master_key && openbitfun_product_domains::account::same_relay_deployment(&self.relay_url, relay) } @@ -131,35 +135,6 @@ pub fn save_session_with_device( master_key: &[u8; 32], relay_url: &str, device_id: Option<&str>, -) -> Result<()> { - save_record(token, user_id, master_key, relay_url, device_id, None) -} - -/// Store the issue time only after a successful identity exchange. -pub fn save_issued_session( - token: &str, - user_id: &str, - master_key: &[u8; 32], - relay_url: &str, - device_id: Option<&str>, -) -> Result<()> { - save_record( - token, - user_id, - master_key, - relay_url, - device_id, - Some(chrono::Utc::now().timestamp()), - ) -} - -fn save_record( - token: &str, - user_id: &str, - master_key: &[u8; 32], - relay_url: &str, - device_id: Option<&str>, - issued_at: Option, ) -> Result<()> { let _guard = state_lock()?; write_record(&LoadedSession { @@ -168,25 +143,80 @@ fn save_record( master_key: *master_key, relay_url: relay_url.to_owned(), device_id: device_id.map(str::to_owned), - issued_at, + issued_at: None, + superseded_tokens: Vec::new(), }) } +/// An interactive login replaces the previous credential family. The host +/// separately revokes its in-memory token, which may lag behind the disk. +pub async fn save_issued_session( + session: &AccountSession, + relay: &str, + device_id: Option<&str>, + previous_host_token: Option<&str>, +) -> Result<()> { + let previous = { + let _guard = state_lock()?; + let previous = load_session_detailed()?; + write_record(&LoadedSession { + token: session.token.clone(), + user_id: session.user_id.clone(), + master_key: session.master_key, + relay_url: relay.to_owned(), + device_id: device_id.map(str::to_owned), + issued_at: Some(chrono::Utc::now().timestamp()), + superseded_tokens: Vec::new(), + })?; + previous + }; + if let Some(previous) = previous { + revoke_saved_tokens(previous, previous_host_token, Some(&session.token)).await; + } + Ok(()) +} + +async fn revoke_saved_tokens( + saved: LoadedSession, + host_token: Option<&str>, + new_token: Option<&str>, +) { + let now = chrono::Utc::now().timestamp(); + let tokens = std::iter::once(saved.token).chain( + saved + .superseded_tokens + .into_iter() + .filter(|prior| prior.expires_at > now) + .map(|prior| prior.token), + ); + let client = AccountClient::new(); + for token in tokens { + if Some(token.as_str()) == host_token || Some(token.as_str()) == new_token { + continue; + } + let credential = AccountSession::new(token, saved.user_id.clone(), saved.master_key); + if let Err(error) = client.revoke_token(&saved.relay_url, &credential).await { + log::warn!("Failed to revoke previous device credential: {error}"); + } + } +} + /// AuthOk can arrive long after issuance and after another host rotated the token. -pub fn record_authenticated_device(token: &str, device_id: &str) -> Result<()> { +pub fn record_authenticated_device(token: &str, device_id: &str) -> Result { let _guard = state_lock()?; if let Some(mut saved) = load_session_detailed()? { if saved.token == token && saved.device_id.as_deref() != Some(device_id) { saved.device_id = Some(device_id.to_owned()); write_record(&saved)?; + return Ok(renewal_due(saved.issued_at, chrono::Utc::now().timestamp())); } } - Ok(()) + Ok(false) } /// Refresh a persisted device using the host's existing signed-in account. pub async fn renew_session_if_due(host_is_cli: bool) -> Result> { - use super::account::{persisted_relay_requires_migration, AccountClient, AccountSession}; + use super::account::persisted_relay_requires_migration; let Some(saved) = load_session_detailed()? else { return Ok(None); }; @@ -205,14 +235,16 @@ pub async fn renew_session_if_due(host_is_cli: bool) -> Result issued_at); + let expires_at = saved + .issued_at + .unwrap_or(issued_at) + .saturating_add(DEVICE_TOKEN_LIFETIME); + if expires_at > issued_at { + saved + .superseded_tokens + .push(crate::remote_persistence::SupersededDeviceToken { + token: saved.token.clone(), + expires_at, + }); + } saved.token = token.to_owned(); saved.device_id = Some(device.to_owned()); saved.issued_at = Some(issued_at); @@ -297,10 +346,45 @@ pub fn load_session_detailed() -> Result> { ) } -/// Remove the persisted session file (called on logout). -pub fn clear_session() { - if let (Ok(_guard), Ok(path)) = (state_lock(), session_file_path()) { - let _ = std::fs::remove_file(&path); +/// Atomically retire the saved credential before network revocation. A racing +/// renewal then either appears in this record or discards its own candidate. +fn take_session_for_logout( + active: Option<&(AccountSession, String)>, +) -> Result> { + let _guard = state_lock()?; + let Some(saved) = load_session_detailed()? else { + return Ok(None); + }; + if active.is_some_and(|(session, relay)| !saved.same_device(session, relay)) { + return Ok(None); + } + std::fs::remove_file(session_file_path()?)?; + Ok(Some(saved)) +} + +pub async fn logout_session(active: Option<(AccountSession, String)>, revoke: bool) { + let saved = match take_session_for_logout(active.as_ref()) { + Ok(saved) => saved, + Err(error) => { + log::warn!("Failed to clear saved device credential: {error}"); + None + } + }; + if !revoke { + return; + } + if let Some(saved) = saved { + revoke_saved_tokens( + saved, + active.as_ref().map(|(session, _)| session.token.as_str()), + None, + ) + .await; + } + if let Some((session, relay)) = active { + if let Err(error) = AccountClient::new().revoke_token(&relay, &session).await { + log::warn!("Failed to revoke active device credential: {error}"); + } } } @@ -389,7 +473,14 @@ mod renewal_tests { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let relay = format!("http://{}", listener.local_addr().unwrap()); let id = "0123456789abcdef0123456789abcdef"; - save_issued_session("fresh", "me", &[2; 32], &relay, Some(id)).unwrap(); + save_issued_session( + &AccountSession::new("fresh".into(), "me".into(), [2; 32]), + &relay, + Some(id), + None, + ) + .await + .unwrap(); assert_eq!( renew_session_if_due(true).await.unwrap().unwrap().token, "fresh" @@ -421,6 +512,110 @@ mod renewal_tests { TEST_STORE.with(|dir| *dir.borrow_mut() = None); } + #[tokio::test] + async fn legacy_renewal_waits_for_the_authenticated_device_id() { + let temp = tempfile::tempdir().unwrap(); + TEST_STORE.with(|dir| *dir.borrow_mut() = Some(temp.path().to_owned())); + save_session("legacy", "me", &[2; 32], "http://127.0.0.1:1").unwrap(); + let error = renew_session_if_due(true).await.unwrap_err(); + assert!(error.to_string().contains("confirm the session device ID")); + assert!(!record_authenticated_device("stale", "other").unwrap()); + assert!(load_session_detailed() + .unwrap() + .unwrap() + .device_id + .is_none()); + assert!(record_authenticated_device("legacy", "0123456789abcdef0123456789abcdef").unwrap()); + assert!( + !record_authenticated_device("legacy", "0123456789abcdef0123456789abcdef").unwrap() + ); + TEST_STORE.with(|dir| *dir.borrow_mut() = None); + } + + #[tokio::test] + async fn logout_from_a_stale_host_revokes_all_live_rotations_once() { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + let temp = tempfile::tempdir().unwrap(); + TEST_STORE.with(|dir| *dir.borrow_mut() = Some(temp.path().to_owned())); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + let now = chrono::Utc::now().timestamp(); + save_session_with_device( + "expired", + "me", + &[2; 32], + &relay, + Some("0123456789abcdef0123456789abcdef"), + ) + .unwrap(); + for (old, new, age) in [ + ("expired", "first", 32), + ("first", "second", 16), + ("second", "current", 0), + ] { + replace_renewed_session( + old, + new, + "0123456789abcdef0123456789abcdef", + now - age * 86400, + ) + .unwrap(); + } + let other = AccountSession::new("different".into(), "me".into(), [3; 32]); + assert!(take_session_for_logout(Some(&(other, relay.clone()))) + .unwrap() + .is_none()); + let saved = load_session_detailed().unwrap().unwrap(); + assert_eq!(saved.superseded_tokens.len(), 1); + assert_eq!(saved.superseded_tokens[0].token, "second"); + + let server = tokio::spawn(async move { + let mut revoked = Vec::new(); + for _ in 0..2 { + let (socket, _) = listener.accept().await.unwrap(); + let mut stream = BufReader::new(socket); + let mut request = String::new(); + while !request.ends_with("\r\n\r\n") { + assert!(stream.read_line(&mut request).await.unwrap() > 0); + } + assert!(request.starts_with("POST /api/auth/logout ")); + let token = request + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("authorization") + .then_some(value.trim()) + }) + .unwrap(); + revoked.push(token.to_owned()); + stream + .get_mut() + .write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + } + revoked.sort(); + revoked + }); + let stale = AccountSession::new("second".into(), "me".into(), [2; 32]); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + logout_session(Some((stale, relay)), true).await; + assert_eq!(server.await.unwrap(), ["Bearer current", "Bearer second"]); + }) + .await + .unwrap(); + assert!(load_session_detailed().unwrap().is_none()); + assert!(replace_renewed_session( + "current", + "late", + "0123456789abcdef0123456789abcdef", + now + ) + .unwrap() + .is_none()); + TEST_STORE.with(|dir| *dir.borrow_mut() = None); + } + #[test] fn auth_ok_and_stale_hosts_cannot_overwrite_a_renewal_or_logout() { let temp = tempfile::tempdir().unwrap(); @@ -445,7 +640,7 @@ mod renewal_tests { replace_renewed_session("old", "stale", id, 9999).unwrap(), Some(renewed) ); - clear_session(); + take_session_for_logout(None).unwrap(); assert!(replace_renewed_session("new", "stale", id, 9999) .unwrap() .is_none()); diff --git a/src/crates/services/services-integrations/src/remote_persistence.rs b/src/crates/services/services-integrations/src/remote_persistence.rs index 9b4e066b3f..a4870c990a 100644 --- a/src/crates/services/services-integrations/src/remote_persistence.rs +++ b/src/crates/services/services-integrations/src/remote_persistence.rs @@ -50,6 +50,13 @@ pub struct AccountHintRecord { pub relay_url: String, } +/// Unexpired device tokens still in use by other processes during rotation. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SupersededDeviceToken { + pub token: String, + pub expires_at: i64, +} + #[derive(Clone, PartialEq, Eq)] pub struct AccountSessionRecord { pub token: String, @@ -58,6 +65,7 @@ pub struct AccountSessionRecord { pub relay_url: String, pub device_id: Option, pub issued_at: Option, + pub superseded_tokens: Vec, } impl std::fmt::Debug for AccountSessionRecord { @@ -113,6 +121,8 @@ struct AccountSessionPayload { device_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] issued_at: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + superseded_tokens: Vec, } /// Whether a stored account session belongs to the same deployed Relay. @@ -238,6 +248,7 @@ pub fn write_current_account_session( relay_url: session.relay_url.clone(), device_id: session.device_id.clone(), issued_at: session.issued_at, + superseded_tokens: session.superseded_tokens.clone(), }; let plaintext = serde_json::to_vec(&payload).context("serialize account session payload")?; let key = derive_current_key(binding, &secret); @@ -287,6 +298,7 @@ fn decode_account_session_payload(bytes: &[u8]) -> Result relay_url: payload.relay_url, device_id: payload.device_id, issued_at: payload.issued_at, + superseded_tokens: payload.superseded_tokens, }; validate_account_session(&session)?; Ok(session) @@ -1138,6 +1150,7 @@ mod tests { }; let session = AccountSessionRecord { issued_at: None, + superseded_tokens: Vec::new(), token: "synthetic-token".to_string(), user_id: "fixture-account".to_string(), master_key: [0x42; 32], @@ -1271,6 +1284,7 @@ mod tests { relay_url: session.relay_url.clone(), device_id: session.device_id.clone(), issued_at: session.issued_at, + superseded_tokens: session.superseded_tokens.clone(), }; let plaintext = serde_json::to_vec(&payload).unwrap(); let key = derive_legacy_v2_key(binding, local_secret, domains); From 63a3c83b517ca939cc1a1df35343878f63bc18dd Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Wed, 18 Nov 2026 21:27:00 +0800 Subject: [PATCH 5/6] build(dispatch): drop installer HTTP dependencies from the SSH transport --- scripts/check-core-boundaries.test.mjs | 2 ++ scripts/core-boundaries/cargo-dependency-boundaries.mjs | 1 - scripts/core-boundaries/rules/feature-rules.mjs | 1 - src/crates/services/services-integrations/AGENTS.md | 2 +- src/crates/services/services-integrations/Cargo.toml | 6 +----- src/crates/services/services-integrations/src/lib.rs | 1 - 6 files changed, 4 insertions(+), 9 deletions(-) diff --git a/scripts/check-core-boundaries.test.mjs b/scripts/check-core-boundaries.test.mjs index 5ec7fd6537..2c3b6f5f41 100644 --- a/scripts/check-core-boundaries.test.mjs +++ b/scripts/check-core-boundaries.test.mjs @@ -3050,6 +3050,7 @@ test('services integrations Reqwest policy uses Cargo-decoded feature references reqwest = ["dep:reqwest"] browser-control = ["reqwest", "reqwest/rustls-no-provider"] file-watch = ["reqwest?/__native-tls"] +remote-ssh-concrete = ["reqwest", "reqwest/stream"] mcp = ["reqwest", "reqwest/rustls-no-provider", "reqwest/json"] models-dev = ["reqwest", "reqwest/rustls-no-provider", "reqwest/system-proxy"] speech = ["reqwest", "reqwest/rustls-no-provider", "reqwest/http3"] @@ -3060,6 +3061,7 @@ speech = ["reqwest", "reqwest/rustls-no-provider", "reqwest/http3"] .join('\n'); assert.match(messages, /browser-control.*missing Reqwest feature reference reqwest\/json/); assert.match(messages, /file-watch.*outside its reviewed owner features/); + assert.match(messages, /remote-ssh-concrete.*outside its reviewed owner features/); assert.match(messages, /mcp.*missing Reqwest feature reference reqwest\/stream/); assert.doesNotMatch(messages, /models-dev.*system-proxy/); assert.match(messages, /speech.*unreviewed Reqwest feature reference reqwest\/http3/); diff --git a/scripts/core-boundaries/cargo-dependency-boundaries.mjs b/scripts/core-boundaries/cargo-dependency-boundaries.mjs index 6154f9393d..97a60f5bdf 100644 --- a/scripts/core-boundaries/cargo-dependency-boundaries.mjs +++ b/scripts/core-boundaries/cargo-dependency-boundaries.mjs @@ -1078,7 +1078,6 @@ export function findServicesIntegrationsReqwestFeatureViolations(pkg) { ['miniapp-runtime', ['reqwest/stream']], ['models-dev', ['reqwest/system-proxy']], ['remote-connect', ['reqwest/json', 'reqwest/multipart', 'reqwest/query']], - ['remote-ssh-concrete', ['reqwest/stream']], ['review-platform', ['reqwest/json', 'reqwest/query', 'reqwest/stream']], ['speech', ['reqwest/stream']], ['web-tools', ['reqwest/json']], diff --git a/scripts/core-boundaries/rules/feature-rules.mjs b/scripts/core-boundaries/rules/feature-rules.mjs index e469abea3e..97703a78a3 100644 --- a/scripts/core-boundaries/rules/feature-rules.mjs +++ b/scripts/core-boundaries/rules/feature-rules.mjs @@ -8,7 +8,6 @@ export const servicesReqwestOwnerFeatures = [ 'miniapp-runtime', 'models-dev', 'remote-connect', - 'remote-ssh-concrete', 'review-platform', 'speech', 'skillhub', diff --git a/src/crates/services/services-integrations/AGENTS.md b/src/crates/services/services-integrations/AGENTS.md index 1c674cc418..2032cead1c 100644 --- a/src/crates/services/services-integrations/AGENTS.md +++ b/src/crates/services/services-integrations/AGENTS.md @@ -2,7 +2,7 @@ Scope: this guide applies to `src/crates/services/services-integrations`. -For remote CLI installation scripts and recovery behavior, run +For SSH dispatch target probing, protocol compatibility, and job transport, run `cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-ssh-concrete --lib remote_ssh::dispatch_ssh::tests`. Generated Bash execution tests require Unix; Windows covers protocol and script assembly checks. These fixtures do not establish live SSH behavior. diff --git a/src/crates/services/services-integrations/Cargo.toml b/src/crates/services/services-integrations/Cargo.toml index e3a63d008d..69a7f65007 100644 --- a/src/crates/services/services-integrations/Cargo.toml +++ b/src/crates/services/services-integrations/Cargo.toml @@ -355,18 +355,14 @@ remote-ssh-concrete = [ "async-trait", "base64", "dep:openbitfun-core-types", - "openbitfun-services-core/tls-provider", "dep:openbitfun-runtime-ports", + "dep:openbitfun-services-core", "chrono", "dirs", "rand", - "reqwest", - "reqwest/rustls-no-provider", - "reqwest/stream", "russh", "russh-sftp", "russh-keys", - "semver", "shellexpand", "ssh_config", "terminal-core", diff --git a/src/crates/services/services-integrations/src/lib.rs b/src/crates/services/services-integrations/src/lib.rs index eade881ba4..c82b51a5d4 100644 --- a/src/crates/services/services-integrations/src/lib.rs +++ b/src/crates/services/services-integrations/src/lib.rs @@ -10,7 +10,6 @@ feature = "miniapp-runtime", feature = "models-dev", feature = "remote-connect", - feature = "remote-ssh-concrete", feature = "review-platform", feature = "speech", feature = "skillhub", From 694cdc9ebbd28b50776018e11c5c4a6354d060f2 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Wed, 18 Nov 2026 21:53:09 +0800 Subject: [PATCH 6/6] test(remote-connect): persist fixture logins before authenticating routes --- .../remote_connect_api/relay_routes_tests.rs | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs b/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs index 8cc1125950..5a67ad257e 100644 --- a/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs +++ b/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs @@ -27,6 +27,15 @@ impl FixtureHost { format!("http://127.0.0.1:{}{}", self.port, self.prefix) } + async fn sign_in_official_session(&self, session: &AccountSession) { + *get_account_context().write().await = Some(AccountContextState { + session: session.clone(), + relay_url: self.url(), + }); + // Login persists the credential. The next AuthOk supplies the device ID. + persist_account_session(None, None).await.unwrap(); + } + async fn credential(&self, device_id: &str, secret: [u8; 32]) -> AccountSession { db::UserRow::upsert_verified(&self.database, "42", "route-test") .await @@ -192,15 +201,13 @@ async fn dual_relay_rpc_persistence_and_teardown_are_independent() { lan_service.prepare_relay(&lan_method).await.unwrap(); *RelayRoute::Official.service().write().await = Some(official_service); *RelayRoute::Lan.service().write().await = Some(lan_service); - *get_account_context().write().await = Some(AccountContextState { - session: official_session.clone(), - relay_url: official.url(), - }); + official.sign_in_official_session(&official_session).await; let generation = account_context_generation(); account_connect_devices().await.unwrap(); let mut original_owner = current_device_routing_owner_snapshot().unwrap(); let saved = session_store::load_session_detailed().unwrap().unwrap(); assert_eq!(saved.token, official_session.token); + assert_eq!(saved.device_id.as_deref(), Some(id.as_str())); RelayRoute::replace_lan_context(Some(AccountContextState { session: lan_session.clone(), relay_url: lan.url(), @@ -311,10 +318,7 @@ async fn dual_relay_rpc_persistence_and_teardown_are_independent() { serde_json::json!({"stream_id":"dual", "epoch":1, "cursor":2}), ); assert_hint(&mut lan_hints, 2).await; - *get_account_context().write().await = Some(AccountContextState { - session: official_session.clone(), - relay_url: official.url(), - }); + official.sign_in_official_session(&official_session).await; account_connect_devices().await.unwrap(); assert!( !invalidate_local_account_session_if_current( @@ -752,10 +756,7 @@ async fn starting_a_connected_route_again_only_returns_its_invitation() { ) .unwrap(), ); - *get_account_context().write().await = Some(AccountContextState { - session: host_session.clone(), - relay_url: official.url(), - }); + official.sign_in_official_session(&host_session).await; let generation = account_context_generation(); account_connect_devices().await.unwrap(); let owner = current_device_routing_owner_snapshot().unwrap();