Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
docs: reorganize documentation and clarify Cloudflare testing
leepokai51ffd4c895db
diff --git a/.github/workflows/host.yml b/.github/workflows/host.ymlindex 4734b8ee..d19eeea2 100644--- a/.github/workflows/host.yml+++ b/.github/workflows/host.yml@@ -3,10 +3,10 @@ name: codync-hoston:push:branches: [main, v2]- paths: ["host/**", "apps/linux/**", ".github/workflows/host.yml"]+ paths: ["host/**", "apps/linux/**", "docs/reference/fixtures/remote-relay-vectors.json", ".github/workflows/host.yml"]tags: ["v*"] # one version tag ships the Mac app, the host and the Linux apppull_request:- paths: ["host/**", "apps/linux/**"]+ paths: ["host/**", "apps/linux/**", "docs/reference/fixtures/remote-relay-vectors.json"]jobs:test:diff --git a/AGENTS.md b/AGENTS.mdindex 5dce36c5..a196eddc 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -5,6 +5,7 @@- `host/`: Rust daemon, ACP integration, SQLite storage, HTTP/SSE API, and terminal UI; unit tests live alongside modules in `src/`.- `kit/`: shared Swift package. `CodyncKit` contains models, clients, and design primitives; `CodyncUI` contains shared screens and stores. Tests and fixtures live in `kit/Tests/CodyncKitTests/`.- `apps/`: iOS, macOS, and Linux clients, plus `screen` and `screen-linux` helpers. Apple assets live in each target’s `Resources/`; widgets live in `apps/ios/Widgets/`.+- `cloud/`: Cloudflare accounts, encrypted relay, Durable Objects and D1; tests live in `cloud/test/`.- `relay/`: Cloudflare push worker and `test/`; `web/`: website git submodule; `packaging/`: distribution templates; `docs/`: architecture and naming guidance.## Build, Test, and Development Commands@@ -17,6 +18,7 @@ Run from the repository root unless a command changes directories:- `cd host && cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test`: run host CI checks.- `cd kit && swift test`: run shared Swift tests.- `cd apps/linux && cargo test`: test Linux code; requires GTK 4 and libadwaita development packages.+- `cd cloud && npm ci && npm test && npm run typecheck`: validate the cloud service; see `docs/guides/cloudflare-testing.md` for integration checks.- `cd relay && npm ci && npm test && npm run typecheck`: install dependencies and validate the relay.## Installing a new build: kill the old one first@@ -32,7 +34,7 @@ Use four-space indentation for Swift and Rust. Follow Swift 6 strict concurrencyName Swift files after their main `UpperCamelCase` type; use `snake_case.rs` and `kebab-case.ts`. Follow role suffixes such as `View`, `Row`, and `Store`. See `docs/architecture/file-structure.md` and `CLAUDE.md` for architectural conventions.-- No native/system UI at all: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.+- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. Keep system authentication and widget containers native. Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.## Testing Guidelinesdiff --git a/CLAUDE.md b/CLAUDE.mdindex 20fee374..21407f3b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -17,7 +17,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- Clients: iOS app, native Mac window (menu bar app), native Linux app (`apps/linux/`, GTK 4 + libadwaita in Rust), terminal UI (`codync-host tui`, `host/src/tui/`, ratatui; layout and state vocabulary modeled on herdr). All talk to the host API; no web UI.- Shared Swift (`kit/`): `CodyncKit` (models, client, theme, avatars) + `CodyncUI` (`BotStore` + chat screens) used by iOS and macOS. Platform specifics go through `BotStore` hooks or `Platform.swift`.- UI principle: buttons an icon can express are icon-only (with tooltip / accessibility label); text only where an icon would be ambiguous (approval choices).-- No native/system UI at all: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.+- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. Keep system authentication and widget containers native. Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.- `host/` — **codync-host** (Rust, macOS + Linux). Detects installed harnesses (`backends.rs`: login-shell PATH + known dirs) and the ACP registry (`registry.rs`, cached in `~/.codync/registry.json`, binaries under `~/.codync/agents`). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`bot.rs`) owns the agent process + session and maps `session/update` onto transcript entries.- **Chat ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is resumed with `session/load` or replaced by *New session*.- **Group chats and threads** are host features every client drives through the same methods (`send` with `threadId`, `thread`, `createBot {kind: group}`); clients never route, parse mentions or count replies themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a thread on a bot's message is a forked session: [docs/features/groups-and-threads.md](docs/features/groups-and-threads.md).diff --git a/README.md b/README.mdindex b92eed9a..64696604 100644--- a/README.md+++ b/README.md@@ -11,13 +11,13 @@ Codync turns the coding agents on your computer — Claude Code, Codex, Cursor,## How it works-```-iPhone · Mac window · Linux (GTK) ⇄ HTTP + SSE ⇄ codync-host ⇄ ACP (stdio) ⇄ claude · codex · cursor · pi · opencode · …- ▲ │- └──────── APNs ◀── relay (Cloudflare Worker) ◀─────┘ "needs you" / "done"+```text+Remote Apple client ⇄ encrypted channel (direct or Cloudflare cloud/) ⇄ codync-host ⇄ ACP agent+Local / SSH client ⇄ loopback HTTP + SSE ⇄ codync-host+Host notifications → APNs worker (relay/) → iPhone```-- **Bots** have a name, a character avatar, standing instructions, an agent backend, a project folder and a permission policy. Each bot is **one endless conversation**; the agent sessions underneath are an implementation detail (resumed with `session/load`, restarted with *New session*).+- **Bots** have a name, a character avatar, standing instructions, an agent backend, a project folder and a permission policy. Each bot has **a persistent main chat and optional reply threads**; the agent sessions underneath are an implementation detail (resumed with `session/load`, restarted with *New session*).- **Bots can ask each other for help.** Tell one “ask Reviewer to check these changes.” The built-in `team` MCP server lets it discover your other visible bots and wait for a reply. Requests appear in both chats; each recipient keeps its own agent, folder and approvals. Native subagents stay under the coding agent's control. See [bot collaboration](docs/features/bot-collaboration.md).- **The chat only shows what matters**: your messages, each turn's final reply, approval cards and notices. Every tool call, diff, plan and thought is one tap away in *Full conversation*. While a bot works, its row shows what it's doing right now.- **Agents are detected automatically**: the host hydrates PATH from your login shell (plus Homebrew, ~/.local/bin, nvm, bun, volta, asdf, mise, pnpm…), finds every harness you have installed, and prefers its native ACP mode. Anything else in the official [ACP registry](https://agentclientprotocol.com/registry) can be picked too — Codync fetches it on first use (npx, uvx or a checksummed binary).@@ -50,7 +50,7 @@ codync-host pair # QR code in the terminal, or SettingBuilding the Linux app yourself needs `libgtk-4-dev libadwaita-1-dev`: `cargo install --path apps/linux`.-Install [Tailscale](https://tailscale.com) on the computer and the phone to reach your bots from anywhere.+Remote access uses an encrypted channel over direct LAN/Tailscale or the Cloudflare relay. Tailscale is optional. Configure matching app/host environments and follow the [Cloudflare test guide](docs/guides/cloudflare-testing.md); development configuration exists, while production configuration still needs completion.**Agents** — install and sign in to whichever you use; Codync finds them. Claude Code, Codex and Pi run through their ACP adapters (fetched by `npx`, so Node.js is needed for those).@@ -66,9 +66,12 @@ Install [Tailscale](https://tailscale.com) on the computer and the phone to reac| `codync-host status` | installed? running? || `codync-host serve [--port 19222]` | run in the foreground || `codync-host statusline [-- <your command>]` | Claude Code status line command (wraps yours) |-| `codync-host reset-token` | unpair every phone |+| `codync-host reset-token` | rotate the local loopback bearer token |+| `codync-host cloud` | cloud enablement, URL and status |+| `codync-host devices` | list/revoke authorized remote devices |+| `codync-host access` | review device access requests |-Data lives in `~/.codync` (`codync.db`, `token`, `host.log`). **The token is full access** — whoever has it can run agents in any folder on your computer. Prefer Tailscale over open Wi-Fi (the API is plain HTTP; Tailscale encrypts it), and `codync-host reset-token` if a phone is lost. The API is `POST /api/<method>` + `GET /events` (SSE), both with `Authorization: Bearer <token>`; see `host/src/api.rs`.+Data lives in `~/.codync`. The local bearer token authorizes loopback helpers and SSH-forwarded callers. Remote devices use individual keys and grants over the encrypted channel; revoke a lost device through device management rather than rotating the loopback token. Host methods and caller permissions live in `host/src/api.rs`.## Repository@@ -80,16 +83,23 @@ Data lives in `~/.codync` (`codync.db`, `token`, `host.log`). **The token is ful| `apps/ios/Widgets/` | Bots, usage and per-provider usage widgets + bot Live Activity || `apps/macos/` | Menu bar + native chat window; installs/monitors the host || `apps/linux/` | Native Linux app (GTK 4 + libadwaita, Rust) |+| `cloud/` | Cloudflare accounts, D1, encrypted channel relay and offline mailbox |+| `apps/shared/` | Shared Apple account integration and environment configuration |+| `apps/screen/`, `apps/screen-linux/` | Platform screen capture/input helpers |+| `docs/` | [Documentation index](docs/README.md) and [file structure](docs/architecture/file-structure.md) || `relay/` | Cloudflare Worker APNs relay with encrypted per-device tickets || `web/` | Website (git submodule) || `packaging/` | Homebrew formula template |+Build, install, restart and full checks: [development guide](docs/guides/development.md).+The Xcode project is generated: `xcodegen generate`.```bashcd host && cargo test # hostcd kit && swift test # shared Swiftcd apps/linux && cargo test # Linux app (needs GTK dev packages)+cd cloud && npm test # cloud API / channel relaycd relay && npm test # relay tickets```diff --git a/cloud/README.md b/cloud/README.mdindex 6f69d5b6..d75ee987 100644--- a/cloud/README.md+++ b/cloud/README.md@@ -13,7 +13,7 @@ Cloudflare Worker for accounts and the off-LAN relay (spec: [docs/reference/remocached per isolate; `CLERK_JWT_KEY` → networkless, dev/e2e only) and Ed25519 request signatures(WebCrypto).-The cloud sees ciphertext and routing metadata only. It can shorten access (revoke, block) but never grant+The channel relay sees ciphertext and routing metadata. The account API also stores account/device metadata. It can shorten access (revoke, block) but never grantit: new devices come from the host's own QR pairing or its approval, and the ACL is signed by the host.## Test@@ -42,10 +42,11 @@ Env: `CODYNC_HOST_BIN` (default `../host/target/debug/codync-host`), `CODYNC_E2E## Deploy-Staging (the integration stage runs this; production needs the owner):+Development deployment (see [environment readiness](../docs/guides/environments-and-deployment.md); these commands change remote resources):```bash-npx wrangler d1 create codync-dev # put database_id into [env.dev]+# Only if the database does not exist: npx wrangler d1 create codync-dev+# Confirm its database_id in [env.dev] before applying migrations.npx wrangler d1 migrations apply codync-dev --env dev --remotenpx wrangler secret put CLERK_SECRET_KEY --env devnpx wrangler secret put CLERK_WEBHOOK_SECRET --env devdiff --git a/docs/README.md b/docs/README.mdnew file mode 100644index 00000000..2aa372ae--- /dev/null+++ b/docs/README.md@@ -0,0 +1,62 @@+# Codync documentation++Current documentation describes the checked-out implementation. Last reviewed: **2026-09-26**.+Source review, a passing build, local integration tests and production acceptance are different checks; a feature documented here is not a claim that its deployed service has been verified.++## Start here++| Task | Read |+|---|---|+| Find a module or decide where a file belongs | [File structure](architecture/file-structure.md) |+| Understand clients, host, cloud and data ownership | [Architecture](architecture/overview.md) |+| Build, install, restart and run checks | [Development](guides/development.md) |+| Test a phone over Cloudflare instead of LAN | [Cloudflare testing](guides/cloudflare-testing.md) |+| Configure dev/main or deploy the services | [Environments and deployment](guides/environments-and-deployment.md) |+| Set up accounts, approvals or desktop SSH | [Accounts and SSH](guides/accounts-and-ssh.md) |+| Change transport or cryptography | [Remote protocol](reference/remote-relay.md) and [shared vectors](reference/fixtures/README.md) |+| Change an Apple screen or button | [UI conventions](design/ui-conventions.md) |++## Features++- [Group chats and reply threads](features/groups-and-threads.md)+- [Bot-to-bot collaboration](features/bot-collaboration.md)+- [Context and memory](features/context-and-memory.md)+- [Voice calls](features/voice-call.md)+- [Remote screen](features/remote-screen.md)+- [Marketplace and agent setup](features/marketplace.md)+- [Widgets, Live Activities and onboarding](design/mobile-widgets.md)++## Documentation layout++```text+docs/+├── README.md # Navigation and maintenance rules+├── architecture/ # Current boundaries, data flow and file ownership+├── guides/ # Build, configuration, testing and deployment steps+├── reference/ # Wire contracts and shared executable fixtures+│ └── fixtures/+├── features/ # Current behavior and implementation entry points+├── design/ # UI rules, rendering and system integration+└── archive/ # Dated plans/audits; never current instructions+```++Service-local entry points remain in [cloud/README.md](../cloud/README.md) and [relay/README.md](../relay/README.md). Repository-wide development rules remain in [AGENTS.md](../AGENTS.md) and [CLAUDE.md](../CLAUDE.md).++## Maintaining these docs++1. Describe implemented behavior in the present tense. Label proposals and unverified deployment steps explicitly.+2. Keep one authoritative explanation per topic; link to it from related pages. Link to source for schemas and public APIs instead of copying entire definitions that drift.+3. Use lowercase, kebab-case filenames and relative links. Source paths written in backticks are relative to the repository root.+4. When moving a document, update inbound links, code comments, test fixture imports and CI path filters in the same change.+5. Check local links and run the affected fixture tests. Keep generated images/build logs under `build/` or a temporary directory, outside the documentation tree.+6. Record verification scope and limitations. Do not turn an old test report or historical audit into a current passing status.++[Archived plans and audits](archive/README.md) retain earlier decisions and review context. Their original dates, line numbers and proposed APIs are historical.++## Documentation validation — 2026-09-26++- Checked 27 Markdown files and 112 local link targets; none were missing.+- Shared fixture SHA-256 is unchanged; the Python generator reproduced it byte for byte.+- Focused fixture/crypto checks passed: Swift 14 tests; Rust 12 tests across library/binary targets; Cloudflare vectors/relay 43 tests.+- `git diff --check` passed. These checks validate the documentation move and its executable consumers, not the deployed Cloudflare path.+- Wrangler reported a production route placement warning; see [environment readiness](guides/environments-and-deployment.md). Deployed-device acceptance remains separate.diff --git a/docs/architecture/overview.md b/docs/architecture/overview.mdnew file mode 100644index 00000000..56eb4a94--- /dev/null+++ b/docs/architecture/overview.md@@ -0,0 +1,66 @@+# Architecture++Codync keeps agents and their working files on a computer. Clients address that computer's bots; the host owns execution, transcripts and authorization.++## Runtime paths++```mermaid+flowchart LR+ Phone[iPhone / remote Apple client] -->|Encrypted WebSocket| Cloud[cloud/ Worker + ComputerRelay DO]+ Phone -->|Encrypted direct channel| Host[codync-host]+ Cloud <-->|Encrypted frames| Host+ Local[Mac / Linux / TUI] -->|Loopback HTTP + SSE| Host+ SSH[Mac SSH tunnel] -->|Forwarded loopback HTTP + SSE| Host+ Host -->|ACP over stdio| Agents[Coding agents]+ Host --> DB[(Local SQLite)]+ Host -->|Sealed alert| Push[relay/ APNs Worker]+ Push --> APNs[Apple Push Notification service]+ APNs --> Phone+```++The phone tries direct candidates first, with a 1.5-second connection race, then uses the configured cloud relay. Both paths use the same end-to-end encrypted channel. Tailscale is an optional direct route. Loopback bearer credentials are for local applications and SSH forwarding, not phone pairing.++## Ownership and storage++| Data | Owner and location |+|---|---|+| Bots, chats, replies, revisions, authorized devices | Host SQLite in its data directory (`~/.codync` by default; `CODYNC_HOME` overrides it) |+| Host signing and mailbox keys | `identity.json`, separate from SQLite |+| Loopback API bearer token | Host `token` file |+| Agent context and provider credentials | Coding harness on that computer |+| Long-term bot memory | Host `bots/<botId>/memory/` |+| Account users, computer ownership, devices and grants | `cloud/` D1 |+| Presence, host-signed ACL, offline encrypted mailbox | Per-computer `ComputerRelay` Durable Object |+| Phone/Mac remote-device signing and push keys | Keychain, partitioned by account context |+| Client mirror, widget snapshots, selected computer | Per-account cache/App Group storage |+| APNs signing key and ticket encryption key | `relay/` Worker secrets |++Cloud account metadata includes names, public keys, ownership and access state. Chat/channel contents and notification title/body are encrypted. Routing IDs, timing and sizes remain visible to the relevant service; “end-to-end encrypted” does not mean all metadata is hidden.++## Host execution++`api.rs` and `channel.rs` share dispatch and caller checks. `hub.rs` coordinates actors and event publication; `store.rs` persists mutations and the global revision. Clients catch up from `rev`, then follow events. Duplicate sends are identified by `clientNonce`.++`bot.rs` serializes each bot's turns and owns its ACP process. A main chat and its reply threads can have distinct sessions. Group turns are queued on member bots and use their main sessions; the group itself has no harness. See [groups and threads](../features/groups-and-threads.md), [collaboration](../features/bot-collaboration.md) and [context/memory](../features/context-and-memory.md).++## Apple state and routing++- `AccountSession` owns Clerk integration; `AccountStore` owns one account context's computer stores.+- `BotReference(accountId, computerId, botId)` identifies a destination. Widgets and pushes carry account/computer scope.+- `BotStore` mirrors one computer and consumes a `HostTransport`: loopback or encrypted channel.+- Account changes retire the old stores; late responses must not update the new context. Signing out erases that context's local credentials and caches.+- The Mac attaches its local host and configured SSH hosts through loopback transports. Remote Apple connections use device identities.++The product currently prioritizes one computer. Existing account-scoped aggregation and SSH support remain; their presence is not a reason to add multi-computer features without a product requirement.++## Service boundaries++`cloud/` implements `/v1`, Clerk authentication, computer registration/claim, host-approved access, WebSocket relay and mailbox. `relay/` implements APNs registration tickets and push forwarding. [Remote protocol](../reference/remote-relay.md) defines wire details; [Cloudflare testing](../guides/cloudflare-testing.md) distinguishes these paths during acceptance.++Remote screen uses the channel for signaling and WebRTC for media/input. Its traffic does not become a Cloudflare video relay. [Remote screen](../features/remote-screen.md) describes the helpers and current limitations.++## Release and environment boundaries++Application/host major versions must match. The channel wire version (`v=1`), pairing URL version (`v=3`) and the cloud health endpoint's service version are separate values.++Debug Apple builds use `apps/shared/Config/dev.plist`; Release uses `main.plist`. The host has no default cloud URL. Production fields are currently incomplete in checked-in configuration, so a successful Debug install is not production readiness. See [environments](../guides/environments-and-deployment.md).diff --git a/docs/archive/README.md b/docs/archive/README.mdnew file mode 100644index 00000000..035cee89--- /dev/null+++ b/docs/archive/README.md@@ -0,0 +1,13 @@+# Archived plans and audits++These documents retain decisions and observations from before the current refactors. They are **historical records**, not current implementation instructions, deployment status, or open-bug lists.++| Record | Date | Current replacement |+|---|---|---|+| [Cloudflare account/device plan](cloudflare-account-device-plan-2026-09-25.md) | 2026-09-25 | [Architecture](../architecture/overview.md), [protocol](../reference/remote-relay.md), [environments](../guides/environments-and-deployment.md) |+| [Bot/computer/SSH plan](bot-computer-ssh-plan-2026-09-25.md) | 2026-09-25 | [Accounts and SSH](../guides/accounts-and-ssh.md), [file structure](../architecture/file-structure.md) |+| [UI audit](ui-audit-2026-09-25.md) | 2026-09-25 | [UI conventions](../design/ui-conventions.md), [widgets](../design/mobile-widgets.md) |++Do not interpret old “not implemented” statements, delegation assignments, version numbers or test reports as the state of the current checkout. Reassess an audit finding against source before turning it into work.++- [Widget verification record, 2026-09-26](mobile-widgets-verification-2026-09-26.md): historical observations and remaining system integration checks.diff --git a/docs/archive/mobile-widgets-verification-2026-09-26.md b/docs/archive/mobile-widgets-verification-2026-09-26.mdnew file mode 100644index 00000000..44dc8c0b--- /dev/null+++ b/docs/archive/mobile-widgets-verification-2026-09-26.md@@ -0,0 +1,35 @@+# Widget verification record — 2026-09-26++> Historical observations from the original UI work, not a current test result. See [current widget documentation](../design/mobile-widgets.md).++## 驗證與後續++已完成:++- iOS Simulator build,含 widget extension 與原生 WidgetKit 預覽巨集,沒有編譯警告。+- Swift package 14 個測試,包含跨帳號隔離、跨電腦 widget 快取清除/保留,以及 Live Activity 錯誤/未知/stale/計時狀態的回歸測試。+- 首次 onboarding 隱藏帳號入口;完成後,即使沒有電腦仍保留帳號入口。+- App 內 Widgets 頁、Claude/Codex 預覽切換、淺色/深色與無障礙大字體佈局檢查。+- 共用卡片的離線圖片輸出:Claude、Codex、接近上限、Bots 工作/待回應、空清單;每種包含小/中尺寸及淺色/深色。+- 本機 HTTP/SSE 測試 host 到 App Group 的整合檢查:初次 bot/用量同步、狀態不變時改名及活動更新、刪除 bot、切換到離線電腦後清除上一台資料。+- 系統 Add Widget 搜尋能找到 Codync。測試配對不會保留在模擬器。+- 大型 widget 用四個限制視窗及六個 bot 測試實際共用元件的排版;三種鎖定畫面配件也產生了深淺色檢查圖。+- Live Activity 五種狀態 × Lock Screen/compact/minimal/expanded 共用內容已輸出檢查;四種原生 ActivityKit 預覽均可編譯。+- 模擬器實際啟動不連 relay/APNs 的本機範例 Activity,確認系統 Dynamic Island compact 與 Lock Screen 卡片的 Needs you 呈現。Lock Screen 同時出現 iOS 的首次 Allow 提示,未操作該權限提示。++驗證限制:系統 widget 搜尋結果沒有提供可點擊的 accessibility 元素,座標點擊與捲動仍回報 `noWindowsAvailable`,鍵盤導覽也未能開啟結果。因此尚未在系統 Home/Lock Screen 上實際加入 widget、編輯 provider 或量測背景刷新排程;原生預覽可編譯與共用卡片圖片檢查不等同這些整合驗證。++Live Activity 的 compact/Lock Screen 已觀察到系統實際呈現;minimal/expanded 的系統切換及 APNs 背景更新未完成端到端操作驗證。兩個同時活動的範例在此次模擬器中仍顯示 compact,不能據此宣稱 minimal 已驗證。++重現方式:++```sh+swift test --package-path kit+python3 tools/render-widgets.py+```++圖片輸出在 `build/widget-previews/`:`widgets-{light,dark}.png`、`large-widgets-{light,dark}.png`、`activities-{light,dark}.png`、`halftone-icons-{light,dark}.png`。腳本使用 macOS 的 SwiftUI ImageRenderer,直接繪製產品共用元件;產物不含使用者資料。實際 WidgetKit/ActivityKit 預覽在 `apps/ios/Widgets/WidgetPreviews.swift`,可於 Xcode canvas 切換 timeline/content states。++DEBUG simulator build 也可用 `SIMCTL_CHILD_CODYNC_ACTIVITY_PREVIEW=needsInput xcrun simctl launch --terminate-running-process booted com.pokai.Codync.ios` 啟動系統範例。值可為 `working`、`needsInput`、`idle`、`error`、`stale` 或 `multiple`;以 `stop` 結束範例。此入口只存在於 DEBUG simulator,不連 host/relay/APNs,清理僅針對 `codync-design-preview-` 的活動。++帳號/雲端架構與 SSH computer 路線分別見 [帳號與裝置計畫](../archive/cloudflare-account-device-plan-2026-09-25.md) 與 [Bot/computer/SSH 計畫](../archive/bot-computer-ssh-plan-2026-09-25.md)。diff --git a/docs/design/mobile-widgets.md b/docs/design/mobile-widgets.mdindex 4f0bea38..e635515b 100644--- a/docs/design/mobile-widgets.md+++ b/docs/design/mobile-widgets.md@@ -1,6 +1,6 @@# Mobile onboarding 與 Widgets 設計-更新:2026-09-26。此工作範圍是 iOS 介面、WidgetKit 與 ActivityKit;Cloudflare 後端由 Claude Code 另行實作。+更新:2026-09-26。本文件描述 iOS onboarding、WidgetKit 與 ActivityKit 的目前設計。連線與部署另見 [Cloudflare 測試](../guides/cloudflare-testing.md)。## 參考方向@@ -13,13 +13,13 @@## Onboarding 與帳號-1. 首次開啟先顯示連接電腦流程,隱藏左上角 profile/帳號切換入口,也不彈出帳號選單。+1. 首次開啟由 Welcome 提供 Get started 與 Google 登入,再進入配對/帳號電腦流程。2. 儲存第一台配對電腦後,記錄此裝置的 `onboardingCompleted`。3. 既有已配對安裝自動視為完成 onboarding。4. 完成後才顯示帳號入口;切換到沒有電腦的帳號,或解除配對後,入口仍保留,避免無法切回原帳號。5. 「帳號」代表 Codync 的 Google/Clerk 登入身分。帳號與 computer 是不同概念。-目前完成條件沿用現有的配對資料儲存事件,不代表已驗證雲端登入或 host 當下在線。待雲端 onboarding 整合時,應由單一流程明確管理登入、電腦註冊與完成狀態。+目前完成條件沿用現有的配對資料儲存事件,不代表已驗證雲端登入或 host 當下在線。Welcome、配對與帳號電腦的選擇由 RootView 和帳號狀態共同決定。## Widget 與 App 內預覽@@ -75,49 +75,22 @@ Dynamic Island 固定黑底,文字採淺色;Lock Screen 卡片配合系統- Widgets 跟隨 App 目前選取的帳號,讀取該帳號的 App Group 快取;不合併不同帳號的 bots 或用量。- 切換帳號時由既有 App 流程重載 widgets;非同步用量請求保留原 storage context,避免舊回應寫入新帳號。- 切換或移除目前電腦時清除舊用量、bot 快取與偏好 URL;更新同一台電腦的地址則保留快取。-- App 與 widget 的非同步用量回應都核對 computer token,避免切換途中收到的舊資料覆蓋新電腦。+- App 與 widget 的非同步用量回應都核對原始帳號 context 與 computer ID,避免切換途中收到的舊資料覆蓋新電腦。- Bot 新增、改名、活動變化、隱藏、刪除與清空都會更新 widget feed;刷新判斷包含 widget 實際顯示的欄位。- Bot 連結帶有帳號與電腦範圍,舊 widget 的連結不會直接開啟其他帳號的 bot。- Provider widget 點擊開啟 Usage。Bot 的中尺寸可點擊個別 bot。- Widgets 顯示最近回報的狀態;即時聊天與審批在 App 完成。WidgetKit 排程由系統決定,不保證即時更新。-- Bots 由 App 更新快取後重載;用量沿用目前直接連 host 的刷新與快取退路,未加入新的 Cloudflare API。+- Bots 由 App 更新快取後重載;用量透過 HostConnector 連線(direct 或 relay),失敗時使用快取。-## 驗證與後續+## 驗證-已完成:--- iOS Simulator build,含 widget extension 與原生 WidgetKit 預覽巨集,沒有編譯警告。-- Swift package 14 個測試,包含跨帳號隔離、跨電腦 widget 快取清除/保留,以及 Live Activity 錯誤/未知/stale/計時狀態的回歸測試。-- 首次 onboarding 隱藏帳號入口;完成後,即使沒有電腦仍保留帳號入口。-- App 內 Widgets 頁、Claude/Codex 預覽切換、淺色/深色與無障礙大字體佈局檢查。-- 共用卡片的離線圖片輸出:Claude、Codex、接近上限、Bots 工作/待回應、空清單;每種包含小/中尺寸及淺色/深色。-- 本機 HTTP/SSE 測試 host 到 App Group 的整合檢查:初次 bot/用量同步、狀態不變時改名及活動更新、刪除 bot、切換到離線電腦後清除上一台資料。-- 系統 Add Widget 搜尋能找到 Codync。測試配對不會保留在模擬器。-- 大型 widget 用四個限制視窗及六個 bot 測試實際共用元件的排版;三種鎖定畫面配件也產生了深淺色檢查圖。-- Live Activity 五種狀態 × Lock Screen/compact/minimal/expanded 共用內容已輸出檢查;四種原生 ActivityKit 預覽均可編譯。-- 模擬器實際啟動不連 relay/APNs 的本機範例 Activity,確認系統 Dynamic Island compact 與 Lock Screen 卡片的 Needs you 呈現。Lock Screen 同時出現 iOS 的首次 Allow 提示,未操作該權限提示。--驗證限制:系統 widget 搜尋結果沒有提供可點擊的 accessibility 元素,座標點擊與捲動仍回報 `noWindowsAvailable`,鍵盤導覽也未能開啟結果。因此尚未在系統 Home/Lock Screen 上實際加入 widget、編輯 provider 或量測背景刷新排程;原生預覽可編譯與共用卡片圖片檢查不等同這些整合驗證。--Live Activity 的 compact/Lock Screen 已觀察到系統實際呈現;minimal/expanded 的系統切換及 APNs 背景更新未完成端到端操作驗證。兩個同時活動的範例在此次模擬器中仍顯示 compact,不能據此宣稱 minimal 已驗證。--重現方式:--```sh-swift test --package-path kit-python3 tools/render-widgets.py-```--圖片輸出在 `build/widget-previews/`:`widgets-{light,dark}.png`、`large-widgets-{light,dark}.png`、`activities-{light,dark}.png`、`halftone-icons-{light,dark}.png`。腳本使用 macOS 的 SwiftUI ImageRenderer,直接繪製產品共用元件;產物不含使用者資料。實際 WidgetKit/ActivityKit 預覽在 `apps/ios/Widgets/WidgetPreviews.swift`,可於 Xcode canvas 切換 timeline/content states。--DEBUG simulator build 也可用 `SIMCTL_CHILD_CODYNC_ACTIVITY_PREVIEW=needsInput xcrun simctl launch --terminate-running-process booted com.pokai.Codync.ios` 啟動系統範例。值可為 `working`、`needsInput`、`idle`、`error`、`stale` 或 `multiple`;以 `stop` 結束範例。此入口只存在於 DEBUG simulator,不連 host/relay/APNs,清理僅針對 `codync-design-preview-` 的活動。--帳號/雲端架構與 SSH computer 路線分別見 [帳號與裝置計畫](../archive/cloudflare-account-device-plan-2026-09-25.md) 與 [Bot/computer/SSH 計畫](../archive/bot-computer-ssh-plan-2026-09-25.md)。+執行 `swift test --package-path kit` 與 `python3 tools/render-widgets.py` 檢查共用邏輯及繪製。系統 WidgetKit/ActivityKit 預覽在 `apps/ios/Widgets/WidgetPreviews.swift`。+實機仍需分別確認加入 Home/Lock Screen widget、編輯 provider、跨帳號切換、背景刷新,以及 Live Activity/APNs 更新。共用圖片與 build 成功不等於這些系統整合已通過。[歷史檢查紀錄](../archive/mobile-widgets-verification-2026-09-26.md) 保留當時的測試範圍與操作限制。## Halftone 與 Thinking Orbs(2026-09-26)-Bot 與 provider 的角色頭像統一使用 `CharacterAvatar` 點陣;小於 24 pt 也不再改用實心剪影。15 pt 用 7 × 7、20–26 pt 用 9 × 9、28 pt 以上用 13 × 13 網格,保留鏤空眼睛並提高小尺寸墨色。iOS 與 macOS 用量卡的 provider 頭像採相同元件。+Bot 的角色頭像使用 `CharacterAvatar` 點陣;provider 圖示由 `ProviderMascot` 選擇,小尺寸可使用隨 app 打包的官方 provider 圖示。15 pt 用 7 × 7、20–26 pt 用 9 × 9、28 pt 以上用 13 × 13 網格,保留鏤空眼睛並提高小尺寸墨色。iOS 與 macOS 共用 provider 呈現邏輯。狀態圖示以 [Jakub Antalik 的 thinking-orbs](https://github.com/Jakubantalik/thinking-orbs) 為來源,這次原生移植四種實際使用的造型:@@ -135,5 +108,3 @@ Bot 與 provider 的角色頭像統一使用 `CharacterAvatar` 點陣;小於 2App 內動畫最多 30 fps;離開畫面、App 非 active 或啟用 Reduce Motion 時顯示靜態幀。Widget、Live Activity 與 Dynamic Island 明確傳入 `animated: false`,不依賴持續動畫計時。狀態仍隨既有資料更新。上游 MIT 授權全文隨 `CodyncKit` resource bundle 發佈,位於 `kit/Sources/CodyncKit/Resources/ThirdPartyNotices/thinking-orbs-LICENSE.txt`。`ThinkingOrbGeometryTests` 使用上游獨立 golden vectors 的取樣,驗證四種造型 × 兩尺寸 × 四時間點的 dot/line 數量、位置、半徑、墨色及深度順序。其餘五種上游造型暫未移植;有對應產品狀態時再加入。--本次驗證:14 個 Swift package 測試全數通過(含 32 組上游幾何參考案例);iOS Simulator App/Widget extension build 成功、無編譯警告;確認兩個產物都包含第三方授權。已檢查深淺色 icon 圖版及 Live Activity 共用元件圖版。此驗證不擴大前述原生系統互動/APNs 的完成範圍。diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdnew file mode 100644index 00000000..7cdb6ec1--- /dev/null+++ b/docs/design/ui-conventions.md@@ -0,0 +1,37 @@+# UI conventions++## iPhone navigation++The bot list and conversation use the system `NavigationStack` toolbar. `ToolbarItem` owns the account, computer, new-chat, call and more buttons; the conversation uses the system back button. iOS supplies Liquid Glass, control sizing, grouping and interaction feedback.++Do not wrap those toolbar controls in `IconButtonStyle`, hand-sized rounded backgrounds or another glass effect. The account avatar is toolbar content, with the system supplying the enclosing surface. This is the explicit exception to the custom-chrome rule below.++`ConnectingIndicator` is in the toolbar center and remains visible for at least 0.7 seconds after appearing. Transient connecting state is omitted from `ConnectionBanner`, so it does not insert/remove loading content above the bot rows or composer. Actionable offline/authorization warnings remain separate. This does not remove the normal pull-to-refresh interaction.++Sources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `kit/Sources/CodyncUI/Thread/ThreadView.swift`, `Chrome.swift`, `Bots/BotRow.swift`.++## Shared application controls++Other custom screens use `Chrome.swift` and `Controls.swift`:++| Need | Component |+|---|---|+| Modal or full-window overlay | `.codyncSheet`, `.codyncOverlay` |+| Header outside the native bot navigation flow | `ModalHeader`, `ScreenHeader` |+| Icon action | `IconButton` |+| Tab selection | `TabBar` |+| Menu / confirmation | `.codyncMenu`, `.codyncDialog` |+| Toggle | `ToggleStyle.codync` |+| Form-like content | `CardForm`, `CardSection` |++Avoid adding stock `Menu`, `Picker`, `Form`/`List` styling, switch toggles, alerts, `ProgressView`, `TabView` or system sheets to these flows. System presentation APIs inside the shared chrome implementation are implementation details, not permission to bypass the components in feature screens. Native WidgetKit/ActivityKit containers and OS authentication/permission flows remain system integrations.++Anything with a background fill gets no extra drawn border. Use `Palette`, `InterfaceMetrics` and `Motion`; visibility changes animate and honor Reduce Motion. Icon-only actions have an accessibility label and desktop help where applicable. Reserve text for actions an icon cannot clearly express.++## Motion and status++`CharacterAvatar` identifies a bot. `ThinkingOrb` conveys working, searching, listening or connecting and needs adjacent text or an accessible outer label. In-app animation pauses off-screen, when inactive, or with Reduce Motion. Widgets/activities use static frames.++Provider identity and activity presentation are shared in `CodyncKit/Design`; use those components rather than re-creating mappings per app. See [mobile widgets](mobile-widgets.md) for current rendering and previews.++The [2026-09-25 audit](../archive/ui-audit-2026-09-25.md) is historical. Its old line numbers and recommendations are not the current UI policy or a list of confirmed open bugs.diff --git a/docs/features/bot-collaboration.md b/docs/features/bot-collaboration.mdindex 18c431da..15d3d724 100644--- a/docs/features/bot-collaboration.md+++ b/docs/features/bot-collaboration.md@@ -10,7 +10,7 @@ The host records the request and its outcome in both chats using existing notice## Execution-- Each bot still owns one ACP process/session and runs one turn at a time. A busy recipient queues the request. Different bots can work concurrently.+- Each bot still owns an ACP process with main/reply-thread sessions and runs one turn at a time. A busy recipient queues the request. Different bots can work concurrently.- Requests have their own reply channel and never merge with user messages or another request. Contiguous user messages keep the existing batching behavior.- The recipient uses its own folder, tools, memory and permission policy. Permission cards appear in its chat. The requesting bot's entire transcript is not copied; only the request is passed. Requests are not treated as user facts by the memory keeper.- The host rejects self-delegation, duplicate outstanding requests to the same recipient, and direct or indirect wait cycles, including queued requests. Up to 64 requests can be outstanding host-wide.diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex b131cec3..ab82be7c 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -4,11 +4,11 @@ How a bot keeps its instructions, context and long-term memory. The mechanisms f(`system-prompt-assembly`, `sand-memory`, `turn-memory`, `upgrade-recreate-resume`) and are adapted to ACP,where the harness owns the conversation.-## Two memories+## Transcript, context and memory| | Where | Owner | Lifetime ||---|---|---|---|-| Transcript | SQLite `entries` | Codync | Forever, one endless thread per bot |+| Transcript | SQLite `entries` | Codync | Persistent main chat and flat reply threads per bot || Model context | ACP session (`bots.session_id`) | The harness | Until *New session*, a failed resume, or an agent/command/folder change || Long-term memory | `~/.codync/bots/<id>/memory/` | Codync (keeper) + the user | Forever, across sessions |@@ -55,7 +55,7 @@ its own context and compacts it itself.- Messages sent while the agent works are folded into one next turn, joined by blank lines.- Bot-to-bot requests occupy separate turns in the same queue; user messages are only folded together up to the next request. Requests never feed the user-fact memory keeper. See [bot collaboration](bot-collaboration.md).- Delegated turns do not set the restart marker: their waiter disappears on restart. Pending delegation notices become interrupted errors instead of automatically replaying work.-- `turn.inflight.<bot>` holds the start time of a running turn. If the host stops mid-turn (update, crash, restart), the next+- `turn.inflight.<bot>` records the running turn start and its thread lane. If the host stops mid-turn (update, crash, restart), the nextstart resumes that session with a hidden "you were interrupted, don't repeat finished steps" prompt. If thesession can't be resumed, or the turn started over an hour ago, it does nothing.@@ -69,3 +69,5 @@ its own context and compacts it itself.starts fresh, but its memory remains.- User-level memory shared across bots, project memory and the daily memory "dreaming" pass from Grok Botare not implemented.++Reply threads have separate session/context lanes; see [groups and threads](groups-and-threads.md). Group/delegated requests do not become user facts in the memory keeper.diff --git a/docs/features/groups-and-threads.md b/docs/features/groups-and-threads.mdindex 8e08eb1a..087836ab 100644--- a/docs/features/groups-and-threads.md+++ b/docs/features/groups-and-threads.md@@ -15,7 +15,7 @@ replies itself.## Data (all over the existing sync: `bot` and `entry` events)-- Bot: `kind` (`agent` | `group`), `members` (group: bot ids, any number), `workingChat` /+- Bot: `kind` (`agent` | `group`), `members` (group: one or more distinct agent bot IDs on the same computer; no nested groups), `workingChat` /`workingThread` (where the running turn talks). A group's `status` / `activity` are its busymember's (`"Alice: Writing a reply…"`); its `lastMessage` names who spoke (`"Alice: …"`).- Entry: `threadId`; `data.author` (the bot that wrote it; every agent-made entry has one);diff --git a/docs/features/marketplace.md b/docs/features/marketplace.mdnew file mode 100644index 00000000..67cdb2db--- /dev/null+++ b/docs/features/marketplace.md@@ -0,0 +1,18 @@+# Marketplace and agent setup++The Plugins screen configures capabilities installed on the selected computer. Account membership does not install the same capability on every computer.++| Capability | Implementation | Behavior |+| --- | --- | --- |+| Agents | `host/src/backends.rs`, `host/src/registry.rs` | Detect installed harnesses and resolve ACP registry adapters |+| Connectors | `host/src/market.rs` | Discover MCP servers or add one manually; install per computer and enable per bot |+| Connected apps | `host/src/composio.rs` | Expose connected Composio apps as connectors |+| Skills | `host/src/market.rs` | Instruction folders containing `SKILL.md`, stored under `~/.codync/skills/<id>` |++An enabled connector is passed to the agent as an MCP server when its session starts or resumes. An enabled skill tells the bot where its instruction folder lives. These are distinct from the built-in `team` and `computer` MCP services.++Registry and repository metadata are untrusted: the host validates names and paths before installing. Secret values stay on the computer; listings report whether required values are configured. Adapter downloads and external authorization depend on the selected provider.++To check a change, use a disposable bot on the intended computer, verify discovery/install/configuration, start a new session as needed, and confirm the agent actually receives the capability. Listing an item alone does not verify its authentication or runtime behavior.++See [file structure](../architecture/file-structure.md), [bot collaboration](bot-collaboration.md), and [remote screen](remote-screen.md).diff --git a/docs/features/remote-screen.md b/docs/features/remote-screen.mdnew file mode 100644index 00000000..f8902a89--- /dev/null+++ b/docs/features/remote-screen.md@@ -0,0 +1,16 @@+# Remote screen++Remote screen lets a phone view and control a computer. Signaling travels through the host API (`screenOffer`); video and input use WebRTC. Passing a Cloudflare chat test does not prove that the media connection can traverse the current network. TURN is outside the current remote relay design.++## Boundaries++- `host/src/screen.rs` coordinates access to the local helper.+- `apps/screen/` is the macOS capture/input helper, installed through `SMAppService` and responsible for the OS permissions.+- `apps/screen-linux/` implements the Linux helper using desktop portals and GStreamer.+- Helpers communicate locally through `~/.codync/screen.sock`. SDP is non-trickle; input uses the `input` and `input-fast` data channels.+- Screen access is off by default. Enabling through `setScreenEnabled` requires a loopback caller. Interactive OS permission prompts must be completed on the computer.+- Bots with their computer capability enabled receive the built-in `computer` MCP tools (`host/src/mcp.rs`). Their permission policy still applies.++## Verification++Check screen permission, capture, input, disconnect and reconnect separately on each platform. Repeat over the intended remote network; a local screen preview or encrypted signaling success does not verify remote media. See [Cloudflare testing](../guides/cloudflare-testing.md) for transport checks and [architecture](../architecture/overview.md) for data flow.diff --git a/docs/features/voice-call.md b/docs/features/voice-call.mdindex b49b503f..016e7e82 100644--- a/docs/features/voice-call.md+++ b/docs/features/voice-call.md@@ -3,7 +3,7 @@A hands-free call with one bot from the iPhone chat (phone icon in the header). The bot is thesame agent on the computer; the call only changes how you talk to it.-## Free tier (shipped): on the phone+## Implemented: on the phone- `kit/Sources/CodyncUI/Call/`: `CallSession` (audio loop) + `CallView` (full-screen layer).- Speech → text with `SFSpeechRecognizer` (on-device when the language supports it). A 1.5 s pause@@ -12,10 +12,10 @@ same agent on the computer; the call only changes how you talk to it.- Each new final reply (`data.final`) is read aloud with `AVSpeechSynthesizer` in the reply's ownlanguage; markdown and code blocks are dropped (`SpokenText`). The mic pauses while it speaks;tapping the avatar interrupts. An approval request is announced, answered in the chat.-- The host and relay see text only. No new cloud pieces. `UIBackgroundModes: audio` keeps the call+- The host receives recognized text; the Cloudflare transport sees encrypted channel frames. Codync does not forward microphone audio to the host. Speech recognition may use Apple services when on-device recognition is unavailable. `UIBackgroundModes: audio` keeps the callalive with the screen locked.-## Pro tier (planned): cloud realtime voice+## Proposal: cloud realtime voice (not implemented)For better recognition (mixed Chinese/English, code terms) and a real conversation (barge-in,"what are you doing?" answered from the transcript):diff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.mdindex 415df09c..7e094bd9 100644--- a/docs/guides/accounts-and-ssh.md+++ b/docs/guides/accounts-and-ssh.md@@ -1,27 +1,14 @@-# macOS account authentication+# Accounts, device approval and SSHThe macOS app uses the official ClerkKit SDK (1.5.6). The sidebar's accountpanel is a custom SwiftUI overlay, independent of the system authentication browser.The footer displays **Account**, never the Mac user's local name.-## Dashboard setup--1. Create a Clerk application named **Codync** and enable Google sign-in.-2. Enable the Native API under **Native applications**.-3. Register the native application for team `7FUM8A8H72` and bundle identifier- `com.pokai.Codync`, following Clerk's Apple/native configuration instructions.-4. Allow the native callback `com.pokai.Codync://callback` where Clerk's dashboard- requests allowed redirect URLs.-5. Copy only the **publishable key** into- `apps/macos/Resources/AccountConfig.plist` (`clerkPublishableKey`), next to- `cloudURL`, the Codync cloud the app talks to (dev for now). A development- launch can override them with `CODYNC_CLERK_PUBLISHABLE_KEY` and `CODYNC_CLOUD_URL`.--The checked-in public configuration uses the Codync development instance-`sunny-mollusk-8651.clerk.accounts.dev`. Native API is enabled, the Apple app-is registered, and `com.pokai.Codync://callback` is allowlisted. Google and-email sign-in are enabled. Production deployment needs its own Clerk instance-and publishable key. Never put a Clerk secret key in the Mac bundle or this file.+## Configuration++Both Apple apps use `apps/shared/AccountSession.swift`. Public keys and cloud URLs come from `apps/shared/Config/<env>.plist`, copied into the bundle as `AccountConfig.plist` by `project.yml`. Debug selects dev; Release selects main. See [environments](environments-and-deployment.md).++Confirm Google sign-in, Native API and the native app registrations in the intended Clerk instance. macOS uses `com.pokai.Codync`, iOS uses `com.pokai.Codync.ios`, with their matching `://callback` URLs. Dashboard configuration and actual OAuth consent must be verified independently of the checked-in plist. Do not bundle Clerk secret keys.## Flow@@ -38,7 +25,7 @@ The custom account menu displays the authenticated email and avatar whenavailable. `AccountSession.sessionToken()` hands the session JWT to the Codynccloud client. A Clerk session never authorizes a computer by itself: eachcomputer approves each device after comparing a 6-digit code-([remote-relay-spec.md](../reference/remote-relay.md) §4.2). Conversations are not uploaded.+([remote relay protocol](../reference/remote-relay.md) §4.2). Conversations are not uploaded.## Verification@@ -64,7 +51,7 @@ Its top-left button opens Accounts; Computers & settings is a separate destinatiinside that sheet. The iOS native application must be registered in the same Clerkinstance with bundle ID `com.pokai.Codync.ios` and its own callback`com.pokai.Codync.ios://callback`. The iOS public configuration is in-`apps/ios/Resources/AccountConfig.plist`. The repository configuration does not prove+`apps/shared/Config/<env>.plist`. The repository configuration does not provethat the corresponding Clerk Dashboard registration has been completed.To retain several accounts at once, enable multi-session support in the Clerk@@ -107,16 +94,10 @@ resolve the target, `ssh-keygen -F` against `~/.ssh/known_hosts` andA changed host key or a different computer ID blocks the connection. Debug builds run`SSH.selfCheck()` at launch (argv, `ssh -G` parsing, validation).-## Local verification on 2026-09-25--- iOS Simulator build succeeded with normal simulator signing. Do not use- `CODE_SIGNING_ALLOWED=NO` for a Clerk runtime smoke test: an unsigned simulator- installation failed Keychain initialization with OSStatus -34018.-- The app launches, the top-left Accounts sheet opens, and its Computers & settings- destination navigates successfully in iPhone 17 Pro / iOS 26.5 Simulator.-- `swift test --package-path kit` passed. Account storage separation and rejecting- another account's or computer's widget link are now covered by- `PairingStorageTests` (per-context computers, usage and deep links).-- Real Google login, two-account switching, and Clerk Dashboard configuration still- need end-to-end verification with test accounts. No cloud ownership implementation- or Cloudflare deployment was performed in this change.+## Verification boundaries++Build with normal simulator signing for Clerk Keychain access. Test Google consent, cancellation, restoration, two-account switching, per-account cache isolation and sign-out on real test accounts. Build success cannot verify Clerk Dashboard state.++For SSH, verify first-contact fingerprints and changed-key rejection. With ProxyJump/ProxyCommand, establish trust in a terminal first. The app checks that the local forwarding listener belongs to its SSH process. The Mac is not a phone-to-SSH gateway.++Use [Cloudflare testing](cloudflare-testing.md) for remote account approval and relay acceptance.diff --git a/docs/guides/cloudflare-testing.md b/docs/guides/cloudflare-testing.mdnew file mode 100644index 00000000..9efc569f--- /dev/null+++ b/docs/guides/cloudflare-testing.md@@ -0,0 +1,64 @@+# Testing the Cloudflare path++The remote channel, account approval and relay implementation exist. You can begin testing the **development** path after the prerequisites below. A successful iOS build/install is not an end-to-end relay result. Production configuration remains incomplete; see [environments](environments-and-deployment.md).++## Prerequisites++- Run matching app/host major versions and replace old running processes after installation ([development](development.md)).+- Point both app and host at the intended cloud. Debug app configuration uses `https://dev-api.codync.dev`; check `codync-host cloud` on the computer. Enable/configure it through **Reach from anywhere** or the CLI when needed.+- Keep the computer awake, online, and its host running. Ensure the selected agent works locally first.+- Pair through a fresh QR, or sign in and approve device access by comparing the six-digit code on the computer. A Google login alone does not authorize access.++## Prove traffic uses the relay++The client tries direct connectivity before falling back to Cloudflare. Successful chat on the same Wi-Fi can therefore exercise only the direct path.++1. Start with one paired computer and confirm its bot list loads.+2. On the phone, disable Wi-Fi and use cellular. Disable a VPN/Tailscale route to this computer for this scenario. Leave the host online.+3. Check the computer's connection route in the app. The cloud icon means relay (accessibility label: “Through the encrypted relay”); the Wi-Fi icon means direct. Require **relay** rather than direct or loopback; correlate host logs if the UI cannot establish the route.+4. Send a harmless prompt, observe streamed state and the final reply, then close/reopen the app and confirm the transcript catches up without duplicate entries.+5. Return to Wi-Fi and repeat; record whether the route changes. A direct result is valid for the direct scenario only.++Record app/host versions, cloud environment, route, network, scenario and observed result. Do not publish local bearer tokens, pairing links, session JWTs or private keys in logs/screenshots.++## Scenario checklist++| Scenario | Expected observation |+| --- | --- |+| QR pairing | Fresh code authorizes this device; expiry/reuse is rejected |+| Account access | Computer appears for its account; access requires host approval and matching six-digit code |+| Relay chat | Confirmed relay route, streamed updates, final response and reconnect catch-up |+| Network transition | Wi-Fi/cellular change reconnects without duplicate messages |+| Brief connection loss | Header shows connecting smoothly; transient reconnect does not insert a status row above bots |+| Host offline | UI reports unreachable; an eligible queued send follows mailbox behavior when the host returns |+| Cancel queued send | Canceled mailbox message does not execute when host reconnects |+| Device revoke | Revoked device cannot establish authorized access; other authorized devices continue |+| Account switching | Pairings, caches, bot links and widgets remain within the selected account/computer |+| APNs | With notification permission, background completion/approval notification arrives and opens the correct chat |++Mailbox is for eligible offline `send` messages, not general offline RPC. Retry/deduplication uses `clientNonce`; do not infer mailbox success merely from a local pending bubble. APNs uses the separate `relay/` service, so relay chat passing does not prove push delivery.++## Repeatable local integration++```sh+cargo build --manifest-path host/Cargo.toml+cd cloud+npm ci+npm test+npm run typecheck+env -u CODYNC_CLOUD npm run e2e+```++The integration runner starts an isolated Wrangler service and real host with temporary state, generated test authentication and a fake ACP agent. `CODYNC_HOST_BIN` can select the host binary; `CODYNC_E2E_CLOUD_PORT` selects the local cloud port. It covers relay pairing/chat/reconnect, mailbox cancellation/deduplication, account claims/approval/revocation, direct channels and bearer access boundaries. Non-loopback rejection coverage can be skipped when no suitable interface exists; inspect the output.++This runner does not validate a deployed Worker, actual Google consent, APNs or iOS background behavior. Cloud CI runs unit/type checks; run this integration command explicitly for the complete local scenario.++## Troubleshooting++- **Direct works, relay fails:** compare cloud URLs, cloud enablement, registration status and host logs.+- **Signed in, no access:** check account ownership and the host's pending approval; compare the displayed code before approving.+- **Old UI/protocol:** stop stale Mac/host copies and relaunch the installed phone process.+- **Chat works, push fails:** inspect notification permission and APNs configuration separately.+- **Release fails while Debug works:** inspect the main environment's empty configuration before diagnosing networking.++Protocol details and security boundaries: [remote relay reference](../reference/remote-relay.md). Account/SSH behavior: [accounts and SSH](accounts-and-ssh.md).diff --git a/docs/guides/development.md b/docs/guides/development.mdnew file mode 100644index 00000000..cf61fd1c--- /dev/null+++ b/docs/guides/development.md@@ -0,0 +1,58 @@+# Development and validation++Run commands from the repository root unless a block changes directory. See [file structure](../architecture/file-structure.md) for ownership and [environment configuration](environments-and-deployment.md) before testing cloud access.++## Apple apps++Install Xcode and XcodeGen, then generate the project from its source:++```sh+xcodegen generate+xcodebuild build -project Codync.xcodeproj -scheme macOS -configuration Debug -derivedDataPath build/dd+```++Use the `iOS` scheme with a connected device or simulator in Xcode. CLI builds accept `-destination 'platform=iOS,id=<device-id>'`. Do not edit `project.pbxproj` directly. Keep normal simulator signing: Clerk uses Keychain, and unsigned simulator builds can fail initialization with OSStatus -34018.++Before launching a newly built Mac app, quit running copies, including DerivedData copies:++```sh+osascript -e 'tell application id "com.pokai.Codync" to quit'+pkill -x Codync+open build/dd/Build/Products/Debug/Codync.app+```++`pkill` can return nonzero when no process exists. If the development launch agent is installed, restart the embedded host and inspect other host processes for stale binaries:++```sh+launchctl kickstart -k gui/$(id -u)/com.pokai.codync.host+pgrep -fl codync-host+```++Install the device build and replace the old iPhone process (substitute its device ID):++```sh+xcrun devicectl device install app --device <device-id> build/dd/Build/Products/Debug-iphoneos/Codync.app+xcrun devicectl device process launch --terminate-existing --device <device-id> com.pokai.Codync.ios+```++Unlock the phone when required. Build, install, launch, and visual inspection are separate checks; report which actually completed.++## Component checks++| Component | Commands | Requirements |+| --- | --- | --- |+| Host | `cd host && cargo build` | Rust toolchain supporting edition 2024 |+| Host checks | `cd host && cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test` | Local agent credentials are unnecessary for unit tests |+| Shared Swift | `swift test --package-path kit` | Swift 6 / Xcode |+| Cloud | `cd cloud && npm ci && npm test && npm run typecheck` | Node and npm; CI uses Node 24 |+| Cloud integration | `cd cloud && env -u CODYNC_CLOUD npm run e2e` | Built host; see [Cloudflare testing](cloudflare-testing.md) |+| APNs relay | `cd relay && npm ci && npm test && npm run typecheck` | Separate package from `cloud/` |+| Linux desktop | `cd apps/linux && cargo test` | GTK 4 and libadwaita development packages |++Host development: `cargo run --manifest-path host/Cargo.toml -- serve`. Avoid competing with an installed host on port 19222; isolated tests should use a temporary `CODYNC_HOME` and another port. Stop test hosts when finished.++## Visual checks++Follow [UI conventions](../design/ui-conventions.md) for native toolbar behavior and [widget design](../design/mobile-widgets.md) for previews. Widget images can be rendered with `python3 tools/render-widgets.py`; output is under `build/widget-previews/`.++For releases, increment `CURRENT_PROJECT_VERSION` before another App Store upload. Versions are defined in `project.yml`; keep the host package version aligned with `MARKETING_VERSION`, then regenerate the Xcode project.diff --git a/docs/guides/environments-and-deployment.md b/docs/guides/environments-and-deployment.mdnew file mode 100644index 00000000..3eeca853--- /dev/null+++ b/docs/guides/environments-and-deployment.md@@ -0,0 +1,37 @@+# Environments and deployment++Reviewed against repository configuration on 2026-09-26. Checked-in configuration does not prove that a deployment is healthy or that an external dashboard is configured.++## Configuration ownership++| Layer | Source | Selection |+| --- | --- | --- |+| Apple app | `apps/shared/Config/dev.plist`, `main.plist` | `project.yml` copies the selected file to bundled `AccountConfig.plist`; Debug uses dev, Release uses main |+| Account SDK | `apps/shared/AccountSession.swift` | Public Clerk configuration; development environment overrides are supported |+| Host | `host/src/cloud.rs` | `CODYNC_CLOUD=off` or stored disable wins; then `CODYNC_CLOUD_URL`, stored URL, compiled default |+| Cloud Worker / D1 / DO | `cloud/wrangler.toml` | Root production, `dev`, or `local` environment |+| APNs Worker | `relay/wrangler.toml` | Separate deployment and secrets; see [relay README](../../relay/README.md) |++The host currently has no compiled cloud URL default. Use the Mac's **Reach from anywhere** control or `codync-host cloud --url https://dev-api.codync.dev` to configure it. `codync-host cloud` displays status; `--disable` turns access off. App and host must point at the same intended cloud.++## Checked-in readiness++- **Development:** app configuration and Worker configuration target `https://dev-api.codync.dev`; dev Clerk issuer and D1 binding are configured in source. Exercise the live path before claiming readiness.+- **Production:** `apps/shared/Config/main.plist` has empty cloud/Clerk values. Root Worker configuration still contains production Clerk issuer and D1 ID placeholders. Release remote access is not ready from these files alone.+- **Production route placement:** `routes` currently follows `[[migrations]]` in `cloud/wrangler.toml`, so TOML attaches it to that migration rather than the root Worker. Wrangler reports an unexpected `routes` field. Move the production route to the root table before production deployment. The dev route is explicitly under `[env.dev]`.+- **Local:** Wrangler's `local` environment supports the isolated integration test and its test issuer. It is not a real Google sign-in test.++## Deployment procedure++Use [cloud/README.md](../../cloud/README.md) for exact Wrangler commands and binding names. Select the environment before changing anything:++1. Confirm the intended Cloudflare account, Worker, route, D1 database and Clerk issuer.+2. Create the database only if it does not exist; use its actual ID in the correct environment.+3. Apply migrations from `cloud/migrations/` to that environment.+4. Run cloud unit tests, type checking and the local integration test.+5. Deploy using `npm run deploy:dev` or `npm run deploy:main` from `cloud/` when deployment is intended.+6. Check the deployed health endpoint, then complete the device scenarios in [Cloudflare testing](cloudflare-testing.md).++Production also needs completed Apple native application registrations in Clerk and populated main app configuration. Publishable keys are public configuration; Clerk secret keys and APNs credentials do not belong in app bundles or documentation. Configure APNs using the separate relay guide.++A healthy HTTP endpoint proves Worker reachability only. It does not prove host registration, encrypted channel traffic, account approval, notification delivery or background reconnection.diff --git a/docs/reference/fixtures/README.md b/docs/reference/fixtures/README.mdnew file mode 100644index 00000000..9f28786f--- /dev/null+++ b/docs/reference/fixtures/README.md@@ -0,0 +1,20 @@+# Shared cryptographic fixtures++[remote-relay-vectors.json](remote-relay-vectors.json) contains deterministic protocol-v1 vectors for host/device keys, handshake, frame encryption, chunking, SAS, pairing offers, mailbox, request signatures, claims, signed ACL and sealed push.++The private values are fixed **test seeds**, not live credentials. Changing these bytes changes the common contract checked by Rust, Swift and TypeScript.++[remote-relay-vectors.py](remote-relay-vectors.py) prints the JSON to stdout and requires Python 3 plus `cryptography`. To compare without overwriting the checked-in fixture, from the repository root:++```sh+python3 docs/reference/fixtures/remote-relay-vectors.py > /tmp/codync-relay-vectors.json+cmp docs/reference/fixtures/remote-relay-vectors.json /tmp/codync-relay-vectors.json+```++Consumers:++- `host/src/crypto.rs` (`include_str!`)+- `kit/Tests/CodyncKitTests/RelayVectorsTests.swift`+- `cloud/test/vectors.test.ts` and `cloud/test/relay.test.ts`++When moving or changing a fixture, update those paths and the cloud/kit/host CI path filters. Run the affected vector tests; a Markdown link check alone cannot validate executable imports. [Protocol reference](../remote-relay.md).diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.mdindex af12488d..af9912a3 100644--- a/docs/reference/remote-relay.md+++ b/docs/reference/remote-relay.md@@ -1,12 +1,8 @@-# 遠端連線實作規格:Cloudflare 中繼(主要)、直連(替代)、帳號與 SSH+# Remote relay protocol-日期:2026-09-25(rev 2:安全與可實作性審查後修訂)-狀態:**實作規格**,交給平行的 CLOUD/HOST/APPLE-KIT/APPLE-APPS 四條 track。與 [帳號與裝置計畫](../archive/cloudflare-account-device-plan-2026-09-25.md)、[SSH 計畫](../archive/bot-computer-ssh-plan-2026-09-25.md) 衝突時,以本文件為準。-測試向量:[remote-relay-vectors.json](fixtures/remote-relay-vectors.json)(由 [remote-relay-vectors.py](fixtures/remote-relay-vectors.py) 以固定種子產生,`python3` + `cryptography`;三種語言的實作都必須逐欄通過)。+Reviewed 2026-09-26. This reference preserves the channel's numbered wire-contract sections. It describes the implemented architecture; it is not a deployment acceptance report. Historical work assignments and proposed SDK definitions have been replaced by source entry points.-本文件中「必須/不得」是介面契約;沒有寫到的內部結構由各 track 自行決定。各 track 之間**只透過本文件溝通**,發現本文件有矛盾或缺漏時停下回報,不要自行發明另一套 wire format。-----+Shared deterministic [vectors](fixtures/remote-relay-vectors.json) and their [generator](fixtures/remote-relay-vectors.py) are consumed by Rust, Swift and TypeScript; see [fixture maintenance](fixtures/README.md).## 0. 決策摘要@@ -17,14 +13,13 @@| D3 | 每台 computer 一個 Durable Object(SQLite storage、WebSocket Hibernation):presence、轉送密文、離線 mailbox(手機→電腦,24h TTL,可取消,依序投遞,ack 後刪除)。電腦→手機的補送仍由 host 的 `rev`/events 語意負責。 | 符合產品決策;DO 不保存聊天。 || D4 | **Host 是授權的唯一權威**。host 在本機 SQLite 保存「已授權裝置」表;**只有兩條路能新增列**:本機 QR 配對(§4.1)與 host 自己的核准動作(`decideAccessRequest` approve,§4.2 B)。雲端 state **只能縮短**授權(刪除列、延長既有列的 lease),永遠不能新增。host 把此表簽成 **ACL** 發佈到自己的 DO,DO 據此放行 WebSocket;E2E 握手時 host 再驗一次。 | 無帳號模式也能用中繼(host 以機器金鑰向雲端註冊,不需帳號);雲端被攻破也無法新增可解密的裝置(新增要 host 本機的使用者動作、ACL 要 host 簽、握手要 host 私鑰);撤權有兩道即時關卡(DO 封鎖 + host 關 channel)。 || D5 | **Computer ID 由 host 簽章公鑰推導**:`computerId = b64url(SHA-256(hostSignPub)[0..16])`。不由雲端分配。 | 自我驗證、離線可得、無法被搶註;DO 名稱可直接推導。代價:換 host 金鑰 = 新 computer(見 §3.5)。 |-| D6 | 帳號 → Computers → Bots:新增 `AccountStore`(`[ComputerID: BotStore]`),`BotReference = accountId + computerId + botId`。 | 產品決策 5。 |+| D6 | 帳號 → Computers → Bots:`AccountStore`(`[ComputerID: BotStore]`),`BotReference = accountId + computerId + botId`。 | 依帳號與電腦隔離狀態。 || D7 | 共用 bearer token(`~/.codync/token`)**只接受 loopback 連線**(Mac App 本機、SSH tunnel、statusline、MCP、TUI、Linux App)。手機與其他遠端 client 一律走 E2E channel。 | 移除「一個 token 開所有手機」的舊模型;不留相容路徑。 || D8 | SSH:macOS App 以系統 OpenSSH `-L` 轉發到遠端 host 的 loopback API;遠端側看到的是 loopback 呼叫者,所以 SSH 帳號等同本機使用者權限(能讀 `~/.codync/token` 的人本來就有這權限)。 | 產品決策 6;重用 loopback API,不需要額外授權層。 |-| D9 | 正式發布前維持 **2.x**(目前 `2.2.0`,`MARKETING_VERSION`、`host/Cargo.toml`):尚無公開使用者,不必為協定變更升 major。 | 正式發布後才依 CLAUDE.md 規則管理 major 相容性。 || D10 | **推播內容也加密**:host 以裝置註冊的 X25519 push key 封裝通知標題/內文(§6.7),APNs 只帶通用文字 + `mutable-content`,iOS Notification Service Extension 解開。Live Activity 只推狀態 enum,不推自由文字。 | 決策 2:Cloudflare(`relay/`)只看得到密文。 |**審查後的取捨(rev 2)**:-- 撤權後的 DO 解封鎖以 **grantId** 判斷(新核准才解),不比較時間戳(見 §7.3);比 `stateAt` 方案少一個跨時鐘欄位。+- 撤權後的 DO 解封鎖以 **grantId** 判斷(新 grant 或本機配對的 null grant),不比較時間戳(見 §7.3);比 `stateAt` 方案少一個跨時鐘欄位。- Mailbox 不在 host 端追蹤已見過的 `epk`:重用 epk 的洩漏發生在送出端、密文已在雲端,host 拒收也無法補救;改以 client 端 MUST(§6.4)與測試保證。- SSH 目標設了 `ProxyJump`/`ProxyCommand` 時不做 keyscan、也不做 `SSH_ASKPASS` 首次確認:要求使用者先在終端機連過一次(host key 已在 `~/.ssh/known_hosts`)。少見情境,換來不必實作 askpass helper。- 推播選擇「加密 + NSE」而非「只送通用文字」:保留 Grok Bot 式的通知預覽。@@ -55,25 +50,20 @@----## 2. Track 分工與檔案所有權--| Track | 獨占路徑 | 產出 |-|---|---|---|-| **CLOUD** | `cloud/**`(新建)、`relay/**`(只改 §6.7 的 `mutableContent` 透傳)、`.github/workflows/cloud.yml`(新建) | Worker(`/v1` API + Clerk + D1)、`ComputerRelay` DO、migrations、vitest、e2e 測試、`cloud/README.md`、CI |-| **HOST** | `host/**`、`.github/workflows/host.yml` | identity、channel、relay client、cloud client、逐裝置授權、loopback-only token、CLI |-| **APPLE-KIT** | `kit/**`、`.github/workflows/kit.yml`(新建,`swift test`) | `DeviceIdentity`、channel 加密、`HostTransport`、`HostConnector`、`CloudClient`、`AccountStore`、`BotStore` 調整、models |-| **APPLE-APPS** | `apps/ios/**`(含 `apps/ios/Widgets`、新 `apps/ios/NotificationService`)、`apps/macos/**`、`apps/shared/**`、`project.yml`、`Codync.xcodeproj`(只經 `xcodegen generate`)、`docs/guides/accounts-and-ssh.md`、`.github/workflows/release-macos.yml` | UI、帳號流程、Mac 核准介面、SSH、Notification Service Extension、entitlements、設定檔 |-- `relay/`(APNs 推播)只加一個欄位:`/push` body 的 `mutableContent: true` → `aps["mutable-content"] = 1`。其他不變。推播撤權由 host 端「ticket 綁定 deviceKey、撤權即刪」達成(§9.4)。-- `docs/architecture/file-structure.md` 的 `cloud/` 一行已由本規格作者加入。-- `apps/linux/**`、`apps/screen*/**`:不動(它們只用 loopback token / unix socket)。-- 共用唯讀檔:`docs/reference/remote-relay.md`、`docs/reference/fixtures/remote-relay-vectors.json`。任何 track 要改它們 → 回報 orchestrator,不自行修改。-- `CLAUDE.md`、`docs/archive/cloudflare-account-device-plan-2026-09-25.md`、`docs/archive/bot-computer-ssh-plan-2026-09-25.md`:由本規格作者更新;各 track 不改。-- 版本:HOST 把 `host/Cargo.toml` 的 `version` 設為 `2.2.0`;APPLE-APPS 把 `project.yml` 的 `MARKETING_VERSION` 設為 `2.2.0`(`CURRENT_PROJECT_VERSION` 只在上傳時遞增)。+## 2. Implementation map-**順序**:四條 track 同時開始,各自以 `remote-relay-vectors.json` 做單元測試,互不等待。APPLE-APPS 依賴 APPLE-KIT 的公開 API(§10.1 已定死簽章),可先以本文件寫 UI,kit 完成後接上。跨 track 整合測試(§12.1)由 CLOUD 擁有,在 HOST 合併後執行。+| Area | Source |+| --- | --- |+| Worker API / authentication / DO | `cloud/src/api.ts`, `auth.ts`, `relay.ts` |+| Cloud schema | `cloud/migrations/` |+| Host identity / crypto / channel | `host/src/identity.rs`, `crypto.rs`, `channel.rs` |+| Host cloud / relay | `host/src/cloud.rs`, `relay.rs` |+| Swift transports / identity | `kit/Sources/CodyncKit/Client/` |+| Account and per-computer state | `kit/Sources/CodyncUI/` |+| Apple account integration | `apps/shared/AccountSession.swift` |----+See [architecture](../architecture/overview.md) and [file structure](../architecture/file-structure.md). Application/host compatibility follows their major version; channel `v`, QR version and Worker package version are separate values.## 3. 身分與金鑰@@ -176,7 +166,7 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair**B. 手機取得存取權**(commit-then-reveal SAS,ZRTP/BLE numeric comparison 同型):1. 手機登入後 `POST /v1/devices`(Clerk + 該 device key 的 `Codync-Sig`)。-2. `GET /v1/computers`(帶 `Codync-Sig` 則回傳每台的 `access`)。+2. `GET /v1/computers`(帶 `Codync-Sig` 則回傳每台的 `access`)。 iPhone 的 Bots 首頁直接列出尚未連線的帳號電腦,點 **Connect** 進入存取申請,不需掃 QR Code;核准後顯示該電腦的 bots。首次裝置授權仍由電腦上的使用者確認。3. 對 `access == "none"` 的電腦:手機產生 32 random bytes `nD`(只存記憶體),`POST /v1/computers/{id}/access-requests {"commit": b64url(SHA-256("codync/sascommit/v1" ‖ dk ‖ nD))}` → `{requestId, expiresAt}`。4. Worker 通知 DO → host 拉 state → 看到新申請(含 `commit`)→ host 產生 32 random bytes `nH`(存本機記憶體,每個 requestId 只產生一次)→ `POST /v1/host/access-requests/{id}/nonce {"nonce": nH}`(已有 host nonce → `409 conflict`,host 不得換)。5. 手機輪詢 `GET /v1/access-requests/{id}`(每 2 秒)→ 出現 `hostNonce` 後才 `POST /v1/access-requests/{id}/reveal {"nonce": nD}` → Worker 存入並通知 DO `cloud.changed`。手機此時計算 SAS 顯示「在電腦上確認代碼 123456」。@@ -188,7 +178,7 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair### 4.3 授權表與 ACL(host 為權威)-host 的授權裝置表(§9.2)每一列:`key, name, platform, source(local|account), grant_id, scopes, lease_until`。+host 的授權裝置表(`host/src/devices.rs`)每一列:`key, name, platform, source(local|account), grant_id, scopes, lease_until`。規則(**雲端只能縮短授權,不能新增**):- 新增列只有兩條路:§4.1 的 `pair`(`source=local`,`grant_id=NULL`)與 §4.2 B 的 host 核准(`source=account`,`grant_id` = decision 回傳值,`key` = host 顯示給使用者的 dk)。@@ -354,7 +344,7 @@ sealed = b64url(epk ‖ ct)Worker → DO 的轉送**不沿用 client 的 URL**:Worker 自己建立新 request `new Request("https://do/relay", {headers})`(只帶 `Upgrade`、`Sec-WebSocket-*` 與下列內部 header),交給 `env.RELAY.get(env.RELAY.idFromName(computerId))`。內部 header:`X-Codync-Internal: 1`、`X-Codync-Role`、`X-Codync-Key`、`X-Codync-Nonce`、`X-Codync-Ts`、`X-Codync-Pair`(offerId 或空)、`X-Codync-Computer`。DO 只以 pathname 完全等於 `/relay`、`/internal/block`、`/internal/changed` 路由,且全部要求 `X-Codync-Internal: 1`;其他 → `404`。因為 client 的 request 永遠不會被原樣轉進 DO,外部無法觸及 `/internal/*`。DO 檢查 nonce 重放後才 `acceptWebSocket`。Device 准入(DO):-- `dk` 在 `blocked` 表 → `403`。+- 一般 socket 的 `dk` 在 `blocked` 表 → `403`;pairing socket 仍可申請配對。- `pair` 參數存在:`offerId` 必須在 ACL `offers` 且未過期;同時最多 2 條 pairing socket,每條最長 120 秒、最多 16 則訊息;不能 `mbox.*`。- 否則 `dk` 必須列在最新 ACL 的 `devices`。**DO 不看 lease**:lease 只由 host 在握手與每個 request 時判斷,所以 host 離線多久,帳號裝置都能連上 DO 看 presence、用 mailbox(host 上線後處理 `mbox.item` 時再驗一次)。- DO 從未收過 ACL(host 從未連過)→ `404 {"error":{"code":"unknownComputer"}}`。@@ -376,7 +366,7 @@ Host → DO:| `t` | 欄位 | 行為 ||---|---|---|-| `acl` | `d`(ACL JSON bytes 的 b64url), `sig` | DO 以 host kid 驗簽、`computerId` 必須相符 → 否則 `{"t":"error","code":"badAcl","ver":<已存>}`。`ver` ≤ 已存 ver → `{"t":"error","code":"staleVersion","ver":<已存>}`,host 設 `acl_ver = max(本機, ver) + 1` 重新簽發。成功 → 存起來;以 `4003 revoked` 關閉 dk 不再列在 `devices` 的一般 socket;以 `4410 pairingExpired` 關閉其 offer 不再列在 `offers` 的 pairing socket;**解除封鎖只在**新 ACL 以「不同且非 null 的 `grant`」列出被封鎖的 dk 時(即 host 做了一次新的核准;`blocked` 表存 `(dk, grant_id)`);回 `{"t":"acl.ok","ver":N}` |+| `acl` | `d`(ACL JSON bytes 的 b64url), `sig` | DO 以 host kid 驗簽、`computerId` 必須相符 → 否則 `{"t":"error","code":"badAcl","ver":<已存>}`。`ver` ≤ 已存 ver → `{"t":"error","code":"staleVersion","ver":<已存>}`,host 設 `acl_ver = max(本機, ver) + 1` 重新簽發。成功 → 存起來;以 `4003 revoked` 關閉 dk 不再列在 `devices` 的一般 socket;以 `4410 pairingExpired` 關閉其 offer 不再列在 `offers` 的 pairing socket;**解除封鎖在**新 ACL 以「null(本機配對)或不同的 `grant`」列出被封鎖的 dk 時(即 host 做了一次新的核准;`blocked` 表存 `(dk, grant_id)`);回 `{"t":"acl.ok","ver":N}` || `ready` | — | host 已完成 state 拉取(§4.3)並發佈 ACL。DO 把 host attachment 設 `ready:true`、送 `presence online:true` 給所有 device、對每條 device socket 送 `open`、開始送 mailbox。之後新接受的 device socket 立即送 `open` || `data` | `link`, `m`(channel 訊息物件) | host 必須 ready;將 `m` 原樣(`JSON.stringify(m)`)送到該 link 的 device socket || `close` | `link`, `code`, `reason` | 關閉該 device socket |@@ -423,7 +413,7 @@ Channel 訊息與 DO 訊息的 `t` 值不重疊:channel 只有 `hello`/`welcom2. 都失敗且有 `cloud` → 連 `{cloud}/v1/relay/device/{computerId}`。每次收到 `presence online:true` 就(重新)送 `hello`;`online:false` → 狀態 `computerOffline(lastSeen)`,保持 socket(可用 mailbox),等下一個 `online:true`。3. 兩者都不可用 → `offline("Can't reach …")`,退避重試。4. App 回前景、網路路徑改變(`NWPathMonitor`)→ 重新跑 1–3(可能從中繼換回直連);events 以當前 `rev` 重新訂閱。-5. 每次 inner `hello` 成功後,把回應的 `urls`、`cloud`、`device`、`name`、`boxKey` 合併進持久化的 `Computer`(§3.3、§10.2);帳號來源的 computer 因此在第一次中繼連線後也能試 LAN 直連。+5. 每次 inner `hello` 成功後,把回應的 `urls`、`cloud`、`device`、`name`、`boxKey` 合併進持久化的 `Computer`(§3.3、§10);帳號來源的 computer 因此在第一次中繼連線後也能試 LAN 直連。### 7.6 心跳、重連、限流@@ -447,185 +437,9 @@ Close code 總表:`1000` 正常、`1011` 內部錯誤/逾時、`4001 unautho----## 8. CLOUD track:`cloud/`+## 8. Cloud HTTP API-### 8.1 結構與設定--```-cloud/- package.json tsconfig.json wrangler.toml README.md- migrations/0001_init.sql- src/index.ts 路由(可用 hono,或像 relay/ 一樣手寫)- src/auth.ts Clerk 驗證、Codync-Sig 驗證- src/api.ts /v1 handlers- src/relay.ts ComputerRelay Durable Object- test/*.test.ts vitest + @cloudflare/vitest-pool-workers- test/e2e/relay.e2e.ts 跨 track 整合測試-```-依賴:`@clerk/backend`、`svix`(webhook);測試:`vitest`、`@cloudflare/vitest-pool-workers`、`@noble/curves`、`@noble/ciphers`、`@noble/hashes`。Worker 端 Ed25519 驗證用 WebCrypto,不引入加密套件。--`wrangler.toml`:-```toml-name = "codync-cloud"-main = "src/index.ts"-compatibility_date = "2026-09-01"-compatibility_flags = ["nodejs_compat"]--[[migrations]]-tag = "v1"-new_sqlite_classes = ["ComputerRelay"]--# production(部署需 owner 確認)-[vars]-CLERK_ISSUER = "<production Clerk Frontend API URL>"-[[d1_databases]]-binding = "DB"-database_name = "codync"-database_id = "<production id>"-migrations_dir = "migrations"-[[durable_objects.bindings]]-name = "RELAY"-class_name = "ComputerRelay"-[triggers]-crons = ["*/15 * * * *"]--[env.dev]-vars = { CLERK_ISSUER = "https://sunny-mollusk-8651.clerk.accounts.dev" }-d1_databases = [{ binding = "DB", database_name = "codync-dev", database_id = "<由 wrangler d1 create 取得>", migrations_dir = "migrations" }]-durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]-triggers = { crons = ["*/15 * * * *"] }--[env.dev] # wrangler dev / e2e:本機 D1,CLERK_JWT_KEY 由測試注入-vars = { CLERK_ISSUER = "https://clerk.test.local" }-d1_databases = [{ binding = "DB", database_name = "codync-dev", database_id = "dev", migrations_dir = "migrations" }]-durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]-```-Worker 名稱:production `codync-cloud`,dev `codync-cloud-dev`。--### 8.2 D1 schema(`migrations/0001_init.sql`)--```sql-CREATE TABLE accounts (- user_id TEXT PRIMARY KEY, -- Clerk sub- email TEXT,- status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active','deleted')),- created_at INTEGER NOT NULL,- deleted_at INTEGER-);--CREATE TABLE computers (- id TEXT PRIMARY KEY, -- computerId- sign_pub TEXT NOT NULL UNIQUE,- box_pub TEXT NOT NULL,- owner_user_id TEXT REFERENCES accounts(user_id),- name TEXT NOT NULL,- platform TEXT NOT NULL CHECK (platform IN ('macos','linux')),- device TEXT, -- laptop|macmini|…|linux(host 的 Device)- version TEXT NOT NULL,- status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active','blocked')),- online INTEGER NOT NULL DEFAULT 0, -- DO 寫入- last_seen_at INTEGER, -- DO 寫入- claimed_at INTEGER,- created_at INTEGER NOT NULL,- updated_at INTEGER NOT NULL-);-CREATE INDEX computers_owner ON computers(owner_user_id);--CREATE TABLE devices (- id TEXT PRIMARY KEY, -- dev_…- owner_user_id TEXT NOT NULL REFERENCES accounts(user_id),- sign_pub TEXT NOT NULL,- name TEXT NOT NULL,- platform TEXT NOT NULL CHECK (platform IN ('ios','macos')),- created_at INTEGER NOT NULL,- last_used_at INTEGER,- revoked_at INTEGER,- UNIQUE (owner_user_id, sign_pub)-);--CREATE TABLE claims (- id TEXT PRIMARY KEY, -- clm_…- user_id TEXT NOT NULL REFERENCES accounts(user_id),- nonce TEXT NOT NULL,- expires_at INTEGER NOT NULL,- consumed_at INTEGER,- computer_id TEXT-);--CREATE TABLE access_requests (- id TEXT PRIMARY KEY, -- req_…- computer_id TEXT NOT NULL REFERENCES computers(id),- device_id TEXT NOT NULL REFERENCES devices(id),- user_id TEXT NOT NULL REFERENCES accounts(user_id),- status TEXT NOT NULL CHECK (status IN ('pending','approved','denied','expired','cancelled')),- commit_hash TEXT NOT NULL, -- SHA-256("codync/sascommit/v1" ‖ dk ‖ nD)- host_nonce TEXT, -- nH,host 設一次- device_nonce TEXT, -- nD,host_nonce 存在後裝置才可設- created_at INTEGER NOT NULL,- expires_at INTEGER NOT NULL, -- created_at + 10 min- decided_at INTEGER,- grant_id TEXT-);-CREATE INDEX access_requests_computer ON access_requests(computer_id, status);-CREATE UNIQUE INDEX access_requests_one_pending ON access_requests(computer_id, device_id) WHERE status = 'pending';--CREATE TABLE grants (- id TEXT PRIMARY KEY, -- grt_…- computer_id TEXT NOT NULL REFERENCES computers(id),- device_id TEXT NOT NULL REFERENCES devices(id),- scopes TEXT NOT NULL, -- JSON array- status TEXT NOT NULL CHECK (status IN ('active','revoked')),- created_at INTEGER NOT NULL,- revoked_at INTEGER,- revoked_reason TEXT -- owner|deviceRevoked|unclaimed|accountDeleted-);-CREATE UNIQUE INDEX grants_active ON grants(computer_id, device_id) WHERE status = 'active';--CREATE TABLE sig_nonces (- kid TEXT NOT NULL,- nonce TEXT NOT NULL,- expires_at INTEGER NOT NULL,- PRIMARY KEY (kid, nonce)-);--CREATE TABLE processed_events (- provider TEXT NOT NULL,- event_id TEXT NOT NULL,- processed_at INTEGER NOT NULL,- PRIMARY KEY (provider, event_id)-);--CREATE TABLE audit_events (- id INTEGER PRIMARY KEY AUTOINCREMENT,- actor TEXT NOT NULL, -- user_id / computer:<id> / system- action TEXT NOT NULL,- target TEXT,- result TEXT NOT NULL,- created_at INTEGER NOT NULL-);-CREATE INDEX audit_time ON audit_events(created_at);-```--原子性要求(每項以單一 `db.batch([...])` 完成,並檢查 `meta.changes`):-- **claim complete**:`UPDATE claims SET consumed_at=?t, computer_id=?c WHERE id=?id AND user_id=?u AND consumed_at IS NULL AND expires_at>?now` → `UPDATE computers SET owner_user_id=?u, claimed_at=?t, updated_at=?t WHERE id=?c AND owner_user_id IS NULL AND EXISTS(SELECT 1 FROM claims WHERE id=?id AND consumed_at=?t)`。第一句 0 changes → `410 claimExpired`;第二句 0 changes 且 owner 已是同一 user → 200(冪等);其他 owner → `409 alreadyClaimed`。-- **approve**:`UPDATE access_requests SET status='approved', decided_at=?, grant_id=?g WHERE id=? AND computer_id=? AND status='pending' AND expires_at>?now` → `INSERT INTO grants (...) SELECT ... WHERE EXISTS(SELECT 1 FROM access_requests WHERE id=? AND grant_id=?g) ON CONFLICT DO NOTHING`;若因 `grants_active` 衝突,回傳既有 active grant。-- **reveal**:`UPDATE access_requests SET device_nonce=? WHERE id=? AND user_id=? AND status='pending' AND host_nonce IS NOT NULL AND device_nonce IS NULL`;0 changes → 依狀態回 `409 conflict`/`410 requestExpired`/`404`。Worker **不**驗 commit(host 驗)。-- **host nonce**:`UPDATE access_requests SET host_nonce=? WHERE id=? AND computer_id=? AND status='pending' AND host_nonce IS NULL`;0 changes → `409 conflict`。-- 所有查詢都帶 owner 範圍;別人的資源一律回 `404 notFound`(不洩漏存在)。建立 access request 同時要求 `computers.owner_user_id = clerk.sub` **且** `devices.owner_user_id = clerk.sub`(device 由 Sig(dev) 的 kid 找出),任一不符 → `404`。--Cron(每 15 分鐘):刪除 `sig_nonces` 過期、`claims` 過期 1 天、`access_requests` pending 過期 → `expired`(同時清空 `host_nonce`/`device_nonce`)、`audit_events` 超過 30 天。--### 8.3 認證--- **Clerk**:`Authorization: Bearer <session JWT>`。以 `@clerk/backend` 的 `verifyToken(token, opts)` 驗證:有 `CLERK_JWT_KEY` 時用 `jwtKey`(networkless,dev/e2e 使用),否則用 `secretKey: CLERK_SECRET_KEY`(自動抓 JWKS、快取、支援輪替);`authorizedParties` 取 `CLERK_AUTHORIZED_PARTIES`(逗號分隔,可空;native token 通常沒有 `azp`,有則必須在清單內)。另外檢查 `iss === CLERK_ISSUER`、`sub` 存在、`sid` 存在。`email` 取自自訂 session claim `email`(owner 在 Clerk 設定,§14.3),缺則為 null。每個 Clerk 請求 `INSERT OR IGNORE INTO accounts`;`status='deleted'` → `403 accountDeleted`。-- **Codync-Sig**:§5。-- **Webhook**:`POST /v1/webhooks/clerk`,`svix` 以 `CLERK_WEBHOOK_SECRET` 驗證,`svix-id` 寫入 `processed_events` 去重。--錯誤格式(所有 `/v1`):-```json-{"error":{"code":"notFound","message":"…"},"requestId":"<cf-ray 或 uuid>"}-```-code 清單:`badRequest`(400) `unauthenticated`(401) `badSignature`(401) `forbidden`(403) `accountDeleted`(403) `notFound`(404) `alreadyClaimed`(409) `conflict`(409) `claimExpired`(410) `requestExpired`(410) `upgradeRequired`(426) `rateLimited`(429) `internal`(500)。+The route table below summarizes the contract. Executable schema and validation live in `cloud/migrations/` and `cloud/src/api.ts`; do not maintain a second copy of the schema here.### 8.4 `/v1` HTTP API@@ -661,475 +475,48 @@ code 清單:`badRequest`(400) `unauthenticated`(401) `badSignature`(401) `forb"requests":[{"requestId","deviceKey","deviceName","platform","email","commit","hostNonce"?,"deviceNonce"?,"createdAt","expiresAt"}]}```grants 只含:grant active、device 未撤銷、device.owner == computer.owner。host 只把它當成「可續約/應刪除」的清單(§4.3)。-- `POST /v1/host/access-requests/{id}/nonce` `{"nonce"}` → `{}`(§8.2;已設過 → `409`)-- `POST /v1/host/grants/{grantId}/revoke` `{}` → `{}`(host 在本機撤銷帳號來源裝置時同步 D1,`revoked_reason='owner'`;失敗只記 `warn`,本機撤銷已生效)-- `POST /v1/host/access-requests/{id}/decision` `{"decision":"approve"|"deny"}` → `{"status","grantId"?}`(§8.2 原子性;request 過期 → `410 requestExpired`;approve 要求 `device_nonce IS NOT NULL`,否則 `409`)+- `POST /v1/host/access-requests/{id}/nonce` `{"nonce"}` → `{}`(`cloud/src/api.ts`;已設過 → `409`)+- `POST /v1/host/grants/{grantId}/revoke` `{}` → `{}`(host 在本機撤銷帳號來源裝置時同步 D1,`revoked_reason='owner'`;失敗記錄並存入 `grant_revokes` 重試,本機撤銷已生效)+- `POST /v1/host/access-requests/{id}/decision` `{"decision":"approve"|"deny"}` → `{"status","grantId"?}`(`cloud/src/api.ts` 的原子更新;request 過期 → `410 requestExpired`;approve 要求 `device_nonce IS NOT NULL`,否則 `409`)- `POST /v1/host/unclaim` `{}` → `{}`(在電腦上移出帳號;同 `DELETE /v1/computers/{id}` 的效果)**Relay**:§7.1。**Webhook**:`user.deleted` → accounts `status='deleted'`、devices 撤銷、grants 撤銷(`accountDeleted`)、computers owner=NULL、DO block + changed。-### 8.5 `ComputerRelay` DO--- DO SQLite 表:`meta(k TEXT PRIMARY KEY, v TEXT)`(`signKey`、`aclVer`、`aclD`、`aclSig`、`lastSeenAt`)、`mailbox(seq INTEGER PRIMARY KEY AUTOINCREMENT, dk TEXT, nonce TEXT, blob BLOB, size INTEGER, exp INTEGER, state TEXT, UNIQUE(dk, nonce))`、`nonces(kid TEXT, nonce TEXT, exp INTEGER, PRIMARY KEY(kid, nonce))`、`blocked(dk TEXT PRIMARY KEY, grant_id TEXT, blocked_at INTEGER)`。-- 內部端點(只經 Worker 自建的 request 呼叫,§7.1):`POST /internal/block {"devices":[{"dk","grantId"}]}`(upsert `blocked`、以 `4003` 關閉相符 socket、送 host `cloud.changed`)、`POST /internal/changed`(送 host `cloud.changed`;host 離線則忽略)。解除封鎖規則見 §7.3 `acl`。-- host 連上/斷線 → `UPDATE computers SET online=?, last_seen_at=? WHERE id=?`(D1 binding;列不存在即 no-op)。-- DO 不解析 `f` 的內容、不保存 channel 訊息。--### 8.6 CLOUD 測試--- 單元(vitest-pool-workers):Codync-Sig 向量(含 authority)、重放、時間窗、跨 authority 拒絕;claim 向量;ACL 驗證(向量 `acl`)、ver 單調與 `staleVersion` 回傳已存 ver;封鎖後以相同 grant 的 ACL 不解封、以新 grant 解封;`computerId` 格式錯誤 400、偽造 `/internal/*` 路徑不可達;access request 跨帳號 computer 404、reveal 早於 host nonce 409、approve 早於 reveal 409;host 未 ready 時 mailbox 仍接受、`data` 丟棄;ready 後新 device socket 立即收到 `open`;host replaced 時 device 收到 false→true presence;claim 競爭(兩帳號同時 complete);approve 雙擊;跨帳號 404;webhook 去重;mailbox 冪等、上限、取消、TTL、依序投遞、host 斷線重送;presence;auto-response;device 准入(封鎖、pairing 限制、offer 消失 → 4410);host 離線超過 15 分鐘帳號裝置仍可 `mbox.put`;`relay/` 的 `mutableContent` 透傳。-- 以 `@noble/*` 在 TS 寫一份 device/host 參考實作(測試用),先通過 `remote-relay-vectors.json`,再用於 e2e。-------## 9. HOST track:`host/src`--### 9.1 新模組--| 檔案 | 內容 |-|---|---|-| `identity.rs` | `Identity { sign: SigningKey, box_secret: StaticSecret }`、`load_or_create(dir)`、`computer_id()`、`sign_pub_b64()`、`box_pub_b64()`、`sign_request(method, path_query, body) -> String`(Codync-Sig header 值) |-| `crypto.rs` | 握手、frame seal/open、chunking、mailbox open、SAS commit/code、offer id、claim 簽章輸入、push seal;全部以向量測試 |-| `channel.rs` | 與傳輸無關的 channel:`run(hub, Transport, ChannelKind)`;握手、授權、inner RPC、訂閱、lease 監看 |-| `relay.rs` | 對 `{cloud}/v1/relay/host` 的出站 WebSocket:ACL 發佈、link 多工、mailbox 處理、重連 |-| `cloud.rs` | `/v1/host/*` HTTP client(`crate::http()`)、state 輪詢、核准決定、`CloudStatus` |-| `devices.rs`(或併入 `store.rs`) | 授權裝置表、`Caller`、`Scope`、`DeviceSource` |--依賴(最新相容版本):`ed25519-dalek`(`rand_core`)、`x25519-dalek`(`static_secrets`)、`chacha20poly1305`、`hkdf`、`rand_core`(`getrandom`)、`tokio-tungstenite`(rustls + webpki roots)、`axum` 開 `ws` feature。注意 `hkdf` 與既有 `sha2 = 0.11` 的 `digest` 版本需一致;必要時 `hkdf` 用自己相容的 `sha2`,不要手寫 HKDF。--### 9.2 Store--`Store::open` 新增 schema 版本(kv `schema`);升到 3 時 `DROP TABLE devices`(舊 push ticket 表,手機重連時會重新註冊)並建立:-```sql-CREATE TABLE devices(- key TEXT PRIMARY KEY, name TEXT NOT NULL, platform TEXT NOT NULL,- source TEXT NOT NULL, grant_id TEXT, scopes TEXT NOT NULL,- lease_until INTEGER, created_at INTEGER NOT NULL, last_seen_at INTEGER);-CREATE TABLE push_tickets(- ticket TEXT PRIMARY KEY, device_key TEXT NOT NULL, push_key TEXT, ctx TEXT, name TEXT, created_at INTEGER NOT NULL);-CREATE TABLE activity_tickets(- ticket TEXT PRIMARY KEY, bot_id TEXT NOT NULL, device_key TEXT NOT NULL, created_at INTEGER NOT NULL);-```-`hub.activities`(記憶體 map)改由 `activity_tickets` 取代。-Rust 以 enum 表示:`DeviceSource { Local, Account }`、`Scope { Control, Screen }`(serde camelCase 字串)。刪除裝置時同一 transaction 刪除其 `push_tickets` 與 `activity_tickets`。kv 新增:`acl_ver`、`cloud_url`、`cloud_enabled`。--`acl_ver` 與 DO 的已存 ver 可能不一致(資料庫被刪、還原,但 `identity.json` 還在):收到 `staleVersion`/`badAcl` 附帶的 `ver` 時,設 `acl_ver = max(acl_ver, ver) + 1` 並重新簽發一次(只重試一次,再失敗記 `error`)。測試:刪除資料庫、保留 identity 後重啟,ACL 能被 DO 接受。--### 9.3 Hub+## 9. Host integration-新增欄位:`identity: Identity`、`auth: watch::Sender<u64>`(裝置表 generation;每次變動 +1,channel 據此重新檢查自己的 dk)、`pairing_codes: Mutex<Vec<PairingCode>>`、`cloud: Mutex<CloudStatus>`、`access_requests: Mutex<Vec<AccessRequest>>`(含 host 自己的 `nH`,只存記憶體;host 重啟後對同一申請 post nonce 會得到 409 → 該申請自動 deny,手機重新申請)。刪除 `activities`(改存 `activity_tickets`,§9.2)。`token` 保留(loopback)。+`host/src/api.rs` dispatches inner methods and enforces caller permissions. Bearer HTTP/SSE is loopback-only; remote callers use the encrypted channel. `host/src/cloud.rs` manages registration, claims, access state and grant revocation retries; `host/src/relay.rs` manages the outgoing relay connection. Inspect these implementations for current method signatures and storage keys.-### 9.4 API 變更(`api.rs`)+`codync-host cloud` reports cloud status; `devices` lists/revokes device access; `access` handles pending approval. `reset-token` rotates the local bearer credential, not remote device grants.-- `authorized()`:只接受 `Authorization: Bearer`(刪除 `?token=`)**且** `peer.ip().to_canonical().is_loopback()`(`--bind ::` 時 IPv4 會以 `::ffff:127.0.0.1` 出現;附單元測試)。`events`/`term_stream`/`statusline` 都要 `ConnectInfo`。-- `dispatch(hub, caller: &Caller, method, body)`;`enum Caller { Local, Device { key: String, scopes: Vec<Scope> }, Pairing { key: String } }`;權限依 §6.6,拒絕回 403。取代今日只針對 `setScreenEnabled` 的特例。-- 抽出 `events_stream(hub, since, client, caller) -> impl Stream<Item = Value>`(SSE 與 channel 共用;`Caller::Device` 看不到 `accessRequests`/`cloud` 事件)與 `term_events(hub, id)`。-- `GET /health` → `{"ok":true,"hostId","computerId","version"}`。-- `GET /channel?v=1`:axum WebSocket,交給 `channel::run`。-- `hello` 回應新增:`computerId`、`signKey`、`boxKey`、`protocol: 1`、`cloud`(啟用時的 cloud URL,否則 null)。events 的 `hello` 事件新增 `computerId`。-- `registerDevice {ticket, name, relay, pushKey, ctx}`:ticket 綁定 `Caller::Device.key`(Local 呼叫則 `device_key = "local"`);`push::notify` 讀 `push_tickets` 並依 §6.7 封裝(沒有 `pushKey` 的 ticket 只收通用文字)。-- `registerActivity`:ticket 寫入 `activity_tickets`,綁定 caller 的 device key;`live_activity_update` 不再送 `activity` 文字。-- 新 loopback 方法:+## 10. Shared Swift integration-| 方法 | body | 回應 |-|---|---|---|-| `pairing` | — | `{"pairingUrl","urls","svg","expiresAt"}`(每次呼叫產生新 code) |-| `devices` | — | `{"devices":[{"key","name","platform","source","scopes","leaseUntil","createdAt","lastSeenAt","connected":bool}]}` |-| `revokeDevice` | `{"key"}` | `{}` |-| `accessRequests` | — | `{"requests":[AccessRequest]}` |-| `decideAccessRequest` | `{"requestId","approve":bool}` | `{}`(approve:`nD` 未驗證 → 409;成功後以 host 顯示的 dk + 回傳的 grantId 新增裝置並發佈 ACL) |-| `claimSign` | `{"claimId","nonce","userId"}` | `{"computerId","signKey","boxKey","name","platform","device","version","sig"}` |-| `unclaim` | — | `{}` |-| `cloudStatus` | — | `CloudStatus` |-| `setCloud` | `{"enabled":bool,"url"?}` | `CloudStatus` |--`AccessRequest = {"requestId","deviceKey","deviceName","platform","email","code"(SAS;`nD` 驗證前為 null),"createdAt","expiresAt"}`-`CloudStatus = {"enabled","url","registered","connected","owner":{"userId","email"}|null,"lastError"}`-新 event(只給 Local):`{"type":"accessRequests","requests":[…]}`、`{"type":"cloud","cloud":CloudStatus}`;不帶 rev(與 `usage`/`screen` 同類)。--### 9.5 Channel(`channel.rs`)--- 同一實作服務兩種傳輸:直連(axum WebSocket)與中繼 link(`relay.rs` 以 mpsc 餵入 `m`、以共用 sink 送出 `{"t":"data","link","m"}`)。-- 流程:等 `hello` → 驗證 → `welcome` → 迴圈:組裝 frame → 解析 inner → request 以 `tokio::spawn` 呼叫 `api::dispatch`(同一 channel 的回應可亂序)→ 回 `ok`/`err`;`sub` 啟動串流任務;`cancel` 中止串流。-- 每個 request 前檢查 dk 仍有效(查 `hub.auth` generation 快取);`watch` 變動 → 立即重查,失效 → 送 `reject`(或 close `4003`)並結束所有串流。`lease_until` 到期時以 timer 主動關閉。-- 第一個成功解密的 frame 之後才標記 connected、更新 `devices.last_seen_at`(§6.2)。-- pairing channel(`Caller::Pairing`):只處理一個 `pair`,回應後以 `4100` 關閉(§4.1)。--### 9.6 Relay 與 cloud client--- cloud URL:env `CODYNC_CLOUD_URL` > kv `cloud_url` > `cloud::DEFAULT_CLOUD_URL: Option<&str>`(目前 `None`,production 部署時填入)。三者皆無 → 雲端停用(不重試、`CloudStatus.enabled=false`)。`CODYNC_CLOUD=off` 一律停用;`host/tests/e2e.rs` 設 `CODYNC_CLOUD=off`。-- 啟動(雲端啟用時):`POST /v1/host/register`(退避重試,最長 30 分鐘間隔)→ 連 `/v1/relay/host` → **state 拉取(§4.3,最多 10 秒)** → 送 `acl` → 等 `acl.ok`(`staleVersion` 處理見 §9.2)→ 送 `ready`。每次重連都走同一順序,並丟棄全部 link 狀態。-- state 拉取:每次 relay 連上時、收到 `cloud.changed` 時、有 owner 時每 5 分鐘;套用 §4.3 規則(只續約/刪除,不新增);對 `hostNonce` 為空的新申請 post nonce(§4.2 B 4);`deviceNonce` 出現時驗 commit、算 SAS、emit `accessRequests`;owner 變更時 emit `cloud` 事件。-- `mbox.item`:依序處理;§6.4 驗證;回 `mbox.ack`(`ok`/`code`)。-- ping 每 30 秒;§7.6 退避與 close code 處理。-- tracing 結構化欄位(`computer_id`、`link`、`error = format!("{e:#}")`);**不記錄**金鑰、密文、pairing code、訊息內容。--### 9.7 CLI--- `codync-host pair [--json]`:改呼叫本機 loopback `pairing`(host 需在執行中,否則明確提示)。JSON:`{"name","computerId","signKey","boxKey","urls","cloud","pairingUrl","expiresAt"}`。-- `codync-host info --json`(不需 host 執行中):`{"name","computerId","signKey","boxKey","version","port","token","running":bool}` — SSH 設定用;`token` 為 loopback token。`info` **只讀** `identity.json` 與 token,絕不建立:檔案不存在 → stderr `start codync-host once first`、exit 1。只有 `serve` 會建立 identity。-- `codync-host access list|approve <requestId|SAS>|deny <requestId>`、`codync-host devices list|revoke <key>`、`codync-host cloud [--enable|--disable] [--url URL]`:皆走 loopback API。-- TUI `--url`:說明改為「遠端請用 SSH tunnel 轉到 loopback」。--### 9.8 HOST 測試--- `crypto.rs`:通過 `remote-relay-vectors.json` 全部欄位(`include_str!("../../docs/reference/fixtures/remote-relay-vectors.json")`)。-- 授權:未知 dk 被拒、pairing 流程(回應後 4100、pairing channel 上非 `pair` 被關)、無 code 時 `pair:true` 在 ECDH 前被拒、code 單次、lease 到期關閉 channel、撤權關閉進行中的 events 訂閱並刪 push/activity tickets、scope 拒絕、loopback-only 方法經 channel 被拒、非 loopback bearer 被拒、`::ffff:127.0.0.1` 視為 loopback。-- state 套用:未知 grant 被忽略(表不變)、已知 grant 續約、缺席者刪除;relay 連上後 state 拉取前帳號裝置握手被拒;relay link 上 `hello.dk != open.dk` 被關;SAS commit 不符自動 deny、reveal 前 approve 被拒。-- `acl_ver`:刪 DB 保留 identity → `staleVersion` 後以 `max+1` 成功。-- `tests/e2e.rs` 延伸:以 Rust 測試端的 device 實作走直連 `/channel`:pair → hello → events → `send`(fake agent)→ 收到回覆。-------## 10. APPLE-KIT track:`kit/`--### 10.1 公開 API(APPLE-APPS 依賴這些名稱與簽章)--```swift-// CodyncKit/Models/Computer.swift-public typealias ComputerID = String-public struct Computer: Codable, Hashable, Sendable, Identifiable {- public var id: ComputerID- public var name: String- public var signKey: String // pin:QR `sk`,或帳號流程 SAS 通過後的 signKey- public var boxKey: String? // pin:只來自 QR `bk` 或 E2E `hello`(§3.3);nil = 尚無 mailbox- public var urls: [String]- public var cloud: URL?- public var device: String?- public var color: String?-}-public struct BotReference: Codable, Hashable, Sendable {- public var accountId: String? // = SharedStore.Context.accountID(原始 Clerk userID;nil = 本機 context)- public var computerId: ComputerID- public var botId: String-}--// CodyncKit/Client/Pairing.swift(取代 HostClient.swift 裡的舊 Pairing)-public struct Pairing: Hashable, Sendable { // 掃到的 QR;暫存,不持久化- public var computer: Computer- public var code: String- public init?(url: URL); public init?(string: String)-}--// CodyncKit/Client/DeviceIdentity.swift-public struct DeviceIdentity: Sendable {- public let publicKey: String // Ed25519,b64url- public let pushKey: String // X25519,b64url(§6.7)- public static func load(context: SharedStore.Context) throws -> DeviceIdentity // 沒有就建立(兩把)- public static func delete(context: SharedStore.Context)- public func signatureHeader(method: String, authority: String, pathAndQuery: String, body: Data) throws -> String- /// NSE 用:以 context.id 找 push key 解開 §6.7 的 `sealed`;失敗回 nil。- public static func openPush(sealed: String, computerId: ComputerID, contextID: String) -> (title: String, body: String)?-}--// CodyncKit/Client/HostTransport.swift-public enum HostRoute: Sendable, Equatable { case loopback, direct, relay }-public enum HostStreamRequest: Sendable { case events(since: Int64, client: String), term(String) }-public enum LinkState: Sendable, Equatable {- case connecting, ready(HostRoute), hostOffline(lastSeen: Date?), unauthorized(String), failed(String)-}-public protocol HostTransport: Sendable {- func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data- /// nonisolated:actor 實作在內部起 Task。每個元素 = 一則 SSE data JSON。- func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error>- /// 每次呼叫回傳一條新的 stream:先 yield 目前狀態,之後每次變化。可多個消費者。- func states() -> AsyncStream<LinkState>-}-// 路由切換(中繼↔直連)或重新握手時,transport 以 HostError.unreachable 結束所有已開的 stream;-// 重新訂閱由 BotStore 負責(以它目前的 rev)。LoopbackTransport.states() 只 yield `.ready(.loopback)`。--public struct HostClient: Sendable {- public let transport: any HostTransport- public init(transport: any HostTransport)- public init(baseURL: URL, token: String) // loopback(Mac 本機、SSH tunnel)- // 既有 typed 方法(hello/sync/send/… 與 Market.swift 的擴充)保持原樣,改走 transport-}--public enum HostError: LocalizedError, Sendable {- case http(Int, String)- case unreachable- case computerOffline(lastSeen: Date?)- case unauthorized(String)- case upgradeRequired-}--// CodyncKit/Client/HostConnector.swift-public enum HostConnector {- /// §7.5:直連優先(1.5 s),否則中繼。回傳的 transport 在 host 離線時仍存活(presence/mailbox)。- public static func connect(_ computer: Computer, identity: DeviceIdentity) async throws -> ChannelTransport- /// §4.1:以 QR 配對(收到 4100 即完成),回傳可持久化的 Computer。- public static func pair(_ pairing: Pairing, identity: DeviceIdentity, deviceName: String, platform: String) async throws -> Computer-}-public actor ChannelTransport: HostTransport {- public nonisolated func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data- public nonisolated func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error>- public nonisolated func states() -> AsyncStream<LinkState>- public nonisolated func computerUpdates() -> AsyncStream<Computer> // 每次 hello 成功後合併的新值(§7.5 步驟 5)- // mailbox- public func enqueue(botId: String, text: String, clientNonce: String) async throws // 無 boxKey → HostError.computerOffline- public func cancelQueued(clientNonce: String) async -> MailboxCancel // .cancelled / .delivering / .unknown- public func listQueued() async -> [QueuedItem]- public nonisolated func mailboxEvents() -> AsyncStream<MailboxEvent> // .delivered/.failed(code)/.expired(nonce)-}--// CodyncKit/Client/CloudClient.swift-public struct CloudClient: Sendable {- public init(baseURL: URL, identity: DeviceIdentity?, token: @escaping @Sendable () async throws -> String)- public func me() async throws -> CloudAccount- public func registerDevice(name: String, platform: String) async throws- public func computers() async throws -> [CloudComputer]- public func renameComputer(_ id: ComputerID, name: String) async throws- public func removeComputer(_ id: ComputerID) async throws- /// §4.2 B 3–5 全流程:commit → 等 hostNonce → reveal;回傳時 `code` 已可顯示。nD 只在記憶體。- public func requestAccess(_ id: ComputerID, signKey: String) async throws -> AccessTicket // requestId, expiresAt, code(SAS)- public func accessStatus(_ requestId: String) async throws -> AccessStatus // pending/approved/denied/expired/cancelled- public func cancelAccess(_ requestId: String) async throws- public func devices() async throws -> [CloudDevice]- public func revokeDevice(_ deviceId: String) async throws- public func grants(_ id: ComputerID) async throws -> [CloudGrant]- public func revokeGrant(_ id: ComputerID, grantId: String) async throws- public func createClaim() async throws -> ClaimChallenge- public func completeClaim(_ claimId: String, signed: ClaimSignature) async throws -> CloudComputer-}-public extension HostClient { // loopback-only 方法(Mac)- func claimSign(claimId: String, nonce: String, userId: String) async throws -> ClaimSignature- func accessRequests() async throws -> [AccessRequest]- func decideAccessRequest(_ id: String, approve: Bool) async throws- func devices() async throws -> [AuthorizedDevice]- func revokeDevice(_ key: String) async throws- func cloudStatus() async throws -> CloudStatus- func setCloud(enabled: Bool) async throws -> CloudStatus- func unclaim() async throws-}--// CodyncKit/Client/SharedStore.swift(取代既有的 pairing/computers/preferredURL/orderedPairing/usage/bots)-public enum SharedStore {- public static let appGroup: String- public static let relayURL: String // APNs 推播 relay(不變)- public static var activeAccountID: String? { get set }- public static var activeContext: Context { get }- public struct Context {- public let accountID: String?- public var id: String { get } // digest(accountID) 或 "local"- public var computers: [Computer] { get nonmutating set }- public var bots: [BotSnapshot] { get nonmutating set } // BotSnapshot { computerId, bot }- public var usage: [ComputerID: Usage] { get nonmutating set }- public var lastComputerId: ComputerID? { get nonmutating set } // 最近活躍的 BotStore;Usage widget 只看這台- public func botURL(_ ref: BotReference) -> URL- public func reference(from url: URL) -> BotReference? // scope 不符或格式錯 → nil(取代 acceptsBotURL)- }- // 移除所有 static 的 pairing / computers / orderedPairing / preferredURL / usage / bots-}-// deep link 格式:codync://bot/<botId>?scope=<Context.id>&computer=<computerId>--// CodyncUI/Store/BotStore.swift(調整)-@MainActor @Observable public final class BotStore {- public enum Connection: Equatable {- case unpaired, connecting, online- case computerOffline(lastSeen: Date?) // 中繼說電腦不在線- case offline(String) // 完全連不到(無直連也無中繼)- case unauthorized(String) // 撤權/lease 到期/身分不符- }- // `isOffline` 對後三者為 true;`== .online` 的既有比較照常可用。- public enum Route: Sendable, Hashable { case loopback(baseURL: URL, token: String), channel }- /// `.channel` 時 BotStore 自己以 `DeviceIdentity.load(context: storage)` 取得身分。- public init(computer: Computer, route: Route, clientKind: String, storage: SharedStore.Context)- public private(set) var computer: Computer- public private(set) var client: HostClient?- public private(set) var connection: Connection- public private(set) var hostRoute: HostRoute?- public private(set) var accessRequests: [AccessRequest] // 只有 loopback 會有- public private(set) var cloud: CloudStatus? // 只有 loopback 會有- public var onConnected: (@MainActor (BotStore) -> Void)? // 取代 onPaired- public var onUsageChanged: (@MainActor (ComputerID, Usage) -> Void)?- public func cancelQueued(_ entry: Entry)- // 移除:pair(_:)、forget(_:)、unpair()、computers、pairing、persistsPairing-}--// CodyncUI/Store/AccountStore.swift(新增)-@MainActor @Observable public final class AccountStore {- public init(storage: SharedStore.Context, clientKind: String, cloud: CloudClient?)- public let storage: SharedStore.Context- public var accountId: String? { storage.accountID }- public private(set) var computers: [Computer]- public private(set) var stores: [ComputerID: BotStore]- public private(set) var cloudComputers: [CloudComputer] // 帳號中但本機尚未授權者也列出- public private(set) var pendingAccess: [ComputerID: AccessTicket]- public var selection: BotReference?- public var roster: [RosterItem] { get } // 跨 computer 彙整、排序同 BotStore.roster- public func store(for id: ComputerID) -> BotStore?- public func pair(_ pairing: Pairing, deviceName: String, platform: String) async throws -> Computer- public func attach(_ computer: Computer, route: BotStore.Route) // Mac 本機/SSH- public func detach(_ id: ComputerID)- public func forget(_ id: ComputerID)- public func refreshCloud() async- public func requestAccess(_ id: ComputerID) async throws -> AccessTicket- public func setColor(_ id: ComputerID, _ color: String)- public func setActive(_ active: Bool)- public func retire()- public var onBotUpdated: (@MainActor (BotReference, Bot) -> Void)?- public var onConnected: (@MainActor (BotStore) -> Void)?- public var onSent: (@MainActor (BotReference, Bot) -> Void)?-}-public struct RosterItem: Identifiable, Sendable { public var ref: BotReference; public var bot: Bot; public var computer: Computer; public var id: BotReference { ref } }-```-型別欄位(`CloudComputer`、`AccessTicket`、`AccessStatus`、`AccessRequest`、`AuthorizedDevice`、`CloudStatus`、`ClaimChallenge`、`ClaimSignature`、`CloudAccount`、`CloudDevice`、`CloudGrant`、`QueuedItem`、`MailboxEvent`、`MailboxCancel`、`BotSnapshot`)直接對應 §7.4/§8.4/§9.4 的 JSON,`Codable` 解碼寬鬆(未知欄位忽略、選填欄位 optional)。以上簽章是最小集合;kit 可以多加,不能改名或改型別。--### 10.2 實作要點+`CodyncKit/Client` owns transport, crypto, identity and cloud API models. `CodyncUI` owns account/per-computer stores and presentation. Consumers must retain account and computer scope when handling asynchronous responses, links and cached widget data. See [file structure](../architecture/file-structure.md).-- `LoopbackTransport`:今日 `HostClient.call`/`sse` 的邏輯搬過來(Bearer header,無 `?token=`)。-- `ChannelTransport`(actor):WebSocket(`URLSessionWebSocketTask`)+ §6 加密+ §6.5 RPC 多工;`states()`、mailbox API 如上。收到 `4100` 時自動以一般模式重連。-- `HostConnector.connect(computer:identity:)` 實作 §7.5;`HostConnector.pair(_:identity:deviceName:platform:)` 實作 §4.1。-- `BotStore.runStream`:訂閱 `transport.states()` 推 `connection`;stream 以 `unreachable` 結束時以目前 `rev` 重新訂閱;`computerOffline` 時不做盲目退避,等 presence。`computerUpdates()` 的新值寫回 `computer` 並由 AccountStore 持久化。`send` 在 `computerOffline` 且有 `boxKey` 時:本地 entry `status = "waiting"`,成功入列後保持,`mbox.delivered` 後等 events 的正式 entry 取代(既有 clientNonce 取代邏輯),`failed`/`expired` → `"failed"`(可重試:重試 = 重新封裝、新的 `epk`,§6.4)。`cancelQueued` → 成功則移除本地 entry;`delivering` 顯示「已送出」。`status == "waiting"` 的本地 entry **要寫入快取**(重開 App 仍看得到並可取消),啟動時以 `listQueued()` 對帳。-- 快取檔名改以 `computer.id` 取代 `pairing.token` 的 digest。`SharedStore.Context.computers` 不含任何秘密,可留在 App Group UserDefaults。舊資料不遷移,使用者重新配對。-- `onUsageChanged` 寫 `storage.usage[computerId]`;BotStore 變成 active/送出訊息時寫 `storage.lastComputerId`。-- `BotActivityAttributes` 新增 `computerId`;`ContentState.activity` 保留欄位但 host 永遠送空字串(§6.7)。-- `ThreadView`、`BotRow`、`ChatRows`:顯示 `computerOffline`(「電腦目前離線,訊息會在它上線時送出」)、`unauthorized`、`waiting` 狀態(含取消按鈕,icon-only + accessibility label)。-- kit 不依賴 ClerkKit;Clerk token 由 App 以 closure 注入 `CloudClient`。-- Keychain:§3.2(macOS 不設 data protection keychain)。+## 11. Apple apps and SSH-### 10.3 APPLE-KIT 測試(`swift test`)+The Apple apps share Clerk integration. QR pairing remains usable without an account; account sign-in requires host-approved device access. macOS uses OpenSSH forwarding for SSH computers, not a mobile SSH gateway. See [accounts and SSH](../guides/accounts-and-ssh.md).-`remote-relay-vectors.json` 全欄位(握手、frame、chunk、mailbox、SAS commit/code、offer、Codync-Sig、push);mailbox 連續封裝兩次 `epk` 不同;`Pairing(url:)` 的 v3 解析與拒絕(`id` 不符、缺 `code`、`cloud` 非 https);`botURL`/`reference(from:)` 來回與跨 scope 拒絕;`states()` 多消費者;RPC 多工與取消(以假的 WebSocket);`BotStore` 在 `computerOffline` 時的 `waiting`/取消/到期;`AccountStore` 兩台 computer 相同 bot ID 不混淆、帳號切換後舊回覆不寫入。+## 12. Verification----+### 12.1 Local integration-## 11. APPLE-APPS track--### 11.1 共通--- `apps/shared/AccountSession.swift`:新增 `func sessionToken() async throws -> String`(ClerkKit 1.5.6 的 session token API,以實際 SDK 名稱為準)。-- 設定檔:`ClerkConfig.plist` 改名為 `AccountConfig.plist`,keys `clerkPublishableKey`、`cloudURL`(目前填 dev URL);env `CODYNC_CLOUD_URL` 可覆寫。兩個 App 都要。-- `project.yml`:`MARKETING_VERSION: 2.2.0`;iOS、Widgets、NotificationService 加 `keychain-access-groups: [$(AppIdentifierPrefix)com.pokai.Codync]`,Info.plist 加 `CodyncKeychainGroup`;新增 `NotificationService` app-extension target(`apps/ios/NotificationService/`,bundle id `com.pokai.Codync.ios.NotificationService`,依賴 CodyncKit,embed 進 iOS App);macOS **不加** entitlements(§3.2);改完執行 `xcodegen generate`。-- `.github/workflows/release-macos.yml`:配合 `AccountConfig.plist` 改名。--### 11.2 iOS--- `AppStore` 改持有 `AccountStore`(取代單一 `BotStore`);`RootView` 以 `accountStore.selection` 導覽,進入聊天時把 `accountStore.store(for: ref.computerId)` 注入 `ThreadView` 的 environment。-- Bot 清單:`accountStore.roster`,每列顯示 computer 名稱與其連線狀態(單台離線不影響其他)。-- 新增 bot:先選 computer(只列 online 的),再開 `BotEditorView`(用該 computer 的 store)。-- Computers 頁(取代 `SettingsView` 的電腦區):本機配對與帳號電腦合併(依 `computerId`);每台分別顯示「已加入帳號/已授權/可連線(直連/中繼)」;未授權的帳號電腦顯示「申請存取」→ 顯示 SAS 並輪詢;支援移除、改色、撤銷(帳號)。-- Pairing:`AccountStore.pair`;文案改為「不需要 Tailscale;在家用 Wi-Fi 直連,其他地方透過加密中繼」,Tailscale 步驟移為選配說明。-- 推播:`PushRegistrar` 對每個 `onConnected` 的 store 呼叫 `registerDevice {ticket, name, relay, pushKey: identity.pushKey, ctx: storage.id}`;通知點擊以 `userInfo["ctx"]`、`["computerId"]`、`["botId"]` 組 `BotReference`,只有 `ctx == storage.id` 且 computer 屬於目前 context 才導覽。-- NotificationService:`DeviceIdentity.openPush(sealed:computerId:contextID:)` 成功 → 替換 title/body;失敗保留通用文字。30 秒內完成,不做網路。-- Widgets:從 `SharedStore.Context` snapshot 顯示(`bots` 為 `[BotSnapshot]`);Usage widget 只顯示 `usage[lastComputerId]`,重新整理時只對 `lastComputerId` 那台 `HostConnector.connect` + `usage` 單次呼叫(直連或中繼),失敗用快取。Live Activity 只顯示狀態(沒有 activity 文字)。deep link 用 `botURL(BotReference)`。-- 登入後:`CloudClient.registerDevice` → `refreshCloud`。登出/切換:`retire()`、刪該 context 的 device key 與快取(§3.2)。--### 11.3 macOS--- `HostController` 保留本機 host 管理;本機 store 以 `.loopback(baseURL: 127.0.0.1:port, token:)` attach 到 Mac 的 `AccountStore`。Mac 也有自己的 device key,可經 channel 連帳號中的其他電腦。-- 核准介面:本機(與每條 SSH)store 的 `accessRequests` 非空 → 選單列圖示加提示、跳出核准 sheet(裝置名稱、平台、email、SAS 大字、Approve/Deny 文字按鈕;`code == nil`(對方尚未揭露)時顯示等待中、Approve 停用)。-- 帳號:「將這台 Mac 加入帳號」(claim 流程 §4.2 A)、「移出帳號」(`unclaim`)、「已授權裝置」清單與撤銷(`devices`/`revokeDevice`)、「可從任何地方連線」開關(`setCloud`),並顯示 `cloudStatus`。-- `ChatWindow` sidebar 顯示跨 computer bots,新增 bot 先選 computer。--### 11.4 SSH(`apps/macos/App/SSHTunnel.swift` 等)--- Profile(非秘密,存 UserDefaults):`id`、`alias` 或 `hostname`、`port`、`user`、`identityFile?`、`remotePort`(預設 19222)、`computerId`(首次連線後記住)、`name`。-- 輸入驗證:hostname/alias `^[A-Za-z0-9._-]+$` 且不以 `-` 開頭;user `^[A-Za-z_][A-Za-z0-9._-]*$`;port 1–65535;identityFile 必須是存在的檔案。以 `Process` 的 argv 陣列傳遞,**永不**經 shell 組字串。-- App 的 known_hosts:`~/.codync/ssh_known_hosts`(路徑無空白)。每個 ssh 呼叫都帶這組 argv(兩個元素;值內以**字面雙引號**包住絕對路徑,因為 ssh 自己的 config tokenizer 會以空白切開 `UserKnownHostsFile`,argv quoting 無效):- `-o`, `UserKnownHostsFile="<HOME>/.ssh/known_hosts" "<HOME>/.codync/ssh_known_hosts"`,以及 `-o`, `StrictHostKeyChecking=yes`。-- 解析目標:先跑 `ssh -G [-p port] [-l user] -- <dest>`,取 `hostname`、`port`、`hostkeyalias`、`proxyjump`、`proxycommand`。known_hosts 查詢名稱 = `hostkeyalias` 或 `hostname`,port ≠ 22 時寫成 `[name]:port`。-- Host key 判定(不解析 ssh 的 stderr 文字):- 1. `ssh-keygen -F <name> -f <file>` 對兩個 known_hosts 檔各查一次。- 2. 找到 → 直接連線(`StrictHostKeyChecking=yes` 由 ssh 自己把關)。- 3. 沒找到且未設 `proxyjump`/`proxycommand` → `ssh-keyscan -p <port> -- <hostname>`,以 `ssh-keygen -lf -` 顯示指紋請使用者確認 → 以 `<name>` 為主機名寫入 `~/.codync/ssh_known_hosts`。- 4. 沒找到但設了 proxy → 不 keyscan,提示「請先在終端機以 ssh 連線一次以確認主機金鑰」(見 §0 取捨)。- 5. 找到了但連線以 exit 255 失敗、且 keyscan(無 proxy 時)取得的金鑰都不在已記錄的條目中 → 判定為**主機金鑰已變更**,阻擋並說明,不提供略過。-- 取得遠端資訊:`ssh <opts> -- <dest> "sh -lc 'codync-host info --json'"`(固定字串,無使用者輸入)。解析失敗 → 「遠端未安裝 codync-host」並顯示安裝指令(複製按鈕;不自動安裝)。-- Tunnel:`ssh -N -T -o ExitOnForwardFailure=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ForwardAgent=no -o ForwardX11=no -o BatchMode=yes -o StrictHostKeyChecking=yes -o 'UserKnownHostsFile="…" "…"' -L 127.0.0.1:<localPort>:127.0.0.1:<remotePort> [-p port] [-i key] [-l user] -- <dest>`;localPort 以綁定 port 0 取得。監看 process,斷線以 1→30 s 退避重啟;`computerId` 與 profile 記錄不符 → 停止並警告。-- 連上後:`AccountStore.attach(computer, route: .loopback(baseURL: 127.0.0.1:localPort, token: token))`;token 每次連線以 `info --json` 取得,不持久化。-- 多個 bots 共用一條 tunnel;只有 detach/移除 profile 才終止。-- 遠端 host 也可自行連雲端中繼:Mac 經 tunnel 呼叫 `pairing` 顯示 QR 給手機、或 `claimSign` 將遠端加入帳號。--### 11.5 APPLE-APPS 測試--編譯 iOS/macOS/Widgets;UI 流程手動驗收(§12.2);SSH argv 組裝(含 `UserKnownHostsFile` 的字面雙引號與 `ssh -G` 輸出解析)與輸入驗證寫成可測的純函式並附單元測試(放在 `kit/Tests` 以外時,至少在 DEBUG 啟動時跑 `assert`-based self-check)。+`cloud/test/e2e/relay.e2e.ts` exercises a real host with local Wrangler and a fake ACP agent. Run `npm run e2e` in `cloud/` after building the host. The three language implementations also consume the shared vectors.----+### 12.2 Deployed-device verification-## 12. 跨 track 驗證+Use the [Cloudflare testing guide](../guides/cloudflare-testing.md). Local tests do not establish live OAuth, deployed Worker, APNs or background behavior.-### 12.1 整合測試(CLOUD 擁有:`cloud/test/e2e/relay.e2e.ts`,`npm run e2e`)+## 13. Acceptance criteria-1. `wrangler d1 migrations apply codync-dev --local --env dev`;測試產生 RSA 金鑰,將公鑰 PEM 設為 `CLERK_JWT_KEY` 啟動 `wrangler dev --env dev --port 8787`。-2. 以 `CODYNC_HOME=<tmp> CODYNC_CLOUD_URL=http://127.0.0.1:8787` 啟動 `host/target/debug/codync-host serve --bind 127.0.0.1 --port <free>`。-3. 等 D1 出現 computer 列、DO presence online。-4. TS 假手機:loopback `pairing` 取 URL → 以 `pair=<offerId>` 走中繼 → `pair` → `hello` → `createBot`(backend `custom`,command 為 `python3 host/tests/fake_agent.py`)→ `events` 訂閱 → `send` → 收到 agent 回覆。-5. 關閉 host → device 收到 `presence online:false` → `mbox.put` 一則 `send` → `mbox.cancel` 另一則 → 重啟 host → 收到 `mbox.delivered`、events 出現該 clientNonce 的 entry、被取消的不存在。-6. 帳號流程:自簽 JWT → `POST /v1/claims` → loopback `claimSign` → complete → 第二支假手機 `POST /v1/devices` → access request(commit)→ 等 hostNonce → reveal → loopback `accessRequests` 的 `code` 等於手機算出的 SAS → `decideAccessRequest` → 以中繼連線成功 → `DELETE …/grants/{id}` → 1 秒內 socket 以 `4003` 關閉 → host 重連後(state 拉取前後)該 dk 都無法再連。-6b. 雲端惡意注入:直接在 D1 插入一筆 grant(第三把 key)→ host 拉 state 後該 key 仍被拒、ACL 不含它。-6c. pairing 經中繼:`pair` 回應後 link 以 `4100` 關閉,假手機以一般模式重連成功,且可超過 16 則訊息。-7. 直連:同一假手機以 `ws://127.0.0.1:<port>/channel` 握手成功;以非 loopback 位址用 bearer token 呼叫 `/api/hello` → 401。+Verify pairing and approval, same-computer direct/relay connectivity, encrypted chat and reconnect catch-up, mailbox cancellation/deduplication, revocation, account isolation, and separate APNs delivery. Record actual results and routes. These are acceptance targets, not claims that all scenarios have passed.-### 12.2 手動驗收(owner + 實機)--兩個 Google 帳號、兩支 iPhone(或模擬器 + 實機)、一台 Mac、一台 Linux(SSH)。-------## 13. 驗收條件--- 手機在行動網路(無 Tailscale)可與家中 NAT 後的 Mac 聊天、stop、回應權限、開 remote screen 訊號;`cloud` Worker log、DO storage 與 `relay/` 推播 Worker 收到的 body 中都找不到任何明文訊息、bot 名稱、token 或 pairing code。-- 同一 Wi-Fi 下自動走直連(UI 顯示直連);離開 Wi-Fi 後在 10 秒內改走中繼且不重複訊息。-- 帳號裝置在電腦離線超過 15 分鐘後仍看得到「電腦離線」並可排入 mailbox。-- 電腦睡眠:手機顯示「電腦離線(上次 …)」而不是「連不到」;送出的訊息顯示「等待電腦上線」可取消;電腦醒來後依序送出、每則只執行一次;24 小時後未送出者顯示失敗。-- 未登入:QR 配對後同樣可經中繼使用;登入不會自動宣告本機配對的電腦。-- 帳號:新手機申請 → Mac 顯示相同 SAS → 核准 → 可連線;撤銷後 5 秒內(host 在線)斷線,host 連不到雲端時最長 15 分鐘失效;手機 B 不受影響。-- 另一帳號猜到 computerId/requestId/grantId 仍全部 404。-- 非 loopback 的 bearer token 一律 401;`setScreenEnabled`、`pairing`、`claimSign` 等經 channel 呼叫一律 403。-- 多 computer:本機 bot 與 SSH bot 並列,兩台有相同 bot ID 時 send/stop 不會送錯;SSH host key 變更時阻擋。-- CI:`cargo fmt --check`、`cargo clippy --all-targets -- -D warnings`、`cargo test`;`cloud`:`npm run typecheck && npm test`;`swift test`(kit);Xcode 三個 target 可編譯。-----+## 14. Environments and deployment-## 14. 部署(dev 可由實作者執行;production 需 owner 確認)+See [environments and deployment](../guides/environments-and-deployment.md) and [cloud setup](../../cloud/README.md). Debug targets development. Main app configuration is empty and production Worker bindings include placeholders; production readiness must be established separately.-### 14.0 環境:main 與 dev+## Implementation clarifications-| 環境 | Cloud Worker | D1 | Clerk | App build |-|---|---|---|---|---|-| **dev** | `codync-cloud-dev` → `https://dev-api.codync.dev`(`wrangler deploy --env dev`) | `codync-dev` | development instance `sunny-mollusk-8651` | Debug(`CODYNC_ENV=dev`) |-| **main** | `codync-cloud` → `https://api.codync.dev`(`wrangler deploy`) | `codync` | production instance(待建立,網域 `codync.dev`) | Release(`CODYNC_ENV=main`) |-| local | `wrangler dev --env local`(e2e) | 本機 `codync-local` | 測試 RSA key(`CLERK_JWT_KEY`) | — |--`apps/shared/Config/<env>.plist` 在 build 時複製成 App 內的 `AccountConfig.plist`;`main.plist` 在 production 上線前留空,Release build 的帳號與雲端功能因此關閉。Host 的雲端 URL 由 Mac App 的 Cloud 開關以 `setCloud` 寫入(或 `CODYNC_CLOUD_URL`)。--### 14.1 Staging--```bash-cd cloud && npm ci-npx wrangler d1 create codync-dev # 將 database_id 填入 [env.dev]-npx wrangler d1 migrations apply codync-dev --env dev --remote-npx wrangler secret put CLERK_SECRET_KEY --env dev # owner 輸入 sk_test_…-npx wrangler secret put CLERK_WEBHOOK_SECRET --env dev # owner 輸入 whsec_…-npx wrangler deploy --env dev # → https://dev-api.codync.dev(custom domain;production 用 api.codync.dev)-```-Host 測 dev:`codync-host cloud --url https://dev-api.codync.dev`(或 env `CODYNC_CLOUD_URL`)。Apple:`AccountConfig.plist` 的 `cloudURL`。--### 14.2 Secrets 與 vars--| 名稱 | 種類 | 說明 |-|---|---|---|-| `CLERK_SECRET_KEY` | secret(owner 輸入) | `verifyToken` 取 JWKS 用 |-| `CLERK_WEBHOOK_SECRET` | secret(owner 輸入) | Svix 簽章 |-| `CLERK_ISSUER` | var | Clerk Frontend API URL |-| `CLERK_AUTHORIZED_PARTIES` | var(選填) | 逗號分隔 |-| `CLERK_JWT_KEY` | var(只給 dev/e2e) | networkless 驗證用的公鑰 PEM;dev/production 不設 |--### 14.3 Owner 手動步驟--0. 允許實作者建立 dev 資源:`wrangler login` 已登入的 Cloudflare 帳號(或提供 `CLOUDFLARE_API_TOKEN`,權限 Workers Scripts:Edit、D1:Edit、Durable Objects)。-1. Clerk Dashboard(dev = `sunny-mollusk-8651`):確認 iOS native app(`com.pokai.Codync.ios`)已註冊並允許 `com.pokai.Codync.ios://callback`;**Sessions → Customize session token** 加入 `{"email": "{{user.primary_email_address}}"}`;**Webhooks** 新增 `https://dev-api.codync.dev/v1/webhooks/clerk`,訂閱 `user.deleted`,複製 signing secret。-2. 輸入上面兩個 secrets。-3. Production:另建 Clerk production instance、`wrangler d1 create codync`、填 `wrangler.toml` 頂層、secrets 不加 `--env`、`npx wrangler deploy`;把 production URL 填入 `host/src/cloud.rs` 的 `DEFAULT_CLOUD_URL` 與 Release 版 `AccountConfig.plist`。-4. Apple Developer:新增 `com.pokai.Codync.ios.NotificationService` App ID 與 keychain access group 後,讓 Xcode 自動簽章更新 provisioning profiles。-5. `relay/` 的 `mutableContent` 變更需重新部署推播 Worker(`cd relay && npx wrangler deploy`,現有 production;需 owner 確認)。-------## 實作差異(已接受)--實作與上文不同、經確認保留的行為:+The following implemented clarifications take precedence over the original contract wording above:- **Close code**:host 送出 `reject` 後自行挑選 WebSocket close code(`RejectCode::close_code`),不照 §表格逐一對應。- **`cloud_synced`**:relay 斷線時不清除;帳號裝置的 lease 最長 15 分鐘內自然失效。@@ -1147,18 +534,11 @@ Host 測 dev:`codync-host cloud --url https://dev-api.codync.dev`(或 env `C- **SSH forward**:以 `lsof` 確認本機 listener 屬於我們啟動的 `ssh`。- **取消 access request**:iOS SAS sheet 與 Mac computers 視窗都有取消按鈕(`DELETE /v1/access-requests/{id}`)。-## 15. 風險與未決+## 15. Limits and risks-| 風險 | 說明/緩解 |-|---|---|-| 帳號流程的 host 公鑰由雲端傳遞 | 被攻破的 Worker 可換公鑰做 MITM;commit-then-reveal SAS 讓每次嘗試只有 10⁻⁶ 成功率,但前提是使用者真的比對。UI 必須把 SAS 放大並要求明確按 Approve。QR 流程不受影響。 |-| 推播 metadata | APNs/`relay/` 看得到 botId、computerId、context id、kind 與時間;內容已封裝(D10)。 |-| Worker/DO 可見 metadata | computerId、deviceKey、連線時間、訊息大小與頻率、mailbox 的 clientNonce 與失敗碼。文件與隱私說明需如實寫。 |-| 任何人可產生金鑰並註冊 computer | register 依 IP 限流、`computers.status='blocked'` 可封鎖;費用告警需在 production 前設定。 |-| `identity.json` 被複製 | 兩台機器搶同一 DO → `4009 replaced` 互踢並記錄錯誤;不自動修復。 |-| ClerkKit/Workers 限制 | ClerkKit session token API 名稱、Workers Rate Limiting binding、WebSocket 1 MiB 上限需在實作時對照當時文件;chunk 256 KiB 預留空間。 |-| `hkdf`/`sha2` 版本 | 見 §9.1。 |-| 協定升級 | 手機↔host 升 major 3;2.x App 需要更新才能連 3.x host。 |-| Production URL 未定 | `DEFAULT_CLOUD_URL = None` 時雲端停用(只有 QR + 直連);production 部署時填入 host 常數與 Release 設定檔。 |-| host 撤銷帳號裝置但 `POST /v1/host/grants/{id}/revoke` 失敗 | 本機已撤銷且 state 不能把它加回(§4.3),D1 只是顯示仍 granted;下次成功時補送。 |-| 直連 LAN 的 `ws://` | 內容已 E2E;但 metadata(連線、大小)在 LAN 可見,可接受。 |+- Account discovery relies on cloud-provided public keys; users must actually compare the commit/reveal six-digit approval code. QR pairing obtains host keys directly from the pairing payload.+- The cloud sees account/device records and routing metadata, connection times, sizes, frequency and mailbox identifiers. Channel content is encrypted. APNs has its own visible routing metadata.+- Copying `identity.json` creates competing connections for one computer identity; replacing host keys requires pairing again.+- Revocation is enforced locally even when cloud synchronization fails; pending cloud revocations are retried.+- Direct `ws://` still encrypts channel content, but exposes connection metadata to the local network.+- Mailbox retention is bounded and is not cloud transcript storage. TURN, phone-native SSH and team sharing are outside this contract.