diff --git a/SECURITY.md b/SECURITY.md
index f4ccac868cc7a..d02b9fb80103a 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -39,18 +39,36 @@ Reports without reproduction steps, demonstrated impact, and remediation advice
OpenClaw is a labor of love. There is no bug bounty program and no budget for paid reports. Please still disclose responsibly so we can fix issues quickly.
The best way to help the project right now is by sending PRs.
+## Maintainers: GHSA Updates via CLI
+
+When patching a GHSA via `gh api`, include `X-GitHub-Api-Version: 2022-11-28` (or newer). Without it, some fields (notably CVSS) may not persist even if the request returns 200.
+
## Out of Scope
- Public Internet Exposure
- Using OpenClaw in ways that the docs recommend not to
- Prompt injection attacks
+## Plugin Trust Boundary
+
+Plugins/extensions are loaded **in-process** with the Gateway and are treated as trusted code.
+
+- Plugins can execute with the same OS privileges as the OpenClaw process.
+- Runtime helpers (for example `runtime.system.runCommandWithTimeout`) are convenience APIs, not a sandbox boundary.
+- Only install plugins you trust, and prefer `plugins.allow` to pin explicit trusted plugin ids.
+
## Operational Guidance
For threat model + hardening guidance (including `openclaw security audit --deep` and `--fix`), see:
- `https://docs.openclaw.ai/gateway/security`
+### Tool filesystem hardening
+
+- `tools.exec.applyPatch.workspaceOnly: true` (recommended): keeps `apply_patch` writes/deletes within the configured workspace directory.
+- `tools.fs.workspaceOnly: true` (optional): restricts `read`/`write`/`edit`/`apply_patch` paths to the workspace directory.
+- Avoid setting `tools.exec.applyPatch.workspaceOnly: false` unless you fully trust who can trigger tool execution.
+
### Web Interface Safety
OpenClaw's web interface (Gateway Control UI + HTTP endpoints) is intended for **local use only**.
@@ -58,6 +76,10 @@ OpenClaw's web interface (Gateway Control UI + HTTP endpoints) is intended for *
- Recommended: keep the Gateway **loopback-only** (`127.0.0.1` / `::1`).
- Config: `gateway.bind="loopback"` (default).
- CLI: `openclaw gateway run --bind loopback`.
+- Canvas host note: network-visible canvas is **intentional** for trusted node scenarios (LAN/tailnet).
+ - Expected setup: non-loopback bind + Gateway auth (token/password/trusted-proxy) + firewall/tailnet controls.
+ - Expected routes: `/__openclaw__/canvas/`, `/__openclaw__/a2ui/`.
+ - This deployment model alone is not a security vulnerability.
- Do **not** expose it to the public internet (no direct bind to `0.0.0.0`, no public reverse proxy). It is not hardened for public exposure.
- If you need remote access, prefer an SSH tunnel or Tailscale serve/funnel (so the Gateway still binds to loopback), plus strong Gateway auth.
- The Gateway HTTP surface includes the canvas host (`/__openclaw__/canvas/`, `/__openclaw__/a2ui/`). Treat canvas content as sensitive/untrusted and avoid exposing it beyond loopback unless you understand the risk.
diff --git a/VISION.md b/VISION.md
new file mode 100644
index 0000000000000..4ff70189ab892
--- /dev/null
+++ b/VISION.md
@@ -0,0 +1,110 @@
+## OpenClaw Vision
+
+OpenClaw is the AI that actually does things.
+It runs on your devices, in your channels, with your rules.
+
+This document explains the current state and direction of the project.
+We are still early, so iteration is fast.
+Project overview and developer docs: [`README.md`](README.md)
+Contribution guide: [`CONTRIBUTING.md`](CONTRIBUTING.md)
+
+OpenClaw started as a personal playground to learn AI and build something genuinely useful:
+an assistant that can run real tasks on a real computer.
+It evolved through several names and shells: Warelay -> Clawdbot -> Moltbot -> OpenClaw.
+
+The goal: a personal assistant that is easy to use, supports a wide range of platforms, and respects privacy and security.
+
+The current focus is:
+
+Priority:
+
+- Security and safe defaults
+- Bug fixes and stability
+- Setup reliability and first-run UX
+
+Next priorities:
+
+- Supporting all major model providers
+- Improving support for major messaging channels (and adding a few high-demand ones)
+- Performance and test infrastructure
+- Better computer-use and agent harness capabilities
+- Ergonomics across CLI and web frontend
+- Companion apps on macOS, iOS, Android, Windows, and Linux
+
+Contribution rules:
+
+- One PR = one issue/topic. Do not bundle multiple unrelated fixes/features.
+- PRs over ~5,000 changed lines are reviewed only in exceptional circumstances.
+- Do not open large batches of tiny PRs at once; each PR has review cost.
+- For very small related fixes, grouping into one focused PR is encouraged.
+
+## Security
+
+Security in OpenClaw is a deliberate tradeoff: strong defaults without killing capability.
+The goal is to stay powerful for real work while making risky paths explicit and operator-controlled.
+
+Canonical security policy and reporting:
+
+- [`SECURITY.md`](SECURITY.md)
+
+We prioritize secure defaults, but also expose clear knobs for trusted high-power workflows.
+
+## Plugins & Memory
+
+OpenClaw has an extensive plugin API.
+Core stays lean; optional capability should usually ship as plugins.
+
+Preferred plugin path is npm package distribution plus local extension loading for development.
+If you build a plugin, host and maintain it in your own repository.
+The bar for adding optional plugins to core is intentionally high.
+Plugin docs: [`docs/tools/plugin.md`](docs/tools/plugin.md)
+Community plugin listing + PR bar: https://docs.openclaw.ai/plugins/community
+
+Memory is a special plugin slot where only one memory plugin can be active at a time.
+Today we ship multiple memory options; over time we plan to converge on one recommended default path.
+
+### Skills
+
+We still ship some bundled skills for baseline UX.
+New skills should be published to ClawHub first (`clawhub.ai`), not added to core by default.
+Core skill additions should be rare and require a strong product or security reason.
+
+### MCP Support
+
+OpenClaw supports MCP through `mcporter`: https://github.com/steipete/mcporter
+
+This keeps MCP integration flexible and decoupled from core runtime:
+
+- add or change MCP servers without restarting the gateway
+- keep core tool/context surface lean
+- reduce MCP churn impact on core stability and security
+
+For now, we prefer this bridge model over building first-class MCP runtime into core.
+If there is an MCP server or feature `mcporter` does not support yet, please open an issue there.
+
+### Setup
+
+OpenClaw is currently terminal-first by design.
+This keeps setup explicit: users see docs, auth, permissions, and security posture up front.
+
+Long term, we want easier onboarding flows as hardening matures.
+We do not want convenience wrappers that hide critical security decisions from users.
+
+### Why TypeScript?
+
+OpenClaw is primarily an orchestration system: prompts, tools, protocols, and integrations.
+TypeScript was chosen to keep OpenClaw hackable by default.
+It is widely known, fast to iterate in, and easy to read, modify, and extend.
+
+## What We Will Not Merge (For Now)
+
+- New core skills when they can live on ClawHub
+- Full-doc translation sets for all docs (deferred; we plan AI-generated translations later)
+- Commercial service integrations that do not clearly fit the model-provider category
+- Wrapper channels around already supported channels without a clear capability or security gap
+- First-class MCP runtime in core when `mcporter` already provides the integration path
+- Agent-hierarchy frameworks (manager-of-managers / nested planner trees) as a default architecture
+- Heavy orchestration layers that duplicate existing agent and tool infrastructure
+
+This list is a roadmap guardrail, not a law of physics.
+Strong user demand and strong technical rationale can change it.
diff --git a/appcast.xml b/appcast.xml
index 469e66f994c60..3318fbaf86b61 100644
--- a/appcast.xml
+++ b/appcast.xml
@@ -2,6 +2,212 @@
OpenClaw
+
+ 2026.2.14
+ Sun, 15 Feb 2026 04:24:34 +0100
+ https://raw.githubusercontent.com/openclaw/openclaw/main/appcast.xml
+ 202602140
+ 2026.2.14
+ 15.0
+ OpenClaw 2026.2.14
+
Slack/Discord: add dmPolicy + allowFrom config aliases for DM access control; legacy dm.policy + dm.allowFrom keys remain supported and openclaw doctor --fix can migrate them.
+
Discord: allow exec approval prompts to target channels or both DM+channel via channels.discord.execApprovals.target. (#16051) Thanks @leonnardo.
+
Sandbox: add sandbox.browser.binds to configure browser-container bind mounts separately from exec containers. (#16230) Thanks @seheepeak.
+
Discord: add debug logging for message routing decisions to improve --debug tracing. (#16202) Thanks @jayleekr.
+
+
Fixes
+
+
CLI/Plugins: ensure openclaw message send exits after successful delivery across plugin-backed channels so one-shot sends do not hang. (#16491) Thanks @yinghaosang.
+
CLI/Plugins: run registered plugin gateway_stop hooks before openclaw message exits (success and failure paths), so plugin-backed channels can clean up one-shot CLI resources. (#16580) Thanks @gumadeiras.
+
WhatsApp: honor per-account dmPolicy overrides (account-level settings now take precedence over channel defaults for inbound DMs). (#10082) Thanks @mcaxtr.
+
Telegram: when channels.telegram.commands.native is false, exclude plugin commands from setMyCommands menu registration while keeping plugin slash handlers callable. (#15132) Thanks @Glucksberg.
+
LINE: return 200 OK for Developers Console "Verify" requests ({"events":[]}) without X-Line-Signature, while still requiring signatures for real deliveries. (#16582) Thanks @arosstale.
+
Cron: deliver text-only output directly when delivery.to is set so cron recipients get full output instead of summaries. (#16360) Thanks @thewilloftheshadow.
+
Cron/Slack: preserve agent identity (name and icon) when cron jobs deliver outbound messages. (#16242) Thanks @robbyczgw-cla.
+
Media: accept MEDIA:-prefixed paths (lenient whitespace) when loading outbound media to prevent ENOENT for tool-returned local media paths. (#13107) Thanks @mcaxtr.
+
Agents: deliver tool result media (screenshots, images, audio) to channels regardless of verbose level. (#11735) Thanks @strelov1.
+
Agents/Image tool: allow workspace-local image paths by including the active workspace directory in local media allowlists, and trust sandbox-validated paths in image loaders to prevent false "not under an allowed directory" rejections. (#15541)
+
Agents/Image tool: propagate the effective workspace root into tool wiring so workspace-local image paths are accepted by default when running without an explicit workspaceDir. (#16722)
+
BlueBubbles: include sender identity in group chat envelopes and pass clean message text to the agent prompt, aligning with iMessage/Signal formatting. (#16210) Thanks @zerone0x.
+
CLI: fix lazy core command registration so top-level maintenance commands (doctor, dashboard, reset, uninstall) resolve correctly instead of exposing a non-functional maintenance placeholder command.
+
CLI/Dashboard: when gateway.bind=lan, generate localhost dashboard URLs to satisfy browser secure-context requirements while preserving non-LAN bind behavior. (#16434) Thanks @BinHPdev.
+
TUI/Gateway: resolve local gateway target URL from gateway.bind mode (tailnet/lan) instead of hardcoded localhost so openclaw tui connects when gateway is non-loopback. (#16299) Thanks @cortexuvula.
+
TUI: honor explicit --session in openclaw tui even when session.scope is global, so named sessions no longer collapse into shared global history. (#16575) Thanks @cinqu.
+
TUI: use available terminal width for session name display in searchable select lists. (#16238) Thanks @robbyczgw-cla.
+
TUI: refactor searchable select list description layout and add regression coverage for ANSI-highlight width bounds.
+
TUI: preserve in-flight streaming replies when a different run finalizes concurrently (avoid clearing active run or reloading history mid-stream). (#10704) Thanks @axschr73.
+
TUI: keep pre-tool streamed text visible when later tool-boundary deltas temporarily omit earlier text blocks. (#6958) Thanks @KrisKind75.
+
TUI: sanitize ANSI/control-heavy history text, redact binary-like lines, and split pathological long unbroken tokens before rendering to prevent startup crashes on binary attachment history. (#13007) Thanks @wilkinspoe.
+
TUI: harden render-time sanitizer for narrow terminals by chunking moderately long unbroken tokens and adding fast-path sanitization guards to reduce overhead on normal text. (#5355) Thanks @tingxueren.
+
TUI: render assistant body text in terminal default foreground (instead of fixed light ANSI color) so contrast remains readable on light themes such as Solarized Light. (#16750) Thanks @paymog.
+
TUI/Hooks: pass explicit reset reason (new vs reset) through sessions.reset and emit internal command hooks for gateway-triggered resets so /new hook workflows fire in TUI/webchat.
+
Cron: prevent cron list/cron status from silently skipping past-due recurring jobs by using maintenance recompute semantics. (#16156) Thanks @zerone0x.
+
Cron: repair missing/corrupt nextRunAtMs for the updated job without globally recomputing unrelated due jobs during cron update. (#15750)
+
Cron: skip missed-job replay on startup for jobs interrupted mid-run (stale runningAtMs markers), preventing restart loops for self-restarting jobs such as update tasks. (#16694) Thanks @sbmilburn.
+
Discord: prefer gateway guild id when logging inbound messages so cached-miss guilds do not appear as guild=dm. Thanks @thewilloftheshadow.
+
Discord: treat empty per-guild channels: {} config maps as no channel allowlist (not deny-all), so groupPolicy: "open" guilds without explicit channel entries continue to receive messages. (#16714) Thanks @xqliu.
+
Models/CLI: guard models status string trimming paths to prevent crashes from malformed non-string config values. (#16395) Thanks @BinHPdev.
+
Gateway/Subagents: preserve queued announce items and summary state on delivery errors, retry failed announce drains, and avoid dropping unsent announcements on timeout/failure. (#16729) Thanks @Clawdette-Workspace.
+
Gateway/Sessions: abort active embedded runs and clear queued session work before sessions.reset, returning unavailable if the run does not stop in time. (#16576) Thanks @Grynn.
+
Sessions/Agents: harden transcript path resolution for mismatched agent context by preserving explicit store roots and adding safe absolute-path fallback to the correct agent sessions directory. (#16288) Thanks @robbyczgw-cla.
+
Agents: add a safety timeout around embedded session.compact() to ensure stalled compaction runs settle and release blocked session lanes. (#16331) Thanks @BinHPdev.
+
Agents: keep unresolved mutating tool failures visible until the same action retry succeeds, scope mutation-error surfacing to mutating calls (including session_status model changes), and dedupe duplicate failure warnings in outbound replies. (#16131) Thanks @Swader.
+
Agents/Process/Bootstrap: preserve unbounded process log offset-only pagination (default tail applies only when both offset and limit are omitted) and enforce strict bootstrapTotalMaxChars budgeting across injected bootstrap content (including markers), skipping additional injection when remaining budget is too small. (#16539) Thanks @CharlieGreenman.
+
Agents/Workspace: persist bootstrap onboarding state so partially initialized workspaces recover missing BOOTSTRAP.md once, while completed onboarding keeps BOOTSTRAP deleted even if runtime files are later recreated. Thanks @gumadeiras.
+
Agents/Workspace: create BOOTSTRAP.md when core workspace files are seeded in partially initialized workspaces, while keeping BOOTSTRAP one-shot after onboarding deletion. (#16457) Thanks @robbyczgw-cla.
+
Agents: classify external timeout aborts during compaction the same as internal timeouts, preventing unnecessary auth-profile rotation and preserving compaction-timeout snapshot fallback behavior. (#9855) Thanks @mverrilli.
+
Agents: treat empty-stream provider failures (request ended without sending any chunks) as timeout-class failover signals, enabling auth-profile rotation/fallback and showing a friendly timeout message instead of raw provider errors. (#10210) Thanks @zenchantlive.
+
Agents: treat read tool file_path arguments as valid in tool-start diagnostics to avoid false “read tool called without path” warnings when alias parameters are used. (#16717) Thanks @Stache73.
+
Ollama/Agents: avoid forcing tag enforcement for Ollama models, which could suppress all output as (no output). (#16191) Thanks @Glucksberg.
+
Plugins: suppress false duplicate plugin id warnings when the same extension is discovered via multiple paths (config/workspace/global vs bundled), while still warning on genuine duplicates. (#16222) Thanks @shadril238.
+
Skills: watch SKILL.md only when refreshing skills snapshot to avoid file-descriptor exhaustion in large data trees. (#11325) Thanks @household-bard.
+
Memory/QMD: make memory status read-only by skipping QMD boot update/embed side effects for status-only manager checks.
+
Memory/QMD: keep original QMD failures when builtin fallback initialization fails (for example missing embedding API keys), instead of replacing them with fallback init errors.
+
Memory/Builtin: keep memory status dirty reporting stable across invocations by deriving status-only manager dirty state from persisted index metadata instead of process-start defaults. (#10863) Thanks @BarryYangi.
+
Memory/QMD: cap QMD command output buffering to prevent memory exhaustion from pathological qmd command output.
+
Memory/QMD: parse qmd scope keys once per request to avoid repeated parsing in scope checks.
+
Memory/QMD: query QMD index using exact docid matches before falling back to prefix lookup for better recall correctness and index efficiency.
+
Memory/QMD: pass result limits to search/vsearch commands so QMD can cap results earlier.
+
Memory/QMD: avoid reading full markdown files when a from/lines window is requested in QMD reads.
+
Memory/QMD: skip rewriting unchanged session export markdown files during sync to reduce disk churn.
+
Memory/QMD: make QMD result JSON parsing resilient to noisy command output by extracting the first JSON array from noisy stdout.
+
Memory/QMD: treat prefixed no results found marker output as an empty result set in qmd JSON parsing. (#11302) Thanks @blazerui.
+
Memory/QMD: avoid multi-collection query ranking corruption by running one qmd query -c per managed collection and merging by best score (also used for search/vsearch fallback-to-query). (#16740) Thanks @volarian-vai.
Memory/QMD/Security: add rawKeyPrefix support for QMD scope rules and preserve legacy keyPrefix: "agent:..." matching, preventing scoped deny bypass when operators match agent-prefixed session keys.
+
Memory/Builtin: narrow memory watcher targets to markdown globs and ignore dependency/venv directories to reduce file-descriptor pressure during memory sync startup. (#11721) Thanks @rex05ai.
+
Security/Memory-LanceDB: treat recalled memories as untrusted context (escape injected memory text + explicit non-instruction framing), skip likely prompt-injection payloads during auto-capture, and restrict auto-capture to user messages to reduce memory-poisoning risk. (#12524) Thanks @davidschmid24.
+
Security/Memory-LanceDB: require explicit autoCapture: true opt-in (default is now disabled) to prevent automatic PII capture unless operators intentionally enable it. (#12552) Thanks @fr33d3m0n.
+
Diagnostics/Memory: prune stale diagnostic session state entries and cap tracked session states to prevent unbounded in-memory growth on long-running gateways. (#5136) Thanks @coygeek and @vignesh07.
+
Gateway/Memory: clean up agentRunSeq tracking on run completion/abort and enforce maintenance-time cap pruning to prevent unbounded sequence-map growth over long uptimes. (#6036) Thanks @coygeek and @vignesh07.
+
Auto-reply/Memory: bound ABORT_MEMORY growth by evicting oldest entries and deleting reset (false) flags so abort state tracking cannot grow unbounded over long uptimes. (#6629) Thanks @coygeek and @vignesh07.
+
Slack/Memory: bound thread-starter cache growth with TTL + max-size pruning to prevent long-running Slack gateways from accumulating unbounded thread cache state. (#5258) Thanks @coygeek and @vignesh07.
+
Outbound/Memory: bound directory cache growth with max-size eviction and proactive TTL pruning to prevent long-running gateways from accumulating unbounded directory entries. (#5140) Thanks @coygeek and @vignesh07.
+
Skills/Memory: remove disconnected nodes from remote-skills cache to prevent stale node metadata from accumulating over long uptimes. (#6760) Thanks @coygeek.
+
Sandbox/Tools: make sandbox file tools bind-mount aware (including absolute container paths) and enforce read-only bind semantics for writes. (#16379) Thanks @tasaankaeris.
+
Media/Security: allow local media reads from OpenClaw state workspace/ and sandboxes/ roots by default so generated workspace media can be delivered without unsafe global path bypasses. (#15541) Thanks @lanceji.
+
Media/Security: harden local media allowlist bypasses by requiring an explicit readFile override when callers mark paths as validated, and reject filesystem-root localRoots entries. (#16739)
+
Discord/Security: harden voice message media loading (SSRF + allowed-local-root checks) so tool-supplied paths/URLs cannot be used to probe internal URLs or read arbitrary local files.
+
Security/BlueBubbles: require explicit mediaLocalRoots allowlists for local outbound media path reads to prevent local file disclosure. (#16322) Thanks @mbelinky.
+
Security/BlueBubbles: reject ambiguous shared-path webhook routing when multiple webhook targets match the same guid/password.
+
Security/BlueBubbles: harden BlueBubbles webhook auth behind reverse proxies by only accepting passwordless webhooks for direct localhost loopback requests (forwarded/proxied requests now require a password). Thanks @simecek.
+
Feishu/Security: harden media URL fetching against SSRF and local file disclosure. (#16285) Thanks @mbelinky.
+
Security/Zalo: reject ambiguous shared-path webhook routing when multiple webhook targets match the same secret.
Security/Signal: harden signal-cli archive extraction during install to prevent path traversal outside the install root.
+
Security/Hooks: restrict hook transform modules to ~/.openclaw/hooks/transforms (prevents path traversal/escape module loads via config). Config note: hooks.transformsDir must now be within that directory. Thanks @akhmittra.
+
Security/Hooks: ignore hook package manifest entries that point outside the package directory (prevents out-of-tree handler loads during hook discovery).
+
Security/Archive: enforce archive extraction entry/size limits to prevent resource exhaustion from high-expansion ZIP/TAR archives. Thanks @vincentkoc.
+
Security/Media: reject oversized base64-backed input media before decoding to avoid large allocations. Thanks @vincentkoc.
+
Security/Media: stream and bound URL-backed input media fetches to prevent memory exhaustion from oversized responses. Thanks @vincentkoc.
+
Security/Skills: harden archive extraction for download-installed skills to prevent path traversal outside the target directory. Thanks @markmusson.
+
Security/Slack: compute command authorization for DM slash commands even when dmPolicy=open, preventing unauthorized users from running privileged commands via DM. Thanks @christos-eth.
+
Security/iMessage: keep DM pairing-store identities out of group allowlist authorization (prevents cross-context command authorization). Thanks @vincentkoc.
+
Security/Google Chat: deprecate users/ allowlists (treat users/... as immutable user id only); keep raw email allowlists for usability. Thanks @vincentkoc.
Telegram/Security: require numeric Telegram sender IDs for allowlist authorization (reject @username principals), auto-resolve @username to IDs in openclaw doctor --fix (when possible), and warn in openclaw security audit when legacy configs contain usernames. Thanks @vincentkoc.
+
Telegram/Security: reject Telegram webhook startup when webhookSecret is missing or empty (prevents unauthenticated webhook request forgery). Thanks @yueyueL.
+
Security/Windows: avoid shell invocation when spawning child processes to prevent cmd.exe metacharacter injection via untrusted CLI arguments (e.g. agent prompt text).
+
Telegram: set webhook callback timeout handling to onTimeout: "return" (10s) so long-running update processing no longer emits webhook 500s and retry storms. (#16763) Thanks @chansearrington.
+
Signal: preserve case-sensitive group: target IDs during normalization so mixed-case group IDs no longer fail with Group not found. (#16748) Thanks @repfigit.
+
Feishu/Security: harden media URL fetching against SSRF and local file disclosure. (#16285) Thanks @mbelinky.
+
Security/Agents: scope CLI process cleanup to owned child PIDs to avoid killing unrelated processes on shared hosts. Thanks @aether-ai-agent.
+
Security/Agents: enforce workspace-root path bounds for apply_patch in non-sandbox mode to block traversal and symlink escape writes. Thanks @p80n-sec.
+
Security/Agents: enforce symlink-escape checks for apply_patch delete hunks under workspaceOnly, while still allowing deleting the symlink itself. Thanks @p80n-sec.
+
Security/Agents (macOS): prevent shell injection when writing Claude CLI keychain credentials. (#15924) Thanks @aether-ai-agent.
+
macOS: hard-limit unkeyed openclaw://agent deep links and ignore deliver / to / channel unless a valid unattended key is provided. Thanks @Cillian-Collins.
+
Scripts/Security: validate GitHub logins and avoid shell invocation in scripts/update-clawtributors.ts to prevent command injection via malicious commit records. Thanks @scanleale.
+
Security: fix Chutes manual OAuth login state validation by requiring the full redirect URL (reject code-only pastes) (thanks @aether-ai-agent).
+
Security/Gateway: harden tool-supplied gatewayUrl overrides by restricting them to loopback or the configured gateway.remote.url. Thanks @p80n-sec.
+
Security/Gateway: block system.execApprovals.* via node.invoke (use exec.approvals.node.* instead). Thanks @christos-eth.
+
Security/Gateway: reject oversized base64 chat attachments before decoding to avoid large allocations. Thanks @vincentkoc.
+
Security/Gateway: stop returning raw resolved config values in skills.status requirement checks (prevents operator.read clients from reading secrets). Thanks @simecek.
Security/Exec approvals: prevent safeBins allowlist bypass via shell expansion (host exec allowlist mode only; not enabled by default). Thanks @christos-eth.
+
Security/Exec: harden PATH handling by disabling project-local node_modules/.bin bootstrapping by default, disallowing node-host PATH overrides, and spawning ACP servers via the current executable by default. Thanks @akhmittra.
+
Security/Tlon: harden Urbit URL fetching against SSRF by blocking private/internal hosts by default (opt-in: channels.tlon.allowPrivateNetwork). Thanks @p80n-sec.
+
Security/Voice Call (Telnyx): require webhook signature verification when receiving inbound events; configs without telnyx.publicKey are now rejected unless skipSignatureVerification is enabled. Thanks @p80n-sec.
+
Security/Voice Call: require valid Twilio webhook signatures even when ngrok free tier loopback compatibility mode is enabled. Thanks @p80n-sec.
+
Security/Discovery: stop treating Bonjour TXT records as authoritative routing (prefer resolved service endpoints) and prevent discovery from overriding stored TLS pins; autoconnect now requires a previously trusted gateway. Thanks @simecek.
Discord: unlock rich interactive agent prompts with Components v2 (buttons, selects, modals, and attachment-backed file blocks) so for native interaction through Discord. Thanks @thewilloftheshadow.
Plugins: expose llm_input and llm_output hook payloads so extensions can observe prompt/input context and model output usage details. (#16724) Thanks @SecondThread.
+
Subagents: nested sub-agents (sub-sub-agents) with configurable depth. Set agents.defaults.subagents.maxSpawnDepth: 2 to allow sub-agents to spawn their own children. Includes maxChildrenPerAgent limit (default 5), depth-aware tool policy, and proper announce chain routing. (#14447) Thanks @tyler6204.
+
Slack/Discord/Telegram: add per-channel ack reaction overrides (account/channel-level) to support platform-specific emoji formats. (#17092) Thanks @zerone0x.
+
Cron/Gateway: add finished-run webhook delivery toggle (notify) and dedicated webhook auth token support (cron.webhookToken) for outbound cron webhook posts. (#14535) Thanks @advaitpaliwal.
+
Channels: deduplicate probe/token resolution base types across core + extensions while preserving per-channel error typing. (#16986) Thanks @iyoda and @thewilloftheshadow.
+
+
Fixes
+
+
Security: replace deprecated SHA-1 sandbox configuration hashing with SHA-256 for deterministic sandbox cache identity and recreation checks. Thanks @kexinoh.
+
Security/Logging: redact Telegram bot tokens from error messages and uncaught stack traces to prevent accidental secret leakage into logs. Thanks @aether-ai-agent.
Sandbox: preserve array order in config hashing so order-sensitive Docker/browser settings trigger container recreation correctly. Thanks @kexinoh.
+
Gateway/Security: redact sensitive session/path details from status responses for non-admin clients; full details remain available to operator.admin. (#8590) Thanks @fr33d3m0n.
+
Gateway/Control UI: preserve requested operator scopes for Control UI bypass modes (allowInsecureAuth / dangerouslyDisableDeviceAuth) when device identity is unavailable, preventing false missing scope failures on authenticated LAN/HTTP operator sessions. (#17682) Thanks @leafbird.
+
LINE/Security: fail closed on webhook startup when channel token or channel secret is missing, and treat LINE accounts as configured only when both are present. (#17587) Thanks @davidahmann.
+
Skills/Security: restrict download installer targetDir to the per-skill tools directory to prevent arbitrary file writes. Thanks @Adam55A-code.
+
Skills/Linux: harden go installer fallback on apt-based systems by handling root/no-sudo environments safely, doing best-effort apt index refresh, and returning actionable errors instead of failing with spawn errors. (#17687) Thanks @mcrolly.
+
Web Fetch/Security: cap downloaded response body size before HTML parsing to prevent memory exhaustion from oversized or deeply nested pages. Thanks @xuemian168.
+
Config/Gateway: make sensitive-key whitelist suffix matching case-insensitive while preserving passwordFile path exemptions, preventing accidental redaction of non-secret config values like maxTokens and IRC password-file paths. (#16042) Thanks @akramcodez.
+
Dev tooling: harden git pre-commit hook against option injection from malicious filenames (for example --force), preventing accidental staging of ignored files. Thanks @mrthankyou.
+
Gateway/Agent: reject malformed agent:-prefixed session keys (for example, agent:main) in agent and agent.identity.get instead of silently resolving them to the default agent, preventing accidental cross-session routing. (#15707) Thanks @rodrigouroz.
+
Gateway/Chat: harden chat.send inbound message handling by rejecting null bytes, stripping unsafe control characters, and normalizing Unicode to NFC before dispatch. (#8593) Thanks @fr33d3m0n.
+
Gateway/Send: return an actionable error when send targets internal-only webchat, guiding callers to use chat.send or a deliverable channel. (#15703) Thanks @rodrigouroz.
+
Control UI: prevent stored XSS via assistant name/avatar by removing inline script injection, serving bootstrap config as JSON, and enforcing script-src 'self'. Thanks @Adam55A-code.
+
Agents/Security: sanitize workspace paths before embedding into LLM prompts (strip Unicode control/format chars) to prevent instruction injection via malicious directory names. Thanks @aether-ai-agent.
+
Agents/Sandbox: clarify system prompt path guidance so sandbox bash/exec uses container paths (for example /workspace) while file tools keep host-bridge mapping, avoiding first-attempt path misses from host-only absolute paths in sandbox command execution. (#17693) Thanks @app/juniordevbot.
+
Agents/Context: apply configured model contextWindow overrides after provider discovery so lookupContextTokens() honors operator config values (including discovery-failure paths). (#17404) Thanks @michaelbship and @vignesh07.
+
Agents/Context: derive lookupContextTokens() from auth-available model metadata and keep the smallest discovered context window for duplicate model ids, preventing cross-provider cache collisions from overestimating session context limits. (#17586) Thanks @githabideri and @vignesh07.
+
Agents/OpenAI: force store=true for direct OpenAI Responses/Codex runs to preserve multi-turn server-side conversation state, while leaving proxy/non-OpenAI endpoints unchanged. (#16803) Thanks @mark9232 and @vignesh07.
+
Memory/FTS: make buildFtsQuery Unicode-aware so non-ASCII queries (including CJK) produce keyword tokens instead of falling back to vector-only search. (#17672) Thanks @KinGP5471.
+
Auto-reply/Compaction: resolve memory/YYYY-MM-DD.md placeholders with timezone-aware runtime dates and append a Current time: line to memory-flush turns, preventing wrong-year memory filenames without making the system prompt time-variant. (#17603, #17633) Thanks @nicholaspapadam-wq and @vignesh07.
+
Agents: return an explicit timeout error reply when an embedded run times out before producing any payloads, preventing silent dropped turns during slow cache-refresh transitions. (#16659) Thanks @liaosvcaf and @vignesh07.
+
Group chats: always inject group chat context (name, participants, reply guidance) into the system prompt on every turn, not just the first. Prevents the model from losing awareness of which group it's in and incorrectly using the message tool to send to the same group. (#14447) Thanks @tyler6204.
+
Browser/Agents: when browser control service is unavailable, return explicit non-retry guidance (instead of "try again") so models do not loop on repeated browser tool calls until timeout. (#17673) Thanks @austenstone.
+
Subagents: use child-run-based deterministic announce idempotency keys across direct and queued delivery paths (with legacy queued-item fallback) to prevent duplicate announce retries without collapsing distinct same-millisecond announces. (#17150) Thanks @widingmarcus-cyber.
+
Subagents/Models: preserve agents.defaults.model.fallbacks when subagent sessions carry a model override, so subagent runs fail over to configured fallback models instead of retrying only the overridden primary model.
+
Telegram: omit message_thread_id for DM sends/draft previews and keep forum-topic handling (id=1 general omitted, non-general kept), preventing DM failures with 400 Bad Request: message thread not found. (#10942) Thanks @garnetlyx.
+
Telegram: replace inbound placeholder with successful preflight voice transcript in message body context, preventing placeholder-only prompt bodies for mention-gated voice messages. (#16789) Thanks @Limitless2023.
+
Telegram: retry inbound media getFile calls (3 attempts with backoff) and gracefully fall back to placeholder-only processing when retries fail, preventing dropped voice/media messages on transient Telegram network errors. (#16154) Thanks @yinghaosang.
+
Telegram: finalize streaming preview replies in place instead of sending a second final message, preventing duplicate Telegram assistant outputs at stream completion. (#17218) Thanks @obviyus.
+
Discord: preserve channel session continuity when runtime payloads omit message.channelId by falling back to event/raw channel_id values for routing/session keys, so same-channel messages keep history across turns/restarts. Also align diagnostics so active Discord runs no longer appear as sessionKey=unknown. (#17622) Thanks @shakkernerd.
+
Discord: dedupe native skill commands by skill name in multi-agent setups to prevent duplicated slash commands with _2 suffixes. (#17365) Thanks @seewhyme.
+
Discord: ensure role allowlist matching uses raw role IDs for message routing authorization. Thanks @xinhuagu.
+
Web UI/Agents: hide BOOTSTRAP.md in the Agents Files list after onboarding is completed, avoiding confusing missing-file warnings for completed workspaces. (#17491) Thanks @gumadeiras.
+
Auto-reply/WhatsApp/TUI/Web: when a final assistant message is NO_REPLY and a messaging tool send succeeded, mirror the delivered messaging-tool text into session-visible assistant output so TUI/Web no longer show NO_REPLY placeholders. (#7010) Thanks @Morrowind-Xie.
+
Cron: infer payload.kind="agentTurn" for model-only cron.update payload patches, so partial agent-turn updates do not fail validation when kind is omitted. (#15664) Thanks @rodrigouroz.
+
TUI: make searchable-select filtering and highlight rendering ANSI-aware so queries ignore hidden escape codes and no longer corrupt ANSI styling sequences during match highlighting. (#4519) Thanks @bee4come.
+
TUI/Windows: coalesce rapid single-line submit bursts in Git Bash into one multiline message as a fallback when bracketed paste is unavailable, preventing pasted multiline text from being split into multiple sends. (#4986) Thanks @adamkane.
+
TUI: suppress false (no output) placeholders for non-local empty final events during concurrent runs, preventing external-channel replies from showing empty assistant bubbles while a local run is still streaming. (#5782) Thanks @LagWizard and @vignesh07.
+
TUI: preserve copy-sensitive long tokens (URLs/paths/file-like identifiers) during wrapping and overflow sanitization so wrapped output no longer inserts spaces that corrupt copy/paste values. (#17515, #17466, #17505) Thanks @abe238, @trevorpan, and @JasonCry.
+
CLI/Build: make legacy daemon CLI compatibility shim generation tolerant of minimal tsdown daemon export sets, while preserving restart/register compatibility aliases and surfacing explicit errors for unavailable legacy daemon commands. Thanks @vignesh07.
CLI: add openclaw logs --local-time to display log timestamps in local timezone. (#13818) Thanks @xialonglee.
-
Telegram: render blockquotes as native tags instead of stripping them. (#14608)
-
Config: avoid redacting maxTokens-like fields during config snapshot redaction, preventing round-trip validation failures in /config. (#14006) Thanks @constansino.
-
-
Breaking
-
-
Hooks: POST /hooks/agent now rejects payload sessionKey overrides by default. To keep fixed hook context, set hooks.defaultSessionKey (recommended with hooks.allowedSessionKeyPrefixes: ["hook:"]). If you need legacy behavior, explicitly set hooks.allowRequestSessionKey: true. Thanks @alpernae for reporting.
Security/Audit: add hook session-routing hardening checks (hooks.defaultSessionKey, hooks.allowRequestSessionKey, and prefix allowlists), and warn when HTTP API endpoints allow explicit session-key routing.
-
Security/Sandbox: confine mirrored skill sync destinations to the sandbox skills/ root and stop using frontmatter-controlled skill names as filesystem destination paths. Thanks @1seal.
-
Security/Web tools: treat browser/web content as untrusted by default (wrapped outputs for browser snapshot/tabs/console and structured external-content metadata for web tools), and strip toolResult.details from model-facing transcript/compaction inputs to reduce prompt-injection replay risk.
-
Security/Hooks: harden webhook and device token verification with shared constant-time secret comparison, and add per-client auth-failure throttling for hook endpoints (429 + Retry-After). Thanks @akhmittra.
-
Security/Browser: require auth for loopback browser control HTTP routes, auto-generate gateway.auth.token when browser control starts without auth, and add a security-audit check for unauthenticated browser control. Thanks @tcusolle.
-
Sessions/Gateway: harden transcript path resolution and reject unsafe session IDs/file paths so session operations stay within agent sessions directories. Thanks @akhmittra.
-
Gateway: raise WS payload/buffer limits so 5,000,000-byte image attachments work reliably. (#14486) Thanks @0xRaini.
-
Logging/CLI: use local timezone timestamps for console prefixing, and include ±HH:MM offsets when using openclaw logs --local-time to avoid ambiguity. (#14771) Thanks @0xRaini.
-
Gateway: drain active turns before restart to prevent message loss. (#13931) Thanks @0xRaini.
-
Gateway: auto-generate auth token during install to prevent launchd restart loops. (#13813) Thanks @cathrynlavery.
-
Gateway: prevent undefined/missing token in auth config. (#13809) Thanks @asklee-klawd.
-
Gateway: handle async EPIPE on stdout/stderr during shutdown. (#13414) Thanks @keshav55.
-
Gateway/Control UI: resolve missing dashboard assets when openclaw is installed globally via symlink-based Node managers (nvm/fnm/n/Homebrew). (#14919) Thanks @aynorica.
-
Cron: use requested agentId for isolated job auth resolution. (#13983) Thanks @0xRaini.
-
Cron: prevent cron jobs from skipping execution when nextRunAtMs advances. (#14068) Thanks @WalterSumbon.
-
Cron: pass agentId to runHeartbeatOnce for main-session jobs. (#14140) Thanks @ishikawa-pro.
-
Cron: re-arm timers when onTimer fires while a job is still executing. (#14233) Thanks @tomron87.
-
Cron: prevent duplicate fires when multiple jobs trigger simultaneously. (#14256) Thanks @xinhuagu.
-
Cron: isolate scheduler errors so one bad job does not break all jobs. (#14385) Thanks @MarvinDontPanic.
-
Cron: prevent one-shot at jobs from re-firing on restart after skipped/errored runs. (#13878) Thanks @lailoo.
-
Heartbeat: prevent scheduler stalls on unexpected run errors and avoid immediate rerun loops after requests-in-flight skips. (#14901) Thanks @joeykrug.
-
Cron: honor stored session model overrides for isolated-agent runs while preserving hooks.gmail.model precedence for Gmail hook sessions. (#14983) Thanks @shtse8.
-
Logging/Browser: fall back to os.tmpdir()/openclaw for default log, browser trace, and browser download temp paths when /tmp/openclaw is unavailable.
-
WhatsApp: convert Markdown bold/strikethrough to WhatsApp formatting. (#14285) Thanks @Raikan10.
-
WhatsApp: allow media-only sends and normalize leading blank payloads. (#14408) Thanks @karimnaguib.
-
WhatsApp: default MIME type for voice messages when Baileys omits it. (#14444) Thanks @mcaxtr.
-
Telegram: handle no-text message in model picker editMessageText. (#14397) Thanks @0xRaini.
-
Telegram: surface REACTION_INVALID as non-fatal warning. (#14340) Thanks @0xRaini.
Slack: change default replyToMode from "off" to "all". (#14364) Thanks @nm-de.
-
Slack: detect control commands when channel messages start with bot mention prefixes (for example, @Bot /new). (#14142) Thanks @beefiker.
-
Signal: enforce E.164 validation for the Signal bot account prompt so mistyped numbers are caught early. (#15063) Thanks @Duartemartins.
-
Discord: process DM reactions instead of silently dropping them. (#10418) Thanks @mcaxtr.
-
Discord: respect replyToMode in threads. (#11062) Thanks @cordx56.
-
Heartbeat: filter noise-only system events so scheduled reminder notifications do not fire when cron runs carry only heartbeat markers. (#13317) Thanks @pvtclawn.
-
Signal: render mention placeholders as @uuid/@phone so mention gating and Clawdbot targeting work. (#2013) Thanks @alexgleason.
-
Discord: omit empty content fields for media-only messages while preserving caption whitespace. (#9507) Thanks @leszekszpunar.
-
Onboarding/Providers: add Z.AI endpoint-specific auth choices (zai-coding-global, zai-coding-cn, zai-global, zai-cn) and expand default Z.AI model wiring. (#13456) Thanks @tomsun28.
-
Onboarding/Providers: update MiniMax API default/recommended models from M2.1 to M2.5, add M2.5/M2.5-Lightning model entries, and include minimax-m2.5 in modern model filtering. (#14865) Thanks @adao-max.
-
Ollama: use configured models.providers.ollama.baseUrl for model discovery and normalize /v1 endpoints to the native Ollama API root. (#14131) Thanks @shtse8.
-
Voice Call: pass Twilio stream auth token via instead of query string. (#14029) Thanks @mcwigglesmcgee.
-
Feishu: pass Buffer directly to the Feishu SDK upload APIs instead of Readable.from(...) to avoid form-data upload failures. (#10345) Thanks @youngerstyle.
-
Feishu: trigger mention-gated group handling only when the bot itself is mentioned (not just any mention). (#11088) Thanks @openperf.
-
Feishu: probe status uses the resolved account context for multi-account credential checks. (#11233) Thanks @onevcat.
-
Feishu DocX: preserve top-level converted block order using firstLevelBlockIds when writing/appending documents. (#13994) Thanks @Cynosure159.
-
Feishu plugin packaging: remove workspace:*openclaw dependency from extensions/feishu and sync lockfile for install compatibility. (#14423) Thanks @jackcooper2015.
-
CLI/Wizard: exit with code 1 when configure, agents add, or interactive onboard wizards are canceled, so set -e automation stops correctly. (#14156) Thanks @0xRaini.
-
Media: strip MEDIA: lines with local paths instead of leaking as visible text. (#14399) Thanks @0xRaini.
-
Config/Cron: exclude maxTokens from config redaction and honor deleteAfterRun on skipped cron jobs. (#13342) Thanks @niceysam.
-
Config: ignore meta field changes in config file watcher. (#13460) Thanks @brandonwise.
-
Cron: use requested agentId for isolated job auth resolution. (#13983) Thanks @0xRaini.
-
Cron: pass agentId to runHeartbeatOnce for main-session jobs. (#14140) Thanks @ishikawa-pro.
-
Cron: prevent cron jobs from skipping execution when nextRunAtMs advances. (#14068) Thanks @WalterSumbon.
-
Cron: re-arm timers when onTimer fires while a job is still executing. (#14233) Thanks @tomron87.
-
Cron: prevent duplicate fires when multiple jobs trigger simultaneously. (#14256) Thanks @xinhuagu.
-
Cron: isolate scheduler errors so one bad job does not break all jobs. (#14385) Thanks @MarvinDontPanic.
-
Cron: prevent one-shot at jobs from re-firing on restart after skipped/errored runs. (#13878) Thanks @lailoo.
-
Daemon: suppress EPIPE error when restarting LaunchAgent. (#14343) Thanks @0xRaini.
-
Antigravity: add opus 4.6 forward-compat model and bypass thinking signature sanitization. (#14218) Thanks @jg-noncelogic.
-
Agents: prevent file descriptor leaks in child process cleanup. (#13565) Thanks @KyleChen26.
Agents: use last API call's cache tokens for context display instead of accumulated sum. (#13805) Thanks @akari-musubi.
-
Agents: keep followup-runner session totalTokens aligned with post-compaction context by using last-call usage and shared token-accounting logic. (#14979) Thanks @shtse8.
Hooks/Tools: dispatch before_tool_call and after_tool_call hooks from both tool execution paths with rebased conflict fixes. (#15012) Thanks @Patrick-Barletta, @Takhoffman.
-
Discord: allow channel-edit to archive/lock threads and set auto-archive duration. (#5542) Thanks @stumct.
-
Discord tests: use a partial @buape/carbon mock in slash command coverage. (#13262) Thanks @arosstale.
-
Tests: update thread ID handling in Slack message collection tests. (#14108) Thanks @swizzmagik.
Gateway: no more post-compaction amnesia; injected transcript writes now preserve Pi session parentId chain so agents can remember again. (#12283) Thanks @Takhoffman.
-]]>
-
-
\ No newline at end of file
diff --git a/apps/android/app/build.gradle.kts b/apps/android/app/build.gradle.kts
index 7bc18a89bc80d..870aaa59c1bac 100644
--- a/apps/android/app/build.gradle.kts
+++ b/apps/android/app/build.gradle.kts
@@ -21,8 +21,8 @@ android {
applicationId = "ai.openclaw.android"
minSdk = 31
targetSdk = 36
- versionCode = 202602130
- versionName = "2026.2.13"
+ versionCode = 202602190
+ versionName = "2026.2.19"
ndk {
// Support all major ABIs — native libs are tiny (~47 KB per ABI)
abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
@@ -63,7 +63,11 @@ android {
}
lint {
- disable += setOf("IconLauncherShape")
+ disable += setOf(
+ "GradleDependency",
+ "IconLauncherShape",
+ "NewerVersionAvailable",
+ )
warningsAsErrors = true
}
diff --git a/apps/android/app/src/main/java/ai/openclaw/android/gateway/GatewayTls.kt b/apps/android/app/src/main/java/ai/openclaw/android/gateway/GatewayTls.kt
index 1e43804d20e50..0726c94fc9738 100644
--- a/apps/android/app/src/main/java/ai/openclaw/android/gateway/GatewayTls.kt
+++ b/apps/android/app/src/main/java/ai/openclaw/android/gateway/GatewayTls.kt
@@ -8,6 +8,7 @@ import java.security.MessageDigest
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
+import java.util.Locale
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
@@ -91,9 +92,11 @@ suspend fun probeGatewayTlsFingerprint(
return withContext(Dispatchers.IO) {
val trustAll =
- @SuppressLint("CustomX509TrustManager")
+ @SuppressLint("CustomX509TrustManager", "TrustAllX509TrustManager")
object : X509TrustManager {
+ @SuppressLint("TrustAllX509TrustManager")
override fun checkClientTrusted(chain: Array, authType: String) {}
+ @SuppressLint("TrustAllX509TrustManager")
override fun checkServerTrusted(chain: Array, authType: String) {}
override fun getAcceptedIssuers(): Array = emptyArray()
}
@@ -144,7 +147,7 @@ private fun sha256Hex(data: ByteArray): String {
val digest = MessageDigest.getInstance("SHA-256").digest(data)
val out = StringBuilder(digest.size * 2)
for (byte in digest) {
- out.append(String.format("%02x", byte))
+ out.append(String.format(Locale.US, "%02x", byte))
}
return out.toString()
}
@@ -152,5 +155,5 @@ private fun sha256Hex(data: ByteArray): String {
private fun normalizeFingerprint(raw: String): String {
val stripped = raw.trim()
.replace(Regex("^sha-?256\\s*:?\\s*", RegexOption.IGNORE_CASE), "")
- return stripped.lowercase().filter { it in '0'..'9' || it in 'a'..'f' }
+ return stripped.lowercase(Locale.US).filter { it in '0'..'9' || it in 'a'..'f' }
}
diff --git a/apps/android/app/src/main/java/ai/openclaw/android/node/AppUpdateHandler.kt b/apps/android/app/src/main/java/ai/openclaw/android/node/AppUpdateHandler.kt
index 7472544d3172e..e54c846c0fbf7 100644
--- a/apps/android/app/src/main/java/ai/openclaw/android/node/AppUpdateHandler.kt
+++ b/apps/android/app/src/main/java/ai/openclaw/android/node/AppUpdateHandler.kt
@@ -187,11 +187,11 @@ class AppUpdateHandler(
lastNotifUpdate = now
if (contentLength > 0) {
val pct = ((totalBytes * 100) / contentLength).toInt()
- val mb = String.format("%.1f", totalBytes / 1048576.0)
- val totalMb = String.format("%.1f", contentLength / 1048576.0)
+ val mb = String.format(Locale.US, "%.1f", totalBytes / 1048576.0)
+ val totalMb = String.format(Locale.US, "%.1f", contentLength / 1048576.0)
notifManager.notify(notifId, buildProgressNotif(pct, 100, "$mb / $totalMb MB ($pct%)"))
} else {
- val mb = String.format("%.1f", totalBytes / 1048576.0)
+ val mb = String.format(Locale.US, "%.1f", totalBytes / 1048576.0)
notifManager.notify(notifId, buildProgressNotif(0, 0, "${mb} MB downloaded"))
}
}
@@ -239,13 +239,15 @@ class AppUpdateHandler(
// Use PackageInstaller session API — works from background on API 34+
// The system handles showing the install confirmation dialog
notifManager.cancel(notifId)
- notifManager.notify(notifId, android.app.Notification.Builder(appContext, channelId)
- .setSmallIcon(android.R.drawable.stat_sys_download_done)
- .setContentTitle("Installing Update...")
-
+ notifManager.notify(
+ notifId,
+ android.app.Notification.Builder(appContext, channelId)
+ .setSmallIcon(android.R.drawable.stat_sys_download_done)
+ .setContentTitle("Installing Update...")
.setContentIntent(launchPi)
- .setContentText("${String.format("%.1f", totalBytes / 1048576.0)} MB downloaded")
- .build())
+ .setContentText("${String.format(Locale.US, "%.1f", totalBytes / 1048576.0)} MB downloaded")
+ .build(),
+ )
val installer = appContext.packageManager.packageInstaller
val params = android.content.pm.PackageInstaller.SessionParams(
diff --git a/apps/ios/.swiftlint.yml b/apps/ios/.swiftlint.yml
index fc8509c83859e..23db4515968b7 100644
--- a/apps/ios/.swiftlint.yml
+++ b/apps/ios/.swiftlint.yml
@@ -3,3 +3,7 @@ parent_config: ../../.swiftlint.yml
included:
- Sources
- ../shared/ClawdisNodeKit/Sources
+
+type_body_length:
+ warning: 900
+ error: 1300
diff --git a/apps/ios/Config/Signing.xcconfig b/apps/ios/Config/Signing.xcconfig
new file mode 100644
index 0000000000000..e0afd46aa7e06
--- /dev/null
+++ b/apps/ios/Config/Signing.xcconfig
@@ -0,0 +1,18 @@
+// Shared iOS signing defaults for local development + CI.
+OPENCLAW_IOS_DEFAULT_TEAM = Y5PE65HELJ
+OPENCLAW_IOS_SELECTED_TEAM = $(OPENCLAW_IOS_DEFAULT_TEAM)
+OPENCLAW_APP_BUNDLE_ID = ai.openclaw.ios
+OPENCLAW_WATCH_APP_BUNDLE_ID = ai.openclaw.ios.watchkitapp
+OPENCLAW_WATCH_EXTENSION_BUNDLE_ID = ai.openclaw.ios.watchkitapp.extension
+
+// Local contributors can override this by running scripts/ios-configure-signing.sh.
+// Keep include after defaults: xcconfig is evaluated top-to-bottom.
+#include? "../.local-signing.xcconfig"
+#include? "../LocalSigning.xcconfig"
+
+CODE_SIGN_STYLE = Automatic
+CODE_SIGN_IDENTITY = Apple Development
+DEVELOPMENT_TEAM = $(OPENCLAW_IOS_SELECTED_TEAM)
+
+// Let Xcode manage provisioning for the selected local team.
+PROVISIONING_PROFILE_SPECIFIER =
diff --git a/apps/ios/LocalSigning.xcconfig.example b/apps/ios/LocalSigning.xcconfig.example
new file mode 100644
index 0000000000000..bfa610fb350bf
--- /dev/null
+++ b/apps/ios/LocalSigning.xcconfig.example
@@ -0,0 +1,14 @@
+// Copy to LocalSigning.xcconfig for personal local signing overrides.
+// This file is only an example and should stay committed.
+
+OPENCLAW_CODE_SIGN_STYLE = Automatic
+OPENCLAW_DEVELOPMENT_TEAM = P5Z8X89DJL
+
+OPENCLAW_APP_BUNDLE_ID = ai.openclaw.ios.test.mariano
+OPENCLAW_SHARE_BUNDLE_ID = ai.openclaw.ios.test.mariano.share
+OPENCLAW_WATCH_APP_BUNDLE_ID = ai.openclaw.ios.test.mariano.watchkitapp
+OPENCLAW_WATCH_EXTENSION_BUNDLE_ID = ai.openclaw.ios.test.mariano.watchkitapp.extension
+
+// Leave empty with automatic signing.
+OPENCLAW_APP_PROFILE =
+OPENCLAW_SHARE_PROFILE =
diff --git a/apps/ios/README.md b/apps/ios/README.md
index 2e426c18d70bf..b870bdcea583a 100644
--- a/apps/ios/README.md
+++ b/apps/ios/README.md
@@ -1,66 +1,110 @@
-# OpenClaw (iOS)
+# OpenClaw iOS (Super Alpha)
-This is an **alpha** iOS app that connects to an OpenClaw Gateway as a `role: node`.
+NO TEST FLIGHT AVAILABLE AT THIS POINT
-Expect rough edges:
+This iPhone app is super-alpha and internal-use only. It connects to an OpenClaw Gateway as a `role: node`.
-- UI and onboarding are changing quickly.
-- Background behavior is not stable yet (foreground app is the supported mode right now).
-- Permissions are opt-in and the app should be treated as sensitive while we harden it.
+## Distribution Status
-## What It Does
+NO TEST FLIGHT AVAILABLE AT THIS POINT
-- Connects to a Gateway over `ws://` / `wss://`
-- Pairs a new device (approved from your bot)
-- Exposes phone services as node commands (camera, location, photos, calendar, reminders, etc; gated by iOS permissions)
-- Provides Talk + Chat surfaces (alpha)
+- Current distribution: local/manual deploy from source via Xcode.
+- App Store flow is not part of the current internal development path.
-## Pairing (Recommended Flow)
+## Super-Alpha Disclaimer
-If your Gateway has the `device-pair` plugin installed:
+- Breaking changes are expected.
+- UI and onboarding flows can change without migration guarantees.
+- Foreground use is the only reliable mode right now.
+- Treat this build as sensitive while permissions and background behavior are still being hardened.
-1. In Telegram, message your bot: `/pair`
-2. Copy the **setup code** message
-3. On iOS: OpenClaw → Settings → Gateway → paste setup code → Connect
-4. Back in Telegram: `/pair approve`
+## Exact Xcode Manual Deploy Flow
-## Build And Run
-
-Prereqs:
-
-- Xcode (current stable)
-- `pnpm`
-- `xcodegen`
-
-From the repo root:
+1. Prereqs:
+ - Xcode 16+
+ - `pnpm`
+ - `xcodegen`
+ - Apple Development signing set up in Xcode
+2. From repo root:
```bash
pnpm install
-pnpm ios:open
+./scripts/ios-configure-signing.sh
+cd apps/ios
+xcodegen generate
+open OpenClaw.xcodeproj
```
-Then in Xcode:
-
-1. Select the `OpenClaw` scheme
-2. Select a simulator or a connected device
-3. Run
-
-If you're using a personal Apple Development team, you may need to change the bundle identifier in Xcode to a unique value so signing succeeds.
+3. In Xcode:
+ - Scheme: `OpenClaw`
+ - Destination: connected iPhone (recommended for real behavior)
+ - Build configuration: `Debug`
+ - Run (`Product` -> `Run`)
+4. If signing fails on a personal team:
+ - Use unique local bundle IDs via `apps/ios/LocalSigning.xcconfig`.
+ - Start from `apps/ios/LocalSigning.xcconfig.example`.
-## Build From CLI
+Shortcut command (same flow + open project):
```bash
-pnpm ios:build
-```
-
-## Tests
-
-```bash
-cd apps/ios
-xcodegen generate
-xcodebuild test -project OpenClaw.xcodeproj -scheme OpenClaw -destination "platform=iOS Simulator,name=iPhone 17"
+pnpm ios:open
```
-## Shared Code
-
-- `apps/shared/OpenClawKit` contains the shared transport/types used by the iOS app.
+## APNs Expectations For Local/Manual Builds
+
+- The app calls `registerForRemoteNotifications()` at launch.
+- `apps/ios/Sources/OpenClaw.entitlements` sets `aps-environment` to `development`.
+- APNs token registration to gateway happens only after gateway connection (`push.apns.register`).
+- Your selected team/profile must support Push Notifications for the app bundle ID you are signing.
+- If push capability or provisioning is wrong, APNs registration fails at runtime (check Xcode logs for `APNs registration failed`).
+- Debug builds register as APNs sandbox; Release builds use production.
+
+## What Works Now (Concrete)
+
+- Pairing via setup code flow (`/pair` then `/pair approve` in Telegram).
+- Gateway connection via discovery or manual host/port with TLS fingerprint trust prompt.
+- Chat + Talk surfaces through the operator gateway session.
+- iPhone node commands in foreground: camera snap/clip, canvas present/navigate/eval/snapshot, screen record, location, contacts, calendar, reminders, photos, motion, local notifications.
+- Share extension deep-link forwarding into the connected gateway session.
+
+## Known Issues / Limitations / Problems
+
+- Foreground-first: iOS can suspend sockets in background; reconnect recovery is still being tuned.
+- Background command limits are strict: `canvas.*`, `camera.*`, `screen.*`, and `talk.*` are blocked when backgrounded.
+- Background location requires `Always` location permission.
+- Pairing/auth errors intentionally pause reconnect loops until a human fixes auth/pairing state.
+- Voice Wake and Talk contend for the same microphone; Talk suppresses wake capture while active.
+- APNs reliability depends on local signing/provisioning/topic alignment.
+- Expect rough UX edges and occasional reconnect churn during active development.
+
+## Current In-Progress Workstream
+
+Automatic wake/reconnect hardening:
+
+- improve wake/resume behavior across scene transitions
+- reduce dead-socket states after background -> foreground
+- tighten node/operator session reconnect coordination
+- reduce manual recovery steps after transient network failures
+
+## Debugging Checklist
+
+1. Confirm build/signing baseline:
+ - regenerate project (`xcodegen generate`)
+ - verify selected team + bundle IDs
+2. In app `Settings -> Gateway`:
+ - confirm status text, server, and remote address
+ - verify whether status shows pairing/auth gating
+3. If pairing is required:
+ - run `/pair approve` from Telegram, then reconnect
+4. If discovery is flaky:
+ - enable `Discovery Debug Logs`
+ - inspect `Settings -> Gateway -> Discovery Logs`
+5. If network path is unclear:
+ - switch to manual host/port + TLS in Gateway Advanced settings
+6. In Xcode console, filter for subsystem/category signals:
+ - `ai.openclaw.ios`
+ - `GatewayDiag`
+ - `APNs registration failed`
+7. Validate background expectations:
+ - repro in foreground first
+ - then test background transitions and confirm reconnect on return
diff --git a/apps/ios/ShareExtension/Info.plist b/apps/ios/ShareExtension/Info.plist
new file mode 100644
index 0000000000000..bc1f60bc24dab
--- /dev/null
+++ b/apps/ios/ShareExtension/Info.plist
@@ -0,0 +1,45 @@
+
+
+
+
+ CFBundleDevelopmentRegion
+ $(DEVELOPMENT_LANGUAGE)
+ CFBundleDisplayName
+ OpenClaw Share
+ CFBundleExecutable
+ $(EXECUTABLE_NAME)
+ CFBundleIdentifier
+ $(PRODUCT_BUNDLE_IDENTIFIER)
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ $(PRODUCT_NAME)
+ CFBundlePackageType
+ XPC!
+ CFBundleShortVersionString
+ 2026.2.19
+ CFBundleVersion
+ 20260219
+ NSExtension
+
+ NSExtensionAttributes
+
+ NSExtensionActivationRule
+
+ NSExtensionActivationSupportsImageWithMaxCount
+ 10
+ NSExtensionActivationSupportsMovieWithMaxCount
+ 1
+ NSExtensionActivationSupportsText
+
+ NSExtensionActivationSupportsWebURLWithMaxCount
+ 1
+
+
+ NSExtensionPointIdentifier
+ com.apple.share-services
+ NSExtensionPrincipalClass
+ $(PRODUCT_MODULE_NAME).ShareViewController
+
+
+
diff --git a/apps/ios/ShareExtension/ShareViewController.swift b/apps/ios/ShareExtension/ShareViewController.swift
new file mode 100644
index 0000000000000..1181641e33097
--- /dev/null
+++ b/apps/ios/ShareExtension/ShareViewController.swift
@@ -0,0 +1,548 @@
+import Foundation
+import OpenClawKit
+import os
+import UIKit
+import UniformTypeIdentifiers
+
+final class ShareViewController: UIViewController {
+ private struct ShareAttachment: Codable {
+ var type: String
+ var mimeType: String
+ var fileName: String
+ var content: String
+ }
+
+ private struct ExtractedShareContent {
+ var payload: SharedContentPayload
+ var attachments: [ShareAttachment]
+ }
+
+ private let logger = Logger(subsystem: "ai.openclaw.ios", category: "ShareExtension")
+ private var statusLabel: UILabel?
+ private let draftTextView = UITextView()
+ private let sendButton = UIButton(type: .system)
+ private let cancelButton = UIButton(type: .system)
+ private var didPrepareDraft = false
+ private var isSending = false
+ private var pendingAttachments: [ShareAttachment] = []
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ self.preferredContentSize = CGSize(width: UIScreen.main.bounds.width, height: 420)
+ self.setupUI()
+ }
+
+ override func viewDidAppear(_ animated: Bool) {
+ super.viewDidAppear(animated)
+ guard !self.didPrepareDraft else { return }
+ self.didPrepareDraft = true
+ Task { await self.prepareDraft() }
+ }
+
+ private func setupUI() {
+ self.view.backgroundColor = .systemBackground
+
+ self.draftTextView.translatesAutoresizingMaskIntoConstraints = false
+ self.draftTextView.font = .preferredFont(forTextStyle: .body)
+ self.draftTextView.backgroundColor = UIColor.secondarySystemBackground
+ self.draftTextView.layer.cornerRadius = 10
+ self.draftTextView.textContainerInset = UIEdgeInsets(top: 12, left: 10, bottom: 12, right: 10)
+
+ self.sendButton.translatesAutoresizingMaskIntoConstraints = false
+ self.sendButton.setTitle("Send to OpenClaw", for: .normal)
+ self.sendButton.titleLabel?.font = .preferredFont(forTextStyle: .headline)
+ self.sendButton.addTarget(self, action: #selector(self.handleSendTap), for: .touchUpInside)
+ self.sendButton.isEnabled = false
+
+ self.cancelButton.translatesAutoresizingMaskIntoConstraints = false
+ self.cancelButton.setTitle("Cancel", for: .normal)
+ self.cancelButton.addTarget(self, action: #selector(self.handleCancelTap), for: .touchUpInside)
+
+ let buttons = UIStackView(arrangedSubviews: [self.cancelButton, self.sendButton])
+ buttons.translatesAutoresizingMaskIntoConstraints = false
+ buttons.axis = .horizontal
+ buttons.alignment = .fill
+ buttons.distribution = .fillEqually
+ buttons.spacing = 12
+
+ self.view.addSubview(self.draftTextView)
+ self.view.addSubview(buttons)
+
+ NSLayoutConstraint.activate([
+ self.draftTextView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 14),
+ self.draftTextView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 14),
+ self.draftTextView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -14),
+ self.draftTextView.bottomAnchor.constraint(equalTo: buttons.topAnchor, constant: -12),
+
+ buttons.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 14),
+ buttons.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -14),
+ buttons.bottomAnchor.constraint(equalTo: self.view.keyboardLayoutGuide.topAnchor, constant: -8),
+ buttons.heightAnchor.constraint(equalToConstant: 44),
+ ])
+ }
+
+ private func prepareDraft() async {
+ let traceId = UUID().uuidString
+ ShareGatewayRelaySettings.saveLastEvent("Share opened.")
+ self.showStatus("Preparing share…")
+ self.logger.info("share begin trace=\(traceId, privacy: .public)")
+ let extracted = await self.extractSharedContent()
+ let payload = extracted.payload
+ self.pendingAttachments = extracted.attachments
+ self.logger.info(
+ "share payload trace=\(traceId, privacy: .public) titleChars=\(payload.title?.count ?? 0) textChars=\(payload.text?.count ?? 0) hasURL=\(payload.url != nil) imageAttachments=\(self.pendingAttachments.count)"
+ )
+ let message = self.composeDraft(from: payload)
+ await MainActor.run {
+ self.draftTextView.text = message
+ self.sendButton.isEnabled = true
+ self.draftTextView.becomeFirstResponder()
+ }
+ if message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ ShareGatewayRelaySettings.saveLastEvent("Share ready: waiting for message input.")
+ self.showStatus("Add a message, then tap Send.")
+ } else {
+ ShareGatewayRelaySettings.saveLastEvent("Share ready: draft prepared.")
+ self.showStatus("Edit text, then tap Send.")
+ }
+ }
+
+ @objc
+ private func handleSendTap() {
+ guard !self.isSending else { return }
+ Task { await self.sendCurrentDraft() }
+ }
+
+ @objc
+ private func handleCancelTap() {
+ self.extensionContext?.completeRequest(returningItems: nil)
+ }
+
+ private func sendCurrentDraft() async {
+ let message = await MainActor.run { self.draftTextView.text ?? "" }
+ let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else {
+ ShareGatewayRelaySettings.saveLastEvent("Share blocked: message is empty.")
+ self.showStatus("Message is empty.")
+ return
+ }
+
+ await MainActor.run {
+ self.isSending = true
+ self.sendButton.isEnabled = false
+ self.cancelButton.isEnabled = false
+ }
+ self.showStatus("Sending to OpenClaw gateway…")
+ ShareGatewayRelaySettings.saveLastEvent("Sending to gateway…")
+ do {
+ try await self.sendMessageToGateway(trimmed, attachments: self.pendingAttachments)
+ ShareGatewayRelaySettings.saveLastEvent(
+ "Sent to gateway (\(trimmed.count) chars, \(self.pendingAttachments.count) attachment(s)).")
+ self.showStatus("Sent to OpenClaw.")
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.45) {
+ self.extensionContext?.completeRequest(returningItems: nil)
+ }
+ } catch {
+ self.logger.error("share send failed reason=\(error.localizedDescription, privacy: .public)")
+ ShareGatewayRelaySettings.saveLastEvent("Send failed: \(error.localizedDescription)")
+ self.showStatus("Send failed: \(error.localizedDescription)")
+ await MainActor.run {
+ self.isSending = false
+ self.sendButton.isEnabled = true
+ self.cancelButton.isEnabled = true
+ }
+ }
+ }
+
+ private func sendMessageToGateway(_ message: String, attachments: [ShareAttachment]) async throws {
+ guard let config = ShareGatewayRelaySettings.loadConfig() else {
+ throw NSError(
+ domain: "OpenClawShare",
+ code: 10,
+ userInfo: [NSLocalizedDescriptionKey: "OpenClaw is not connected to a gateway yet."])
+ }
+ guard let url = URL(string: config.gatewayURLString) else {
+ throw NSError(
+ domain: "OpenClawShare",
+ code: 11,
+ userInfo: [NSLocalizedDescriptionKey: "Invalid saved gateway URL."])
+ }
+
+ let gateway = GatewayNodeSession()
+ defer {
+ Task { await gateway.disconnect() }
+ }
+ let makeOptions: (String) -> GatewayConnectOptions = { clientId in
+ GatewayConnectOptions(
+ role: "node",
+ scopes: [],
+ caps: [],
+ commands: [],
+ permissions: [:],
+ clientId: clientId,
+ clientMode: "node",
+ clientDisplayName: "OpenClaw Share",
+ includeDeviceIdentity: false)
+ }
+
+ do {
+ try await gateway.connect(
+ url: url,
+ token: config.token,
+ password: config.password,
+ connectOptions: makeOptions("openclaw-ios"),
+ sessionBox: nil,
+ onConnected: {},
+ onDisconnected: { _ in },
+ onInvoke: { req in
+ BridgeInvokeResponse(
+ id: req.id,
+ ok: false,
+ error: OpenClawNodeError(
+ code: .invalidRequest,
+ message: "share extension does not support node invoke"))
+ })
+ } catch {
+ let expectsLegacyClientId = self.shouldRetryWithLegacyClientId(error)
+ guard expectsLegacyClientId else { throw error }
+ try await gateway.connect(
+ url: url,
+ token: config.token,
+ password: config.password,
+ connectOptions: makeOptions("moltbot-ios"),
+ sessionBox: nil,
+ onConnected: {},
+ onDisconnected: { _ in },
+ onInvoke: { req in
+ BridgeInvokeResponse(
+ id: req.id,
+ ok: false,
+ error: OpenClawNodeError(
+ code: .invalidRequest,
+ message: "share extension does not support node invoke"))
+ })
+ }
+
+ struct AgentRequestPayload: Codable {
+ var message: String
+ var sessionKey: String?
+ var thinking: String
+ var deliver: Bool
+ var attachments: [ShareAttachment]?
+ var receipt: Bool
+ var receiptText: String?
+ var to: String?
+ var channel: String?
+ var timeoutSeconds: Int?
+ var key: String?
+ }
+
+ let deliveryChannel = config.deliveryChannel?.trimmingCharacters(in: .whitespacesAndNewlines)
+ let deliveryTo = config.deliveryTo?.trimmingCharacters(in: .whitespacesAndNewlines)
+ let canDeliverToRoute = (deliveryChannel?.isEmpty == false) && (deliveryTo?.isEmpty == false)
+
+ let params = AgentRequestPayload(
+ message: message,
+ sessionKey: config.sessionKey,
+ thinking: "low",
+ deliver: canDeliverToRoute,
+ attachments: attachments.isEmpty ? nil : attachments,
+ receipt: canDeliverToRoute,
+ receiptText: canDeliverToRoute ? "Just received your iOS share + request, working on it." : nil,
+ to: canDeliverToRoute ? deliveryTo : nil,
+ channel: canDeliverToRoute ? deliveryChannel : nil,
+ timeoutSeconds: nil,
+ key: UUID().uuidString)
+ let data = try JSONEncoder().encode(params)
+ guard let json = String(data: data, encoding: .utf8) else {
+ throw NSError(
+ domain: "OpenClawShare",
+ code: 12,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to encode chat payload."])
+ }
+ struct NodeEventParams: Codable {
+ var event: String
+ var payloadJSON: String
+ }
+ let eventData = try JSONEncoder().encode(NodeEventParams(event: "agent.request", payloadJSON: json))
+ guard let nodeEventParams = String(data: eventData, encoding: .utf8) else {
+ throw NSError(
+ domain: "OpenClawShare",
+ code: 13,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to encode node event payload."])
+ }
+ _ = try await gateway.request(method: "node.event", paramsJSON: nodeEventParams, timeoutSeconds: 25)
+ }
+
+ private func shouldRetryWithLegacyClientId(_ error: Error) -> Bool {
+ if let gatewayError = error as? GatewayResponseError {
+ let code = gatewayError.code.lowercased()
+ let message = gatewayError.message.lowercased()
+ let pathValue = (gatewayError.details["path"]?.value as? String)?.lowercased() ?? ""
+ let mentionsClientIdPath =
+ message.contains("/client/id") || message.contains("client id")
+ || pathValue.contains("/client/id")
+ let isInvalidConnectParams =
+ (code.contains("invalid") && code.contains("connect"))
+ || message.contains("invalid connect params")
+ if isInvalidConnectParams && mentionsClientIdPath {
+ return true
+ }
+ }
+
+ let text = error.localizedDescription.lowercased()
+ return text.contains("invalid connect params")
+ && (text.contains("/client/id") || text.contains("client id"))
+ }
+
+ private func showStatus(_ text: String) {
+ DispatchQueue.main.async {
+ let label: UILabel
+ if let existing = self.statusLabel {
+ label = existing
+ } else {
+ let newLabel = UILabel()
+ newLabel.translatesAutoresizingMaskIntoConstraints = false
+ newLabel.numberOfLines = 0
+ newLabel.textAlignment = .center
+ newLabel.font = .preferredFont(forTextStyle: .body)
+ newLabel.textColor = .label
+ newLabel.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.92)
+ newLabel.layer.cornerRadius = 12
+ newLabel.clipsToBounds = true
+ newLabel.layoutMargins = UIEdgeInsets(top: 12, left: 14, bottom: 12, right: 14)
+ self.view.addSubview(newLabel)
+ NSLayoutConstraint.activate([
+ newLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 18),
+ newLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -18),
+ newLabel.bottomAnchor.constraint(equalTo: self.sendButton.topAnchor, constant: -10),
+ ])
+ self.statusLabel = newLabel
+ label = newLabel
+ }
+ label.text = " \(text) "
+ }
+ }
+
+ private func composeDraft(from payload: SharedContentPayload) -> String {
+ var lines: [String] = []
+ let title = self.sanitizeDraftFragment(payload.title)
+ let text = self.sanitizeDraftFragment(payload.text)
+ let url = payload.url?.absoluteString.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+
+ if let title, !title.isEmpty { lines.append(title) }
+ if let text, !text.isEmpty { lines.append(text) }
+ if !url.isEmpty { lines.append(url) }
+
+ return lines.joined(separator: "\n\n")
+ }
+
+ private func sanitizeDraftFragment(_ raw: String?) -> String? {
+ guard let raw else { return nil }
+ let banned = [
+ "shared from ios.",
+ "text:",
+ "shared attachment(s):",
+ "please help me with this.",
+ "please help me with this.w",
+ ]
+ let cleanedLines = raw
+ .components(separatedBy: .newlines)
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { line in
+ guard !line.isEmpty else { return false }
+ let lowered = line.lowercased()
+ return !banned.contains { lowered == $0 || lowered.hasPrefix($0) }
+ }
+ let cleaned = cleanedLines.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
+ return cleaned.isEmpty ? nil : cleaned
+ }
+
+ private func extractSharedContent() async -> ExtractedShareContent {
+ guard let items = self.extensionContext?.inputItems as? [NSExtensionItem] else {
+ return ExtractedShareContent(
+ payload: SharedContentPayload(title: nil, url: nil, text: nil),
+ attachments: [])
+ }
+
+ var title: String?
+ var sharedURL: URL?
+ var sharedText: String?
+ var imageCount = 0
+ var videoCount = 0
+ var fileCount = 0
+ var unknownCount = 0
+ var attachments: [ShareAttachment] = []
+ let maxImageAttachments = 3
+
+ for item in items {
+ if title == nil {
+ title = item.attributedTitle?.string ?? item.attributedContentText?.string
+ }
+
+ for provider in item.attachments ?? [] {
+ if sharedURL == nil {
+ sharedURL = await self.loadURL(from: provider)
+ }
+
+ if sharedText == nil {
+ sharedText = await self.loadText(from: provider)
+ }
+
+ if provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) {
+ imageCount += 1
+ if attachments.count < maxImageAttachments,
+ let attachment = await self.loadImageAttachment(from: provider, index: attachments.count)
+ {
+ attachments.append(attachment)
+ }
+ } else if provider.hasItemConformingToTypeIdentifier(UTType.movie.identifier) {
+ videoCount += 1
+ } else if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) {
+ fileCount += 1
+ } else {
+ unknownCount += 1
+ }
+
+ }
+ }
+
+ _ = imageCount
+ _ = videoCount
+ _ = fileCount
+ _ = unknownCount
+
+ return ExtractedShareContent(
+ payload: SharedContentPayload(title: title, url: sharedURL, text: sharedText),
+ attachments: attachments)
+ }
+
+ private func loadImageAttachment(from provider: NSItemProvider, index: Int) async -> ShareAttachment? {
+ let imageUTI = self.preferredImageTypeIdentifier(from: provider) ?? UTType.image.identifier
+ guard let rawData = await self.loadDataValue(from: provider, typeIdentifier: imageUTI) else {
+ return nil
+ }
+
+ let maxBytes = 5_000_000
+ guard let image = UIImage(data: rawData),
+ let data = self.normalizedJPEGData(from: image, maxBytes: maxBytes)
+ else {
+ return nil
+ }
+
+ return ShareAttachment(
+ type: "image",
+ mimeType: "image/jpeg",
+ fileName: "shared-image-\(index + 1).jpg",
+ content: data.base64EncodedString())
+ }
+
+ private func preferredImageTypeIdentifier(from provider: NSItemProvider) -> String? {
+ for identifier in provider.registeredTypeIdentifiers {
+ guard let utType = UTType(identifier) else { continue }
+ if utType.conforms(to: .image) {
+ return identifier
+ }
+ }
+ return nil
+ }
+
+ private func normalizedJPEGData(from image: UIImage, maxBytes: Int) -> Data? {
+ var quality: CGFloat = 0.9
+ while quality >= 0.4 {
+ if let data = image.jpegData(compressionQuality: quality), data.count <= maxBytes {
+ return data
+ }
+ quality -= 0.1
+ }
+ guard let fallback = image.jpegData(compressionQuality: 0.35) else { return nil }
+ if fallback.count <= maxBytes { return fallback }
+ return nil
+ }
+
+ private func loadURL(from provider: NSItemProvider) async -> URL? {
+ if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier) {
+ if let url = await self.loadURLValue(
+ from: provider,
+ typeIdentifier: UTType.url.identifier)
+ {
+ return url
+ }
+ }
+
+ if provider.hasItemConformingToTypeIdentifier(UTType.text.identifier) {
+ if let text = await self.loadTextValue(from: provider, typeIdentifier: UTType.text.identifier),
+ let url = URL(string: text.trimmingCharacters(in: .whitespacesAndNewlines)),
+ url.scheme != nil
+ {
+ return url
+ }
+ }
+
+ return nil
+ }
+
+ private func loadText(from provider: NSItemProvider) async -> String? {
+ if provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {
+ if let text = await self.loadTextValue(from: provider, typeIdentifier: UTType.plainText.identifier) {
+ return text
+ }
+ }
+
+ if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier) {
+ if let url = await self.loadURLValue(from: provider, typeIdentifier: UTType.url.identifier) {
+ return url.absoluteString
+ }
+ }
+
+ return nil
+ }
+
+ private func loadURLValue(from provider: NSItemProvider, typeIdentifier: String) async -> URL? {
+ await withCheckedContinuation { continuation in
+ provider.loadItem(forTypeIdentifier: typeIdentifier, options: nil) { item, _ in
+ if let url = item as? URL {
+ continuation.resume(returning: url)
+ return
+ }
+ if let str = item as? String, let url = URL(string: str) {
+ continuation.resume(returning: url)
+ return
+ }
+ if let ns = item as? NSString, let url = URL(string: ns as String) {
+ continuation.resume(returning: url)
+ return
+ }
+ continuation.resume(returning: nil)
+ }
+ }
+ }
+
+ private func loadTextValue(from provider: NSItemProvider, typeIdentifier: String) async -> String? {
+ await withCheckedContinuation { continuation in
+ provider.loadItem(forTypeIdentifier: typeIdentifier, options: nil) { item, _ in
+ if let text = item as? String {
+ continuation.resume(returning: text)
+ return
+ }
+ if let text = item as? NSString {
+ continuation.resume(returning: text as String)
+ return
+ }
+ if let text = item as? NSAttributedString {
+ continuation.resume(returning: text.string)
+ return
+ }
+ continuation.resume(returning: nil)
+ }
+ }
+ }
+
+ private func loadDataValue(from provider: NSItemProvider, typeIdentifier: String) async -> Data? {
+ await withCheckedContinuation { continuation in
+ provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, _ in
+ continuation.resume(returning: data)
+ }
+ }
+ }
+}
diff --git a/apps/ios/Signing.xcconfig b/apps/ios/Signing.xcconfig
new file mode 100644
index 0000000000000..f942fc0224ff6
--- /dev/null
+++ b/apps/ios/Signing.xcconfig
@@ -0,0 +1,17 @@
+// Default signing values for shared/repo builds.
+// Auto-selected local team overrides live in .local-signing.xcconfig (git-ignored).
+// Manual local overrides can go in LocalSigning.xcconfig (git-ignored).
+
+OPENCLAW_CODE_SIGN_STYLE = Manual
+OPENCLAW_DEVELOPMENT_TEAM = Y5PE65HELJ
+
+OPENCLAW_APP_BUNDLE_ID = ai.openclaw.ios
+OPENCLAW_SHARE_BUNDLE_ID = ai.openclaw.ios.share
+
+OPENCLAW_APP_PROFILE = ai.openclaw.ios Development
+OPENCLAW_SHARE_PROFILE = ai.openclaw.ios.share Development
+
+// Keep local includes after defaults: xcconfig is evaluated top-to-bottom,
+// so later assignments in local files override the defaults above.
+#include? ".local-signing.xcconfig"
+#include? "LocalSigning.xcconfig"
diff --git a/apps/ios/Sources/Calendar/CalendarService.swift b/apps/ios/Sources/Calendar/CalendarService.swift
index 9ac83dd39285b..94b2d9ea3f5ff 100644
--- a/apps/ios/Sources/Calendar/CalendarService.swift
+++ b/apps/ios/Sources/Calendar/CalendarService.swift
@@ -6,7 +6,7 @@ final class CalendarService: CalendarServicing {
func events(params: OpenClawCalendarEventsParams) async throws -> OpenClawCalendarEventsPayload {
let store = EKEventStore()
let status = EKEventStore.authorizationStatus(for: .event)
- let authorized = await Self.ensureAuthorization(store: store, status: status)
+ let authorized = EventKitAuthorization.allowsRead(status: status)
guard authorized else {
throw NSError(domain: "Calendar", code: 1, userInfo: [
NSLocalizedDescriptionKey: "CALENDAR_PERMISSION_REQUIRED: grant Calendar permission",
@@ -39,7 +39,7 @@ final class CalendarService: CalendarServicing {
func add(params: OpenClawCalendarAddParams) async throws -> OpenClawCalendarAddPayload {
let store = EKEventStore()
let status = EKEventStore.authorizationStatus(for: .event)
- let authorized = await Self.ensureWriteAuthorization(store: store, status: status)
+ let authorized = EventKitAuthorization.allowsWrite(status: status)
guard authorized else {
throw NSError(domain: "Calendar", code: 2, userInfo: [
NSLocalizedDescriptionKey: "CALENDAR_PERMISSION_REQUIRED: grant Calendar permission",
@@ -95,38 +95,6 @@ final class CalendarService: CalendarServicing {
return OpenClawCalendarAddPayload(event: payload)
}
- private static func ensureAuthorization(store: EKEventStore, status: EKAuthorizationStatus) async -> Bool {
- switch status {
- case .authorized:
- return true
- case .notDetermined:
- // Don’t prompt during node.invoke; prompts block the invoke and lead to timeouts.
- return false
- case .restricted, .denied:
- return false
- case .fullAccess:
- return true
- case .writeOnly:
- return false
- @unknown default:
- return false
- }
- }
-
- private static func ensureWriteAuthorization(store: EKEventStore, status: EKAuthorizationStatus) async -> Bool {
- switch status {
- case .authorized, .fullAccess, .writeOnly:
- return true
- case .notDetermined:
- // Don’t prompt during node.invoke; prompts block the invoke and lead to timeouts.
- return false
- case .restricted, .denied:
- return false
- @unknown default:
- return false
- }
- }
-
private static func resolveCalendar(
store: EKEventStore,
calendarId: String?,
diff --git a/apps/ios/Sources/Camera/CameraController.swift b/apps/ios/Sources/Camera/CameraController.swift
index e76dbeeabb90e..1e9c10bc44c93 100644
--- a/apps/ios/Sources/Camera/CameraController.swift
+++ b/apps/ios/Sources/Camera/CameraController.swift
@@ -93,14 +93,10 @@ actor CameraController {
}
withExtendedLifetime(delegate) {}
- let maxPayloadBytes = 5 * 1024 * 1024
- // Base64 inflates payloads by ~4/3; cap encoded bytes so the payload stays under 5MB (API limit).
- let maxEncodedBytes = (maxPayloadBytes / 4) * 3
- let res = try JPEGTranscoder.transcodeToJPEG(
- imageData: rawData,
+ let res = try PhotoCapture.transcodeJPEGForGateway(
+ rawData: rawData,
maxWidthPx: maxWidth,
- quality: quality,
- maxBytes: maxEncodedBytes)
+ quality: quality)
return (
format: format.rawValue,
@@ -335,8 +331,8 @@ private final class PhotoCaptureDelegate: NSObject, AVCapturePhotoCaptureDelegat
func photoOutput(
_ output: AVCapturePhotoOutput,
didFinishProcessingPhoto photo: AVCapturePhoto,
- error: Error?)
- {
+ error: Error?
+ ) {
guard !self.didResume else { return }
self.didResume = true
@@ -364,8 +360,8 @@ private final class PhotoCaptureDelegate: NSObject, AVCapturePhotoCaptureDelegat
func photoOutput(
_ output: AVCapturePhotoOutput,
didFinishCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings,
- error: Error?)
- {
+ error: Error?
+ ) {
guard let error else { return }
guard !self.didResume else { return }
self.didResume = true
diff --git a/apps/ios/Sources/Chat/IOSGatewayChatTransport.swift b/apps/ios/Sources/Chat/IOSGatewayChatTransport.swift
index 3c828551ada0b..9571839059d4f 100644
--- a/apps/ios/Sources/Chat/IOSGatewayChatTransport.swift
+++ b/apps/ios/Sources/Chat/IOSGatewayChatTransport.swift
@@ -2,8 +2,10 @@ import OpenClawChatUI
import OpenClawKit
import OpenClawProtocol
import Foundation
+import OSLog
struct IOSGatewayChatTransport: OpenClawChatTransport, Sendable {
+ private static let logger = Logger(subsystem: "ai.openclaw", category: "ios.chat.transport")
private let gateway: GatewayNodeSession
init(gateway: GatewayNodeSession) {
@@ -33,10 +35,8 @@ struct IOSGatewayChatTransport: OpenClawChatTransport, Sendable {
}
func setActiveSessionKey(_ sessionKey: String) async throws {
- struct Subscribe: Codable { var sessionKey: String }
- let data = try JSONEncoder().encode(Subscribe(sessionKey: sessionKey))
- let json = String(data: data, encoding: .utf8)
- await self.gateway.sendEvent(event: "chat.subscribe", payloadJSON: json)
+ // Operator clients receive chat events without node-style subscriptions.
+ // (chat.subscribe is a node event, not an operator RPC method.)
}
func requestHistory(sessionKey: String) async throws -> OpenClawChatHistoryPayload {
@@ -54,6 +54,7 @@ struct IOSGatewayChatTransport: OpenClawChatTransport, Sendable {
idempotencyKey: String,
attachments: [OpenClawChatAttachmentPayload]) async throws -> OpenClawChatSendResponse
{
+ Self.logger.info("chat.send start sessionKey=\(sessionKey, privacy: .public) len=\(message.count, privacy: .public) attachments=\(attachments.count, privacy: .public)")
struct Params: Codable {
var sessionKey: String
var message: String
@@ -72,8 +73,15 @@ struct IOSGatewayChatTransport: OpenClawChatTransport, Sendable {
idempotencyKey: idempotencyKey)
let data = try JSONEncoder().encode(params)
let json = String(data: data, encoding: .utf8)
- let res = try await self.gateway.request(method: "chat.send", paramsJSON: json, timeoutSeconds: 35)
- return try JSONDecoder().decode(OpenClawChatSendResponse.self, from: res)
+ do {
+ let res = try await self.gateway.request(method: "chat.send", paramsJSON: json, timeoutSeconds: 35)
+ let decoded = try JSONDecoder().decode(OpenClawChatSendResponse.self, from: res)
+ Self.logger.info("chat.send ok runId=\(decoded.runId, privacy: .public)")
+ return decoded
+ } catch {
+ Self.logger.error("chat.send failed \(error.localizedDescription, privacy: .public)")
+ throw error
+ }
}
func requestHealth(timeoutMs: Int) async throws -> Bool {
diff --git a/apps/ios/Sources/EventKit/EventKitAuthorization.swift b/apps/ios/Sources/EventKit/EventKitAuthorization.swift
new file mode 100644
index 0000000000000..c27e9a3efdef8
--- /dev/null
+++ b/apps/ios/Sources/EventKit/EventKitAuthorization.swift
@@ -0,0 +1,34 @@
+import EventKit
+
+enum EventKitAuthorization {
+ static func allowsRead(status: EKAuthorizationStatus) -> Bool {
+ switch status {
+ case .authorized, .fullAccess:
+ return true
+ case .writeOnly:
+ return false
+ case .notDetermined:
+ // Don’t prompt during node.invoke; prompts block the invoke and lead to timeouts.
+ return false
+ case .restricted, .denied:
+ return false
+ @unknown default:
+ return false
+ }
+ }
+
+ static func allowsWrite(status: EKAuthorizationStatus) -> Bool {
+ switch status {
+ case .authorized, .fullAccess, .writeOnly:
+ return true
+ case .notDetermined:
+ // Don’t prompt during node.invoke; prompts block the invoke and lead to timeouts.
+ return false
+ case .restricted, .denied:
+ return false
+ @unknown default:
+ return false
+ }
+ }
+}
+
diff --git a/apps/ios/Sources/Gateway/GatewayConnectionController.swift b/apps/ios/Sources/Gateway/GatewayConnectionController.swift
index 995e2f36d048e..92abd996b72c2 100644
--- a/apps/ios/Sources/Gateway/GatewayConnectionController.swift
+++ b/apps/ios/Sources/Gateway/GatewayConnectionController.swift
@@ -72,32 +72,55 @@ final class GatewayConnectionController {
}
}
- func connect(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) async {
+ func allowAutoConnectAgain() {
+ self.didAutoConnect = false
+ self.maybeAutoConnect()
+ }
+
+ func restartDiscovery() {
+ self.discovery.stop()
+ self.didAutoConnect = false
+ self.discovery.start()
+ self.updateFromDiscovery()
+ }
+
+
+ /// Returns `nil` when a connect attempt was started, otherwise returns a user-facing error.
+ func connectWithDiagnostics(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) async -> String? {
await self.connectDiscoveredGateway(gateway)
}
private func connectDiscoveredGateway(
- _ gateway: GatewayDiscoveryModel.DiscoveredGateway) async
+ _ gateway: GatewayDiscoveryModel.DiscoveredGateway) async -> String?
{
let instanceId = UserDefaults.standard.string(forKey: "node.instanceId")?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ if instanceId.isEmpty {
+ return "Missing instanceId (node.instanceId). Try restarting the app."
+ }
let token = GatewaySettingsStore.loadGatewayToken(instanceId: instanceId)
let password = GatewaySettingsStore.loadGatewayPassword(instanceId: instanceId)
// Resolve the service endpoint (SRV/A/AAAA). TXT is unauthenticated; do not route via TXT.
- guard let target = await self.resolveServiceEndpoint(gateway.endpoint) else { return }
+ guard let target = await self.resolveServiceEndpoint(gateway.endpoint) else {
+ return "Failed to resolve the discovered gateway endpoint."
+ }
let stableID = gateway.stableID
// Discovery is a LAN operation; refuse unauthenticated plaintext connects.
let tlsRequired = true
let stored = GatewayTLSStore.loadFingerprint(stableID: stableID)
- guard gateway.tlsEnabled || stored != nil else { return }
+ guard gateway.tlsEnabled || stored != nil else {
+ return "Discovered gateway is missing TLS and no trusted fingerprint is stored."
+ }
if tlsRequired, stored == nil {
guard let url = self.buildGatewayURL(host: target.host, port: target.port, useTLS: true)
- else { return }
- guard let fp = await self.probeTLSFingerprint(url: url) else { return }
+ else { return "Failed to build TLS URL for trust verification." }
+ guard let fp = await self.probeTLSFingerprint(url: url) else {
+ return "Failed to read TLS fingerprint from discovered gateway."
+ }
self.pendingTrustConnect = (url: url, stableID: stableID, isManual: false)
self.pendingTrustPrompt = TrustPrompt(
stableID: stableID,
@@ -107,7 +130,7 @@ final class GatewayConnectionController {
fingerprintSha256: fp,
isManual: false)
self.appModel?.gatewayStatusText = "Verify gateway TLS fingerprint"
- return
+ return nil
}
let tlsParams = stored.map { fp in
@@ -118,7 +141,7 @@ final class GatewayConnectionController {
host: target.host,
port: target.port,
useTLS: tlsParams?.required == true)
- else { return }
+ else { return "Failed to build discovered gateway URL." }
GatewaySettingsStore.saveLastGatewayConnectionDiscovered(stableID: stableID, useTLS: true)
self.didAutoConnect = true
self.startAutoConnect(
@@ -127,6 +150,11 @@ final class GatewayConnectionController {
tls: tlsParams,
token: token,
password: password)
+ return nil
+ }
+
+ func connect(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) async {
+ _ = await self.connectWithDiagnostics(gateway)
}
func connectManual(host: String, port: Int, useTLS: Bool) async {
@@ -490,6 +518,125 @@ final class GatewayConnectionController {
}
}
+ private func resolveHostPortFromBonjourEndpoint(_ endpoint: NWEndpoint) async -> (host: String, port: Int)? {
+ switch endpoint {
+ case let .hostPort(host, port):
+ return (host: host.debugDescription, port: Int(port.rawValue))
+ case let .service(name, type, domain, _):
+ return await Self.resolveBonjourServiceToHostPort(name: name, type: type, domain: domain)
+ default:
+ return nil
+ }
+ }
+
+ private static func resolveBonjourServiceToHostPort(
+ name: String,
+ type: String,
+ domain: String,
+ timeoutSeconds: TimeInterval = 3.0
+ ) async -> (host: String, port: Int)? {
+ // NetService callbacks are delivered via a run loop. If we resolve from a thread without one,
+ // we can end up never receiving callbacks, which in turn leaks the continuation and leaves
+ // the UI stuck "connecting". Keep the whole lifecycle on the main run loop and always
+ // resume the continuation exactly once (timeout/cancel safe).
+ @MainActor
+ final class Resolver: NSObject, @preconcurrency NetServiceDelegate {
+ private var cont: CheckedContinuation<(host: String, port: Int)?, Never>?
+ private let service: NetService
+ private var timeoutTask: Task?
+ private var finished = false
+
+ init(cont: CheckedContinuation<(host: String, port: Int)?, Never>, service: NetService) {
+ self.cont = cont
+ self.service = service
+ super.init()
+ }
+
+ func start(timeoutSeconds: TimeInterval) {
+ self.service.delegate = self
+ self.service.schedule(in: .main, forMode: .default)
+
+ // NetService has its own timeout, but we keep a manual one as a backstop in case
+ // callbacks never arrive (e.g. local network permission issues).
+ self.timeoutTask = Task { @MainActor [weak self] in
+ guard let self else { return }
+ let ns = UInt64(max(0.1, timeoutSeconds) * 1_000_000_000)
+ try? await Task.sleep(nanoseconds: ns)
+ self.finish(nil)
+ }
+
+ self.service.resolve(withTimeout: timeoutSeconds)
+ }
+
+ func netServiceDidResolveAddress(_ sender: NetService) {
+ self.finish(Self.extractHostPort(sender))
+ }
+
+ func netService(_ sender: NetService, didNotResolve errorDict: [String: NSNumber]) {
+ _ = errorDict // currently best-effort; callers surface a generic failure
+ self.finish(nil)
+ }
+
+ private func finish(_ result: (host: String, port: Int)?) {
+ guard !self.finished else { return }
+ self.finished = true
+
+ self.timeoutTask?.cancel()
+ self.timeoutTask = nil
+
+ self.service.stop()
+ self.service.remove(from: .main, forMode: .default)
+
+ let c = self.cont
+ self.cont = nil
+ c?.resume(returning: result)
+ }
+
+ private static func extractHostPort(_ svc: NetService) -> (host: String, port: Int)? {
+ let port = svc.port
+
+ if let host = svc.hostName?.trimmingCharacters(in: .whitespacesAndNewlines), !host.isEmpty {
+ return (host: host, port: port)
+ }
+
+ guard let addrs = svc.addresses else { return nil }
+ for addrData in addrs {
+ let host = addrData.withUnsafeBytes { ptr -> String? in
+ guard let base = ptr.baseAddress, !ptr.isEmpty else { return nil }
+ var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
+
+ let rc = getnameinfo(
+ base.assumingMemoryBound(to: sockaddr.self),
+ socklen_t(ptr.count),
+ &buffer,
+ socklen_t(buffer.count),
+ nil,
+ 0,
+ NI_NUMERICHOST)
+ guard rc == 0 else { return nil }
+ return String(cString: buffer)
+ }
+
+ if let host, !host.isEmpty {
+ return (host: host, port: port)
+ }
+ }
+
+ return nil
+ }
+ }
+
+ return await withCheckedContinuation { cont in
+ Task { @MainActor in
+ let service = NetService(domain: domain, type: type, name: name)
+ let resolver = Resolver(cont: cont, service: service)
+ // Keep the resolver alive for the lifetime of the NetService resolve.
+ objc_setAssociatedObject(service, "resolver", resolver, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ resolver.start(timeoutSeconds: timeoutSeconds)
+ }
+ }
+ }
+
private func buildGatewayURL(host: String, port: Int, useTLS: Bool) -> URL? {
let scheme = useTLS ? "wss" : "ws"
var components = URLComponents()
@@ -582,6 +729,9 @@ final class GatewayConnectionController {
if locationMode != .off { caps.append(OpenClawCapability.location.rawValue) }
caps.append(OpenClawCapability.device.rawValue)
+ if WatchMessagingService.isSupportedOnDevice() {
+ caps.append(OpenClawCapability.watch.rawValue)
+ }
caps.append(OpenClawCapability.photos.rawValue)
caps.append(OpenClawCapability.contacts.rawValue)
caps.append(OpenClawCapability.calendar.rawValue)
@@ -625,6 +775,10 @@ final class GatewayConnectionController {
commands.append(OpenClawDeviceCommand.status.rawValue)
commands.append(OpenClawDeviceCommand.info.rawValue)
}
+ if caps.contains(OpenClawCapability.watch.rawValue) {
+ commands.append(OpenClawWatchCommand.status.rawValue)
+ commands.append(OpenClawWatchCommand.notify.rawValue)
+ }
if caps.contains(OpenClawCapability.photos.rawValue) {
commands.append(OpenClawPhotosCommand.latest.rawValue)
}
@@ -675,6 +829,12 @@ final class GatewayConnectionController {
permissions["motion"] =
motionStatus == .authorized || pedometerStatus == .authorized
+ let watchStatus = WatchMessagingService.currentStatusSnapshot()
+ permissions["watchSupported"] = watchStatus.supported
+ permissions["watchPaired"] = watchStatus.paired
+ permissions["watchAppInstalled"] = watchStatus.appInstalled
+ permissions["watchReachable"] = watchStatus.reachable
+
return permissions
}
diff --git a/apps/ios/Sources/Gateway/GatewayConnectionIssue.swift b/apps/ios/Sources/Gateway/GatewayConnectionIssue.swift
new file mode 100644
index 0000000000000..56d490e226bab
--- /dev/null
+++ b/apps/ios/Sources/Gateway/GatewayConnectionIssue.swift
@@ -0,0 +1,71 @@
+import Foundation
+
+enum GatewayConnectionIssue: Equatable {
+ case none
+ case tokenMissing
+ case unauthorized
+ case pairingRequired(requestId: String?)
+ case network
+ case unknown(String)
+
+ var requestId: String? {
+ if case let .pairingRequired(requestId) = self {
+ return requestId
+ }
+ return nil
+ }
+
+ var needsAuthToken: Bool {
+ switch self {
+ case .tokenMissing, .unauthorized:
+ return true
+ default:
+ return false
+ }
+ }
+
+ var needsPairing: Bool {
+ if case .pairingRequired = self { return true }
+ return false
+ }
+
+ static func detect(from statusText: String) -> Self {
+ let trimmed = statusText.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return .none }
+ let lower = trimmed.lowercased()
+
+ if lower.contains("pairing required") || lower.contains("not_paired") || lower.contains("not paired") {
+ return .pairingRequired(requestId: self.extractRequestId(from: trimmed))
+ }
+ if lower.contains("gateway token missing") {
+ return .tokenMissing
+ }
+ if lower.contains("unauthorized") {
+ return .unauthorized
+ }
+ if lower.contains("connection refused") ||
+ lower.contains("timed out") ||
+ lower.contains("network is unreachable") ||
+ lower.contains("cannot find host") ||
+ lower.contains("could not connect")
+ {
+ return .network
+ }
+ if lower.hasPrefix("gateway error:") {
+ return .unknown(trimmed)
+ }
+ return .none
+ }
+
+ private static func extractRequestId(from statusText: String) -> String? {
+ let marker = "requestId:"
+ guard let range = statusText.range(of: marker) else { return nil }
+ let suffix = statusText[range.upperBound...]
+ let trimmed = suffix.trimmingCharacters(in: .whitespacesAndNewlines)
+ let end = trimmed.firstIndex(where: { ch in
+ ch == ")" || ch.isWhitespace || ch == "," || ch == ";"
+ }) ?? trimmed.endIndex
+ let id = String(trimmed[.. String {
diff --git a/apps/ios/Sources/Gateway/GatewayQuickSetupSheet.swift b/apps/ios/Sources/Gateway/GatewayQuickSetupSheet.swift
new file mode 100644
index 0000000000000..eac92df71e886
--- /dev/null
+++ b/apps/ios/Sources/Gateway/GatewayQuickSetupSheet.swift
@@ -0,0 +1,113 @@
+import SwiftUI
+
+struct GatewayQuickSetupSheet: View {
+ @Environment(NodeAppModel.self) private var appModel
+ @Environment(GatewayConnectionController.self) private var gatewayController
+ @Environment(\.dismiss) private var dismiss
+
+ @AppStorage("onboarding.quickSetupDismissed") private var quickSetupDismissed: Bool = false
+ @State private var connecting: Bool = false
+ @State private var connectError: String?
+
+ var body: some View {
+ NavigationStack {
+ VStack(alignment: .leading, spacing: 16) {
+ Text("Connect to a Gateway?")
+ .font(.title2.bold())
+
+ if let candidate = self.bestCandidate {
+ VStack(alignment: .leading, spacing: 6) {
+ Text(verbatim: candidate.name)
+ .font(.headline)
+ Text(verbatim: candidate.debugID)
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+
+ VStack(alignment: .leading, spacing: 2) {
+ // Use verbatim strings so Bonjour-provided values can't be interpreted as
+ // localized format strings (which can crash with Objective-C exceptions).
+ Text(verbatim: "Discovery: \(self.gatewayController.discoveryStatusText)")
+ Text(verbatim: "Status: \(self.appModel.gatewayStatusText)")
+ Text(verbatim: "Node: \(self.appModel.nodeStatusText)")
+ Text(verbatim: "Operator: \(self.appModel.operatorStatusText)")
+ }
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+ .padding(12)
+ .background(.thinMaterial)
+ .clipShape(RoundedRectangle(cornerRadius: 14))
+
+ Button {
+ self.connectError = nil
+ self.connecting = true
+ Task {
+ let err = await self.gatewayController.connectWithDiagnostics(candidate)
+ await MainActor.run {
+ self.connecting = false
+ self.connectError = err
+ // If we kicked off a connect, leave the sheet up so the user can see status evolve.
+ }
+ }
+ } label: {
+ Group {
+ if self.connecting {
+ HStack(spacing: 8) {
+ ProgressView().progressViewStyle(.circular)
+ Text("Connecting…")
+ }
+ } else {
+ Text("Connect")
+ }
+ }
+ .frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.borderedProminent)
+ .disabled(self.connecting)
+
+ if let connectError {
+ Text(connectError)
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ }
+
+ Button {
+ self.dismiss()
+ } label: {
+ Text("Not now")
+ .frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.bordered)
+ .disabled(self.connecting)
+
+ Toggle("Don’t show this again", isOn: self.$quickSetupDismissed)
+ .padding(.top, 4)
+ } else {
+ Text("No gateways found yet. Make sure your gateway is running and Bonjour discovery is enabled.")
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+ }
+ .padding()
+ .navigationTitle("Quick Setup")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button {
+ self.quickSetupDismissed = true
+ self.dismiss()
+ } label: {
+ Text("Close")
+ }
+ }
+ }
+ }
+ }
+
+ private var bestCandidate: GatewayDiscoveryModel.DiscoveredGateway? {
+ // Prefer whatever discovery says is first; the list is already name-sorted.
+ self.gatewayController.gateways.first
+ }
+}
diff --git a/apps/ios/Sources/Gateway/GatewaySettingsStore.swift b/apps/ios/Sources/Gateway/GatewaySettingsStore.swift
index 11fbbc5f0ca56..3ff57ad2e6746 100644
--- a/apps/ios/Sources/Gateway/GatewaySettingsStore.swift
+++ b/apps/ios/Sources/Gateway/GatewaySettingsStore.swift
@@ -4,6 +4,7 @@ import os
enum GatewaySettingsStore {
private static let gatewayService = "ai.openclaw.gateway"
private static let nodeService = "ai.openclaw.node"
+ private static let talkService = "ai.openclaw.talk"
private static let instanceIdDefaultsKey = "node.instanceId"
private static let preferredGatewayStableIDDefaultsKey = "gateway.preferredStableID"
@@ -24,6 +25,7 @@ enum GatewaySettingsStore {
private static let instanceIdAccount = "instanceId"
private static let preferredGatewayStableIDAccount = "preferredStableID"
private static let lastDiscoveredGatewayStableIDAccount = "lastDiscoveredStableID"
+ private static let talkElevenLabsApiKeyAccount = "elevenlabs.apiKey"
static func bootstrapPersistence() {
self.ensureStableInstanceID()
@@ -143,6 +145,27 @@ enum GatewaySettingsStore {
case discovered
}
+ static func loadTalkElevenLabsApiKey() -> String? {
+ let value = KeychainStore.loadString(
+ service: self.talkService,
+ account: self.talkElevenLabsApiKeyAccount)?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ if value?.isEmpty == false { return value }
+ return nil
+ }
+
+ static func saveTalkElevenLabsApiKey(_ apiKey: String?) {
+ let trimmed = apiKey?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ if trimmed.isEmpty {
+ _ = KeychainStore.delete(service: self.talkService, account: self.talkElevenLabsApiKeyAccount)
+ return
+ }
+ _ = KeychainStore.saveString(
+ trimmed,
+ service: self.talkService,
+ account: self.talkElevenLabsApiKeyAccount)
+ }
+
static func saveLastGatewayConnectionManual(host: String, port: Int, useTLS: Bool, stableID: String) {
let defaults = UserDefaults.standard
defaults.set(LastGatewayKind.manual.rawValue, forKey: self.lastGatewayKindDefaultsKey)
@@ -184,6 +207,25 @@ enum GatewaySettingsStore {
return .manual(host: host, port: port, useTLS: useTLS, stableID: stableID)
}
+ static func clearLastGatewayConnection(defaults: UserDefaults = .standard) {
+ defaults.removeObject(forKey: self.lastGatewayKindDefaultsKey)
+ defaults.removeObject(forKey: self.lastGatewayHostDefaultsKey)
+ defaults.removeObject(forKey: self.lastGatewayPortDefaultsKey)
+ defaults.removeObject(forKey: self.lastGatewayTlsDefaultsKey)
+ defaults.removeObject(forKey: self.lastGatewayStableIDDefaultsKey)
+ }
+
+ static func deleteGatewayCredentials(instanceId: String) {
+ let trimmed = instanceId.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+ _ = KeychainStore.delete(
+ service: self.gatewayService,
+ account: self.gatewayTokenAccount(instanceId: trimmed))
+ _ = KeychainStore.delete(
+ service: self.gatewayService,
+ account: self.gatewayPasswordAccount(instanceId: trimmed))
+ }
+
static func loadGatewayClientIdOverride(stableID: String) -> String? {
let trimmedID = stableID.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedID.isEmpty else { return nil }
diff --git a/apps/ios/Sources/Gateway/GatewaySetupCode.swift b/apps/ios/Sources/Gateway/GatewaySetupCode.swift
new file mode 100644
index 0000000000000..8ccbab42da73a
--- /dev/null
+++ b/apps/ios/Sources/Gateway/GatewaySetupCode.swift
@@ -0,0 +1,42 @@
+import Foundation
+
+struct GatewaySetupPayload: Codable {
+ var url: String?
+ var host: String?
+ var port: Int?
+ var tls: Bool?
+ var token: String?
+ var password: String?
+}
+
+enum GatewaySetupCode {
+ static func decode(raw: String) -> GatewaySetupPayload? {
+ if let payload = decodeFromJSON(raw) {
+ return payload
+ }
+ if let decoded = decodeBase64Payload(raw),
+ let payload = decodeFromJSON(decoded)
+ {
+ return payload
+ }
+ return nil
+ }
+
+ private static func decodeFromJSON(_ json: String) -> GatewaySetupPayload? {
+ guard let data = json.data(using: .utf8) else { return nil }
+ return try? JSONDecoder().decode(GatewaySetupPayload.self, from: data)
+ }
+
+ private static func decodeBase64Payload(_ raw: String) -> String? {
+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return nil }
+ let normalized = trimmed
+ .replacingOccurrences(of: "-", with: "+")
+ .replacingOccurrences(of: "_", with: "/")
+ let padding = normalized.count % 4
+ let padded = padding == 0 ? normalized : normalized + String(repeating: "=", count: 4 - padding)
+ guard let data = Data(base64Encoded: padded) else { return nil }
+ return String(data: data, encoding: .utf8)
+ }
+}
+
diff --git a/apps/ios/Sources/Gateway/GatewayTrustPromptAlert.swift b/apps/ios/Sources/Gateway/GatewayTrustPromptAlert.swift
index f117ad9ea46f0..eff6b71bad543 100644
--- a/apps/ios/Sources/Gateway/GatewayTrustPromptAlert.swift
+++ b/apps/ios/Sources/Gateway/GatewayTrustPromptAlert.swift
@@ -6,10 +6,10 @@ struct GatewayTrustPromptAlert: ViewModifier {
private var promptBinding: Binding {
Binding(
get: { self.gatewayController.pendingTrustPrompt },
- set: { newValue in
- if newValue == nil {
- self.gatewayController.clearPendingTrustPrompt()
- }
+ set: { _ in
+ // Keep pending trust state until explicit user action.
+ // `alert(item:)` may set the binding to nil during dismissal, which can race with
+ // the button handler and cause accept to no-op.
})
}
@@ -39,4 +39,3 @@ extension View {
self.modifier(GatewayTrustPromptAlert())
}
}
-
diff --git a/apps/ios/Sources/Gateway/TCPProbe.swift b/apps/ios/Sources/Gateway/TCPProbe.swift
new file mode 100644
index 0000000000000..e22da96298f86
--- /dev/null
+++ b/apps/ios/Sources/Gateway/TCPProbe.swift
@@ -0,0 +1,43 @@
+import Foundation
+import Network
+import os
+
+enum TCPProbe {
+ static func probe(host: String, port: Int, timeoutSeconds: Double, queueLabel: String) async -> Bool {
+ guard port >= 1, port <= 65535 else { return false }
+ guard let nwPort = NWEndpoint.Port(rawValue: UInt16(port)) else { return false }
+
+ let endpointHost = NWEndpoint.Host(host)
+ let connection = NWConnection(host: endpointHost, port: nwPort, using: .tcp)
+
+ return await withCheckedContinuation { cont in
+ let queue = DispatchQueue(label: queueLabel)
+ let finished = OSAllocatedUnfairLock(initialState: false)
+ let finish: @Sendable (Bool) -> Void = { ok in
+ let shouldResume = finished.withLock { flag -> Bool in
+ if flag { return false }
+ flag = true
+ return true
+ }
+ guard shouldResume else { return }
+ connection.cancel()
+ cont.resume(returning: ok)
+ }
+
+ connection.stateUpdateHandler = { state in
+ switch state {
+ case .ready:
+ finish(true)
+ case .failed, .cancelled:
+ finish(false)
+ default:
+ break
+ }
+ }
+
+ connection.start(queue: queue)
+ queue.asyncAfter(deadline: .now() + timeoutSeconds) { finish(false) }
+ }
+ }
+}
+
diff --git a/apps/ios/Sources/Info.plist b/apps/ios/Sources/Info.plist
index fe3c9ba4ed8ed..fe086049a8f3c 100644
--- a/apps/ios/Sources/Info.plist
+++ b/apps/ios/Sources/Info.plist
@@ -17,13 +17,24 @@
CFBundleName$(PRODUCT_NAME)CFBundlePackageType
- APPL
- CFBundleShortVersionString
- 2026.2.13
- CFBundleVersion
- 20260213
- NSAppTransportSecurity
+ APPL
+ CFBundleShortVersionString
+ 2026.2.19
+ CFBundleURLTypes
+
+ CFBundleURLName
+ ai.openclaw.ios
+ CFBundleURLSchemes
+
+ openclaw
+
+
+
+ CFBundleVersion
+ 20260219
+ NSAppTransportSecurity
+ NSAllowsArbitraryLoadsInWebContent
@@ -51,6 +62,7 @@
UIBackgroundModesaudio
+ remote-notificationUILaunchScreen
diff --git a/apps/ios/Sources/Location/LocationService.swift b/apps/ios/Sources/Location/LocationService.swift
index 99265d02e893f..f1f0f69ed7fa4 100644
--- a/apps/ios/Sources/Location/LocationService.swift
+++ b/apps/ios/Sources/Location/LocationService.swift
@@ -12,6 +12,10 @@ final class LocationService: NSObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
private var authContinuation: CheckedContinuation?
private var locationContinuation: CheckedContinuation?
+ private var updatesContinuation: AsyncStream.Continuation?
+ private var isStreaming = false
+ private var significantLocationCallback: (@Sendable (CLLocation) -> Void)?
+ private var isMonitoringSignificantChanges = false
override init() {
super.init()
@@ -104,6 +108,56 @@ final class LocationService: NSObject, CLLocationManagerDelegate {
}
}
+ func startLocationUpdates(
+ desiredAccuracy: OpenClawLocationAccuracy,
+ significantChangesOnly: Bool) -> AsyncStream
+ {
+ self.stopLocationUpdates()
+
+ self.manager.desiredAccuracy = Self.accuracyValue(desiredAccuracy)
+ self.manager.pausesLocationUpdatesAutomatically = true
+ self.manager.allowsBackgroundLocationUpdates = true
+
+ self.isStreaming = true
+ if significantChangesOnly {
+ self.manager.startMonitoringSignificantLocationChanges()
+ } else {
+ self.manager.startUpdatingLocation()
+ }
+
+ return AsyncStream(bufferingPolicy: .bufferingNewest(1)) { continuation in
+ self.updatesContinuation = continuation
+ continuation.onTermination = { @Sendable _ in
+ Task { @MainActor in
+ self.stopLocationUpdates()
+ }
+ }
+ }
+ }
+
+ func stopLocationUpdates() {
+ guard self.isStreaming else { return }
+ self.isStreaming = false
+ self.manager.stopUpdatingLocation()
+ self.manager.stopMonitoringSignificantLocationChanges()
+ self.updatesContinuation?.finish()
+ self.updatesContinuation = nil
+ }
+
+ func startMonitoringSignificantLocationChanges(onUpdate: @escaping @Sendable (CLLocation) -> Void) {
+ self.significantLocationCallback = onUpdate
+ guard !self.isMonitoringSignificantChanges else { return }
+ self.isMonitoringSignificantChanges = true
+ self.manager.startMonitoringSignificantLocationChanges()
+ }
+
+ func stopMonitoringSignificantLocationChanges() {
+ guard self.isMonitoringSignificantChanges else { return }
+ self.isMonitoringSignificantChanges = false
+ self.significantLocationCallback = nil
+ self.manager.stopMonitoringSignificantLocationChanges()
+ }
+
nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
let status = manager.authorizationStatus
Task { @MainActor in
@@ -117,12 +171,22 @@ final class LocationService: NSObject, CLLocationManagerDelegate {
nonisolated func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locs = locations
Task { @MainActor in
- guard let cont = self.locationContinuation else { return }
- self.locationContinuation = nil
- if let latest = locs.last {
- cont.resume(returning: latest)
- } else {
- cont.resume(throwing: Error.unavailable)
+ // Resolve the one-shot continuation first (if any).
+ if let cont = self.locationContinuation {
+ self.locationContinuation = nil
+ if let latest = locs.last {
+ cont.resume(returning: latest)
+ } else {
+ cont.resume(throwing: Error.unavailable)
+ }
+ // Don't return — also forward to significant-change callback below
+ // so both consumers receive updates when both are active.
+ }
+ if let callback = self.significantLocationCallback, let latest = locs.last {
+ callback(latest)
+ }
+ if let latest = locs.last, let updates = self.updatesContinuation {
+ updates.yield(latest)
}
}
}
diff --git a/apps/ios/Sources/Location/SignificantLocationMonitor.swift b/apps/ios/Sources/Location/SignificantLocationMonitor.swift
new file mode 100644
index 0000000000000..f12a157dc69b6
--- /dev/null
+++ b/apps/ios/Sources/Location/SignificantLocationMonitor.swift
@@ -0,0 +1,38 @@
+import CoreLocation
+import Foundation
+import OpenClawKit
+
+/// Monitors significant location changes and pushes `location.update`
+/// events to the gateway so the severance hook can determine whether
+/// the user is at their configured work location.
+@MainActor
+enum SignificantLocationMonitor {
+ static func startIfNeeded(
+ locationService: any LocationServicing,
+ locationMode: OpenClawLocationMode,
+ gateway: GatewayNodeSession
+ ) {
+ guard locationMode == .always else { return }
+ let status = locationService.authorizationStatus()
+ guard status == .authorizedAlways else { return }
+ locationService.startMonitoringSignificantLocationChanges { location in
+ struct Payload: Codable {
+ var lat: Double
+ var lon: Double
+ var accuracyMeters: Double
+ var source: String?
+ }
+ let payload = Payload(
+ lat: location.coordinate.latitude,
+ lon: location.coordinate.longitude,
+ accuracyMeters: location.horizontalAccuracy,
+ source: "ios-significant-location")
+ guard let data = try? JSONEncoder().encode(payload),
+ let json = String(data: data, encoding: .utf8)
+ else { return }
+ Task { @MainActor in
+ await gateway.sendEvent(event: "location.update", payloadJSON: json)
+ }
+ }
+ }
+}
diff --git a/apps/ios/Sources/Model/NodeAppModel+Canvas.swift b/apps/ios/Sources/Model/NodeAppModel+Canvas.swift
index 372f8361d3059..e8dce2cd30cf6 100644
--- a/apps/ios/Sources/Model/NodeAppModel+Canvas.swift
+++ b/apps/ios/Sources/Model/NodeAppModel+Canvas.swift
@@ -61,37 +61,10 @@ extension NodeAppModel {
private static func probeTCP(url: URL, timeoutSeconds: Double) async -> Bool {
guard let host = url.host, !host.isEmpty else { return false }
let portInt = url.port ?? ((url.scheme ?? "").lowercased() == "wss" ? 443 : 80)
- guard portInt >= 1, portInt <= 65535 else { return false }
- guard let nwPort = NWEndpoint.Port(rawValue: UInt16(portInt)) else { return false }
-
- let endpointHost = NWEndpoint.Host(host)
- let connection = NWConnection(host: endpointHost, port: nwPort, using: .tcp)
- return await withCheckedContinuation { cont in
- let queue = DispatchQueue(label: "a2ui.preflight")
- let finished = OSAllocatedUnfairLock(initialState: false)
- let finish: @Sendable (Bool) -> Void = { ok in
- let shouldResume = finished.withLock { flag -> Bool in
- if flag { return false }
- flag = true
- return true
- }
- guard shouldResume else { return }
- connection.cancel()
- cont.resume(returning: ok)
- }
-
- connection.stateUpdateHandler = { state in
- switch state {
- case .ready:
- finish(true)
- case .failed, .cancelled:
- finish(false)
- default:
- break
- }
- }
- connection.start(queue: queue)
- queue.asyncAfter(deadline: .now() + timeoutSeconds) { finish(false) }
- }
+ return await TCPProbe.probe(
+ host: host,
+ port: portInt,
+ timeoutSeconds: timeoutSeconds,
+ queueLabel: "a2ui.preflight")
}
}
diff --git a/apps/ios/Sources/Model/NodeAppModel.swift b/apps/ios/Sources/Model/NodeAppModel.swift
index 0ca521ccc60ea..1d09251dd76e5 100644
--- a/apps/ios/Sources/Model/NodeAppModel.swift
+++ b/apps/ios/Sources/Model/NodeAppModel.swift
@@ -2,6 +2,7 @@ import OpenClawChatUI
import OpenClawKit
import OpenClawProtocol
import Observation
+import os
import SwiftUI
import UIKit
import UserNotifications
@@ -10,7 +11,6 @@ import UserNotifications
private struct NotificationCallError: Error, Sendable {
let message: String
}
-
// Ensures notification requests return promptly even if the system prompt blocks.
private final class NotificationInvokeLatch: @unchecked Sendable {
private let lock = NSLock()
@@ -37,10 +37,11 @@ private final class NotificationInvokeLatch: @unchecked Sendable {
cont?.resume(returning: response)
}
}
-
@MainActor
@Observable
final class NodeAppModel {
+ private let deepLinkLogger = Logger(subsystem: "ai.openclaw.ios", category: "DeepLink")
+ private let pushWakeLogger = Logger(subsystem: "ai.openclaw.ios", category: "PushWake")
enum CameraHUDKind {
case photo
case recording
@@ -53,35 +54,24 @@ final class NodeAppModel {
private let camera: any CameraServicing
private let screenRecorder: any ScreenRecordingServicing
var gatewayStatusText: String = "Offline"
+ var nodeStatusText: String = "Offline"
+ var operatorStatusText: String = "Offline"
var gatewayServerName: String?
var gatewayRemoteAddress: String?
var connectedGatewayID: String?
var gatewayAutoReconnectEnabled: Bool = true
+ // When the gateway requires pairing approval, we pause reconnect churn and show a stable UX.
+ // Reconnect loops (both our own and the underlying WebSocket watchdog) can otherwise generate
+ // multiple pending requests and cause the onboarding UI to "flip-flop".
+ var gatewayPairingPaused: Bool = false
+ var gatewayPairingRequestId: String?
var seamColorHex: String?
private var mainSessionBaseKey: String = "main"
var selectedAgentId: String?
var gatewayDefaultAgentId: String?
var gatewayAgents: [AgentSummary] = []
-
- var mainSessionKey: String {
- let base = SessionKey.normalizeMainKey(self.mainSessionBaseKey)
- let agentId = (self.selectedAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
- let defaultId = (self.gatewayDefaultAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
- if agentId.isEmpty || (!defaultId.isEmpty && agentId == defaultId) { return base }
- return SessionKey.makeAgentSessionKey(agentId: agentId, baseKey: base)
- }
-
- var activeAgentName: String {
- let agentId = (self.selectedAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
- let defaultId = (self.gatewayDefaultAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
- let resolvedId = agentId.isEmpty ? defaultId : agentId
- if resolvedId.isEmpty { return "Main" }
- if let match = self.gatewayAgents.first(where: { $0.id == resolvedId }) {
- let name = (match.name ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
- return name.isEmpty ? match.id : name
- }
- return resolvedId
- }
+ var lastShareEventText: String = "No share events yet."
+ var openChatRequestID: Int = 0
// Primary "node" connection: used for device capabilities and node.invoke requests.
private let nodeGateway = GatewayNodeSession()
@@ -104,16 +94,22 @@ final class NodeAppModel {
private let calendarService: any CalendarServicing
private let remindersService: any RemindersServicing
private let motionService: any MotionServicing
+ private let watchMessagingService: any WatchMessagingServicing
var lastAutoA2uiURL: String?
private var pttVoiceWakeSuspended = false
private var talkVoiceWakeSuspended = false
private var backgroundVoiceWakeSuspended = false
private var backgroundTalkSuspended = false
+ private var backgroundTalkKeptActive = false
private var backgroundedAt: Date?
private var reconnectAfterBackgroundArmed = false
private var gatewayConnected = false
private var operatorConnected = false
+ private var shareDeliveryChannel: String?
+ private var shareDeliveryTo: String?
+ private var apnsDeviceTokenHex: String?
+ private var apnsLastRegisteredTokenHex: String?
var gatewaySession: GatewayNodeSession { self.nodeGateway }
var operatorSession: GatewayNodeSession { self.operatorGateway }
private(set) var activeGatewayConnectConfig: GatewayConnectConfig?
@@ -135,6 +131,7 @@ final class NodeAppModel {
calendarService: any CalendarServicing = CalendarService(),
remindersService: any RemindersServicing = RemindersService(),
motionService: any MotionServicing = MotionService(),
+ watchMessagingService: any WatchMessagingServicing = WatchMessagingService(),
talkMode: TalkModeManager = TalkModeManager())
{
self.screen = screen
@@ -148,7 +145,9 @@ final class NodeAppModel {
self.calendarService = calendarService
self.remindersService = remindersService
self.motionService = motionService
+ self.watchMessagingService = watchMessagingService
self.talkMode = talkMode
+ self.apnsDeviceTokenHex = UserDefaults.standard.string(forKey: Self.apnsDeviceTokenUserDefaultsKey)
GatewayDiagnostics.bootstrap()
self.voiceWake.configure { [weak self] cmd in
@@ -164,6 +163,7 @@ final class NodeAppModel {
let enabled = UserDefaults.standard.bool(forKey: "voiceWake.enabled")
self.voiceWake.setEnabled(enabled)
self.talkMode.attachGateway(self.operatorGateway)
+ self.refreshLastShareEventFromRelay()
let talkEnabled = UserDefaults.standard.bool(forKey: "talk.enabled")
// Route through the coordinator so VoiceWake and Talk don't fight over the microphone.
self.setTalkEnabled(talkEnabled)
@@ -264,15 +264,18 @@ final class NodeAppModel {
func setScenePhase(_ phase: ScenePhase) {
+ let keepTalkActive = UserDefaults.standard.bool(forKey: "talk.background.enabled")
switch phase {
case .background:
self.isBackgrounded = true
self.stopGatewayHealthMonitor()
self.backgroundedAt = Date()
self.reconnectAfterBackgroundArmed = true
- // Be conservative: release the mic when the app backgrounds.
+ // Release voice wake mic in background.
self.backgroundVoiceWakeSuspended = self.voiceWake.suspendForExternalAudioCapture()
- self.backgroundTalkSuspended = self.talkMode.suspendForBackground()
+ let shouldKeepTalkActive = keepTalkActive && self.talkMode.isEnabled
+ self.backgroundTalkKeptActive = shouldKeepTalkActive
+ self.backgroundTalkSuspended = self.talkMode.suspendForBackground(keepActive: shouldKeepTalkActive)
case .active, .inactive:
self.isBackgrounded = false
if self.operatorConnected {
@@ -284,8 +287,12 @@ final class NodeAppModel {
Task { [weak self] in
guard let self else { return }
let suspended = await MainActor.run { self.backgroundTalkSuspended }
- await MainActor.run { self.backgroundTalkSuspended = false }
- await self.talkMode.resumeAfterBackground(wasSuspended: suspended)
+ let keptActive = await MainActor.run { self.backgroundTalkKeptActive }
+ await MainActor.run {
+ self.backgroundTalkSuspended = false
+ self.backgroundTalkKeptActive = false
+ }
+ await self.talkMode.resumeAfterBackground(wasSuspended: suspended, wasKeptActive: keptActive)
}
}
if phase == .active, self.reconnectAfterBackgroundArmed {
@@ -340,6 +347,7 @@ final class NodeAppModel {
}
func setTalkEnabled(_ enabled: Bool) {
+ UserDefaults.standard.set(enabled, forKey: "talk.enabled")
if enabled {
// Voice wake holds the microphone continuously; talk mode needs exclusive access for STT.
// When talk is enabled from the UI, prioritize talk and pause voice wake.
@@ -351,6 +359,11 @@ final class NodeAppModel {
self.talkVoiceWakeSuspended = false
}
self.talkMode.setEnabled(enabled)
+ Task { [weak self] in
+ await self?.pushTalkModeToGateway(
+ enabled: enabled,
+ phase: enabled ? "enabled" : "disabled")
+ }
}
func requestLocationPermissions(mode: OpenClawLocationMode) async -> Bool {
@@ -380,6 +393,14 @@ final class NodeAppModel {
}
private static let defaultSeamColor = Color(red: 79 / 255.0, green: 122 / 255.0, blue: 154 / 255.0)
+ private static let apnsDeviceTokenUserDefaultsKey = "push.apns.deviceTokenHex"
+ private static var apnsEnvironment: String {
+#if DEBUG
+ "sandbox"
+#else
+ "production"
+#endif
+ }
private static func color(fromHex raw: String?) -> Color? {
let trimmed = (raw ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
@@ -447,6 +468,16 @@ final class NodeAppModel {
GatewaySettingsStore.saveGatewaySelectedAgentId(stableID: stableID, agentId: self.selectedAgentId)
}
self.talkMode.updateMainSessionKey(self.mainSessionKey)
+ if let relay = ShareGatewayRelaySettings.loadConfig() {
+ ShareGatewayRelaySettings.saveConfig(
+ ShareGatewayRelayConfig(
+ gatewayURLString: relay.gatewayURLString,
+ token: relay.token,
+ password: relay.password,
+ sessionKey: self.mainSessionKey,
+ deliveryChannel: self.shareDeliveryChannel,
+ deliveryTo: self.shareDeliveryTo))
+ }
}
func setGlobalWakeWords(_ words: [String]) async {
@@ -479,16 +510,49 @@ final class NodeAppModel {
let stream = await self.operatorGateway.subscribeServerEvents(bufferingNewest: 200)
for await evt in stream {
if Task.isCancelled { return }
- guard evt.event == "voicewake.changed" else { continue }
guard let payload = evt.payload else { continue }
- struct Payload: Decodable { var triggers: [String] }
- guard let decoded = try? GatewayPayloadDecoding.decode(payload, as: Payload.self) else { continue }
- let triggers = VoiceWakePreferences.sanitizeTriggerWords(decoded.triggers)
- VoiceWakePreferences.saveTriggerWords(triggers)
+ switch evt.event {
+ case "voicewake.changed":
+ struct Payload: Decodable { var triggers: [String] }
+ guard let decoded = try? GatewayPayloadDecoding.decode(payload, as: Payload.self) else { continue }
+ let triggers = VoiceWakePreferences.sanitizeTriggerWords(decoded.triggers)
+ VoiceWakePreferences.saveTriggerWords(triggers)
+ case "talk.mode":
+ struct Payload: Decodable {
+ var enabled: Bool
+ var phase: String?
+ }
+ guard let decoded = try? GatewayPayloadDecoding.decode(payload, as: Payload.self) else { continue }
+ self.applyTalkModeSync(enabled: decoded.enabled, phase: decoded.phase)
+ default:
+ continue
+ }
}
}
}
+ private func applyTalkModeSync(enabled: Bool, phase: String?) {
+ _ = phase
+ guard self.talkMode.isEnabled != enabled else { return }
+ self.setTalkEnabled(enabled)
+ }
+
+ private func pushTalkModeToGateway(enabled: Bool, phase: String?) async {
+ guard await self.isOperatorConnected() else { return }
+ struct TalkModePayload: Encodable {
+ var enabled: Bool
+ var phase: String?
+ }
+ let payload = TalkModePayload(enabled: enabled, phase: phase)
+ guard let data = try? JSONEncoder().encode(payload),
+ let json = String(data: data, encoding: .utf8)
+ else { return }
+ _ = try? await self.operatorGateway.request(
+ method: "talk.mode",
+ paramsJSON: json,
+ timeoutSeconds: 8)
+ }
+
private func startGatewayHealthMonitor() {
self.gatewayHealthMonitorDisabled = false
self.gatewayHealthMonitor.start(
@@ -515,8 +579,11 @@ final class NodeAppModel {
onFailure: { [weak self] _ in
guard let self else { return }
await self.operatorGateway.disconnect()
+ await self.nodeGateway.disconnect()
await MainActor.run {
self.operatorConnected = false
+ self.gatewayConnected = false
+ self.gatewayStatusText = "Reconnecting…"
self.talkMode.updateGatewayConnected(false)
}
})
@@ -577,28 +644,41 @@ final class NodeAppModel {
switch route {
case let .agent(link):
await self.handleAgentDeepLink(link, originalURL: url)
+ case .gateway:
+ break
}
}
private func handleAgentDeepLink(_ link: AgentDeepLink, originalURL: URL) async {
let message = link.message.trimmingCharacters(in: .whitespacesAndNewlines)
guard !message.isEmpty else { return }
+ self.deepLinkLogger.info(
+ "agent deep link received messageChars=\(message.count) url=\(originalURL.absoluteString, privacy: .public)"
+ )
if message.count > 20000 {
self.screen.errorText = "Deep link too large (message exceeds 20,000 characters)."
+ self.recordShareEvent("Rejected: message too large (\(message.count) chars).")
return
}
guard await self.isGatewayConnected() else {
self.screen.errorText = "Gateway not connected (cannot forward deep link)."
+ self.recordShareEvent("Failed: gateway not connected.")
+ self.deepLinkLogger.error("agent deep link rejected: gateway not connected")
return
}
do {
try await self.sendAgentRequest(link: link)
self.screen.errorText = nil
+ self.recordShareEvent("Sent to gateway (\(message.count) chars).")
+ self.deepLinkLogger.info("agent deep link forwarded to gateway")
+ self.openChatRequestID &+= 1
} catch {
self.screen.errorText = "Agent request failed: \(error.localizedDescription)"
+ self.recordShareEvent("Failed: \(error.localizedDescription)")
+ self.deepLinkLogger.error("agent deep link send failed: \(error.localizedDescription, privacy: .public)")
}
}
@@ -1345,6 +1425,14 @@ private extension NodeAppModel {
return try await self.handleDeviceInvoke(req)
}
+ register([
+ OpenClawWatchCommand.status.rawValue,
+ OpenClawWatchCommand.notify.rawValue,
+ ]) { [weak self] req in
+ guard let self else { throw NodeCapabilityRouter.RouterError.handlerUnavailable }
+ return try await self.handleWatchInvoke(req)
+ }
+
register([OpenClawPhotosCommand.latest.rawValue]) { [weak self] req in
guard let self else { throw NodeCapabilityRouter.RouterError.handlerUnavailable }
return try await self.handlePhotosInvoke(req)
@@ -1395,14 +1483,67 @@ private extension NodeAppModel {
return NodeCapabilityRouter(handlers: handlers)
}
+ func handleWatchInvoke(_ req: BridgeInvokeRequest) async throws -> BridgeInvokeResponse {
+ switch req.command {
+ case OpenClawWatchCommand.status.rawValue:
+ let status = await self.watchMessagingService.status()
+ let payload = OpenClawWatchStatusPayload(
+ supported: status.supported,
+ paired: status.paired,
+ appInstalled: status.appInstalled,
+ reachable: status.reachable,
+ activationState: status.activationState)
+ let json = try Self.encodePayload(payload)
+ return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: json)
+ case OpenClawWatchCommand.notify.rawValue:
+ let params = try Self.decodeParams(OpenClawWatchNotifyParams.self, from: req.paramsJSON)
+ let title = params.title.trimmingCharacters(in: .whitespacesAndNewlines)
+ let body = params.body.trimmingCharacters(in: .whitespacesAndNewlines)
+ if title.isEmpty && body.isEmpty {
+ return BridgeInvokeResponse(
+ id: req.id,
+ ok: false,
+ error: OpenClawNodeError(
+ code: .invalidRequest,
+ message: "INVALID_REQUEST: empty watch notification"))
+ }
+ do {
+ let result = try await self.watchMessagingService.sendNotification(
+ id: req.id,
+ title: title,
+ body: body,
+ priority: params.priority)
+ let payload = OpenClawWatchNotifyPayload(
+ deliveredImmediately: result.deliveredImmediately,
+ queuedForDelivery: result.queuedForDelivery,
+ transport: result.transport)
+ let json = try Self.encodePayload(payload)
+ return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: json)
+ } catch {
+ return BridgeInvokeResponse(
+ id: req.id,
+ ok: false,
+ error: OpenClawNodeError(
+ code: .unavailable,
+ message: error.localizedDescription))
+ }
+ default:
+ return BridgeInvokeResponse(
+ id: req.id,
+ ok: false,
+ error: OpenClawNodeError(code: .invalidRequest, message: "INVALID_REQUEST: unknown command"))
+ }
+ }
+
func locationMode() -> OpenClawLocationMode {
let raw = UserDefaults.standard.string(forKey: "location.enabledMode") ?? "off"
return OpenClawLocationMode(rawValue: raw) ?? .off
}
func isLocationPreciseEnabled() -> Bool {
- if UserDefaults.standard.object(forKey: "location.preciseEnabled") == nil { return true }
- return UserDefaults.standard.bool(forKey: "location.preciseEnabled")
+ // iOS settings now expose a single location mode control.
+ // Default location tool precision stays high unless a command explicitly requests balanced.
+ true
}
static func decodeParams(_ type: T.Type, from json: String?) throws -> T {
@@ -1454,6 +1595,26 @@ private extension NodeAppModel {
}
extension NodeAppModel {
+ var mainSessionKey: String {
+ let base = SessionKey.normalizeMainKey(self.mainSessionBaseKey)
+ let agentId = (self.selectedAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let defaultId = (self.gatewayDefaultAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ if agentId.isEmpty || (!defaultId.isEmpty && agentId == defaultId) { return base }
+ return SessionKey.makeAgentSessionKey(agentId: agentId, baseKey: base)
+ }
+
+ var activeAgentName: String {
+ let agentId = (self.selectedAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let defaultId = (self.gatewayDefaultAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let resolvedId = agentId.isEmpty ? defaultId : agentId
+ if resolvedId.isEmpty { return "Main" }
+ if let match = self.gatewayAgents.first(where: { $0.id == resolvedId }) {
+ let name = (match.name ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ return name.isEmpty ? match.id : name
+ }
+ return resolvedId
+ }
+
func connectToGateway(
url: URL,
gatewayStableID: String,
@@ -1506,6 +1667,8 @@ extension NodeAppModel {
func disconnectGateway() {
self.gatewayAutoReconnectEnabled = false
+ self.gatewayPairingPaused = false
+ self.gatewayPairingRequestId = nil
self.nodeGatewayTask?.cancel()
self.nodeGatewayTask = nil
self.operatorGatewayTask?.cancel()
@@ -1528,6 +1691,7 @@ extension NodeAppModel {
self.seamColorHex = nil
self.mainSessionBaseKey = "main"
self.talkMode.updateMainSessionKey(self.mainSessionKey)
+ ShareGatewayRelaySettings.clearConfig()
self.showLocalCanvasOnDisconnect()
}
}
@@ -1535,6 +1699,8 @@ extension NodeAppModel {
private extension NodeAppModel {
func prepareForGatewayConnect(url: URL, stableID: String) {
self.gatewayAutoReconnectEnabled = true
+ self.gatewayPairingPaused = false
+ self.gatewayPairingRequestId = nil
self.nodeGatewayTask?.cancel()
self.operatorGatewayTask?.cancel()
self.gatewayHealthMonitor.stop()
@@ -1548,6 +1714,7 @@ private extension NodeAppModel {
self.gatewayDefaultAgentId = nil
self.gatewayAgents = []
self.selectedAgentId = GatewaySettingsStore.loadGatewaySelectedAgentId(stableID: stableID)
+ self.apnsLastRegisteredTokenHex = nil
}
func startOperatorGatewayLoop(
@@ -1564,6 +1731,14 @@ private extension NodeAppModel {
guard let self else { return }
var attempt = 0
while !Task.isCancelled {
+ if self.gatewayPairingPaused {
+ try? await Task.sleep(nanoseconds: 1_000_000_000)
+ continue
+ }
+ if !self.gatewayAutoReconnectEnabled {
+ try? await Task.sleep(nanoseconds: 1_000_000_000)
+ continue
+ }
if await self.isOperatorConnected() {
try? await Task.sleep(nanoseconds: 1_000_000_000)
continue
@@ -1592,6 +1767,7 @@ private extension NodeAppModel {
"operator gateway connected host=\(url.host ?? "?") scheme=\(url.scheme ?? "?")")
await self.refreshBrandingFromGateway()
await self.refreshAgentsFromGateway()
+ await self.refreshShareRouteFromGateway()
await self.startVoiceWakeSync()
await MainActor.run { self.startGatewayHealthMonitor() }
},
@@ -1639,8 +1815,17 @@ private extension NodeAppModel {
var attempt = 0
var currentOptions = nodeOptions
var didFallbackClientId = false
+ var pausedForPairingApproval = false
while !Task.isCancelled {
+ if self.gatewayPairingPaused {
+ try? await Task.sleep(nanoseconds: 1_000_000_000)
+ continue
+ }
+ if !self.gatewayAutoReconnectEnabled {
+ try? await Task.sleep(nanoseconds: 1_000_000_000)
+ continue
+ }
if await self.isGatewayConnected() {
try? await Task.sleep(nanoseconds: 1_000_000_000)
continue
@@ -1669,12 +1854,28 @@ private extension NodeAppModel {
self.screen.errorText = nil
UserDefaults.standard.set(true, forKey: "gateway.autoconnect")
}
- GatewayDiagnostics.log(
- "gateway connected host=\(url.host ?? "?") scheme=\(url.scheme ?? "?")")
+ let relayData = await MainActor.run {
+ (
+ sessionKey: self.mainSessionKey,
+ deliveryChannel: self.shareDeliveryChannel,
+ deliveryTo: self.shareDeliveryTo
+ )
+ }
+ ShareGatewayRelaySettings.saveConfig(
+ ShareGatewayRelayConfig(
+ gatewayURLString: url.absoluteString,
+ token: token,
+ password: password,
+ sessionKey: relayData.sessionKey,
+ deliveryChannel: relayData.deliveryChannel,
+ deliveryTo: relayData.deliveryTo))
+ GatewayDiagnostics.log("gateway connected host=\(url.host ?? "?") scheme=\(url.scheme ?? "?")")
if let addr = await self.nodeGateway.currentRemoteAddress() {
await MainActor.run { self.gatewayRemoteAddress = addr }
}
await self.showA2UIOnConnectIfNeeded()
+ await self.onNodeGatewayConnected()
+ await MainActor.run { SignificantLocationMonitor.startIfNeeded(locationService: self.locationService, locationMode: self.locationMode(), gateway: self.nodeGateway) }
},
onDisconnected: { [weak self] reason in
guard let self else { return }
@@ -1726,11 +1927,60 @@ private extension NodeAppModel {
self.showLocalCanvasOnDisconnect()
}
GatewayDiagnostics.log("gateway connect error: \(error.localizedDescription)")
+
+ // If auth is missing/rejected, pause reconnect churn until the user intervenes.
+ // Reconnect loops only spam the same failing handshake and make onboarding noisy.
+ let lower = error.localizedDescription.lowercased()
+ if lower.contains("unauthorized") || lower.contains("gateway token missing") {
+ await MainActor.run {
+ self.gatewayAutoReconnectEnabled = false
+ }
+ }
+
+ // If pairing is required, stop reconnect churn. The user must approve the request
+ // on the gateway before another connect attempt will succeed, and retry loops can
+ // generate multiple pending requests.
+ if lower.contains("not_paired") || lower.contains("pairing required") {
+ let requestId: String? = {
+ // GatewayResponseError for connect decorates the message with `(requestId: ...)`.
+ // Keep this resilient since other layers may wrap the text.
+ let text = error.localizedDescription
+ guard let start = text.range(of: "(requestId: ")?.upperBound else { return nil }
+ guard let end = text[start...].firstIndex(of: ")") else { return nil }
+ let raw = String(text[start.. String? = { raw in
+ let value = (raw ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ return value.isEmpty ? nil : value
+ }
+
+ do {
+ let data = try JSONEncoder().encode(
+ Params(includeGlobal: true, includeUnknown: false, limit: 80))
+ guard let json = String(data: data, encoding: .utf8) else { return }
+ let response = try await self.operatorGateway.request(
+ method: "sessions.list",
+ paramsJSON: json,
+ timeoutSeconds: 10)
+ let decoded = try JSONDecoder().decode(SessionsListResult.self, from: response)
+ let currentKey = self.mainSessionKey
+ let sorted = decoded.sessions.sorted { ($0.updatedAt ?? 0) > ($1.updatedAt ?? 0) }
+ let exactMatch = sorted.first { row in
+ row.key == currentKey && normalize(row.lastChannel) != nil && normalize(row.lastTo) != nil
+ }
+ let selected = exactMatch
+ let channel = normalize(selected?.lastChannel)
+ let to = normalize(selected?.lastTo)
+
+ await MainActor.run {
+ self.shareDeliveryChannel = channel
+ self.shareDeliveryTo = to
+ if let relay = ShareGatewayRelaySettings.loadConfig() {
+ ShareGatewayRelaySettings.saveConfig(
+ ShareGatewayRelayConfig(
+ gatewayURLString: relay.gatewayURLString,
+ token: relay.token,
+ password: relay.password,
+ sessionKey: self.mainSessionKey,
+ deliveryChannel: channel,
+ deliveryTo: to))
+ }
+ }
+ } catch {
+ // Best-effort only.
+ }
+ }
+
+ func runSharePipelineSelfTest() async {
+ self.recordShareEvent("Share self-test running…")
+
+ let payload = SharedContentPayload(
+ title: "OpenClaw Share Self-Test",
+ url: URL(string: "https://openclaw.ai/share-self-test"),
+ text: "Validate iOS share->deep-link->gateway forwarding.")
+ guard let deepLink = ShareToAgentDeepLink.buildURL(
+ from: payload,
+ instruction: "Reply with: SHARE SELF-TEST OK")
+ else {
+ self.recordShareEvent("Self-test failed: could not build deep link.")
+ return
+ }
+
+ await self.handleDeepLink(url: deepLink)
+ }
+
+ func refreshLastShareEventFromRelay() {
+ if let event = ShareGatewayRelaySettings.loadLastEvent() {
+ self.lastShareEventText = event
+ }
+ }
+
+ func recordShareEvent(_ text: String) {
+ ShareGatewayRelaySettings.saveLastEvent(text)
+ self.refreshLastShareEventFromRelay()
+ }
+
+ func reloadTalkConfig() {
+ Task { [weak self] in
+ await self?.talkMode.reloadConfig()
+ }
+ }
+
+ /// Back-compat hook retained for older gateway-connect flows.
+ func onNodeGatewayConnected() async {
+ await self.registerAPNsTokenIfNeeded()
+ }
+
+ func handleSilentPushWake(_ userInfo: [AnyHashable: Any]) async -> Bool {
+ guard Self.isSilentPushPayload(userInfo) else {
+ self.pushWakeLogger.info("Ignored APNs payload: not silent push")
+ return false
+ }
+ self.pushWakeLogger.info("Silent push received; attempting reconnect if needed")
+ return await self.reconnectGatewaySessionsForSilentPushIfNeeded()
+ }
+
+ func updateAPNsDeviceToken(_ tokenData: Data) {
+ let tokenHex = tokenData.map { String(format: "%02x", $0) }.joined()
+ let trimmed = tokenHex.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+ self.apnsDeviceTokenHex = trimmed
+ UserDefaults.standard.set(trimmed, forKey: Self.apnsDeviceTokenUserDefaultsKey)
+ Task { [weak self] in
+ await self?.registerAPNsTokenIfNeeded()
+ }
+ }
+
+ private func registerAPNsTokenIfNeeded() async {
+ guard self.gatewayConnected else { return }
+ guard let token = self.apnsDeviceTokenHex?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !token.isEmpty
+ else {
+ return
+ }
+ if token == self.apnsLastRegisteredTokenHex {
+ return
+ }
+ guard let topic = Bundle.main.bundleIdentifier?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !topic.isEmpty
+ else {
+ return
+ }
+
+ struct PushRegistrationPayload: Codable {
+ var token: String
+ var topic: String
+ var environment: String
+ }
+
+ let payload = PushRegistrationPayload(
+ token: token,
+ topic: topic,
+ environment: Self.apnsEnvironment)
+ do {
+ let json = try Self.encodePayload(payload)
+ await self.nodeGateway.sendEvent(event: "push.apns.register", payloadJSON: json)
+ self.apnsLastRegisteredTokenHex = token
+ } catch {
+ // Best-effort only.
+ }
+ }
+
+ private static func isSilentPushPayload(_ userInfo: [AnyHashable: Any]) -> Bool {
+ guard let apsAny = userInfo["aps"] else { return false }
+ if let aps = apsAny as? [AnyHashable: Any] {
+ return Self.hasContentAvailable(aps["content-available"])
+ }
+ if let aps = apsAny as? [String: Any] {
+ return Self.hasContentAvailable(aps["content-available"])
+ }
+ return false
+ }
+
+ private static func hasContentAvailable(_ value: Any?) -> Bool {
+ if let number = value as? NSNumber {
+ return number.intValue == 1
+ }
+ if let text = value as? String {
+ return text.trimmingCharacters(in: .whitespacesAndNewlines) == "1"
+ }
+ return false
+ }
+
+ private func reconnectGatewaySessionsForSilentPushIfNeeded() async -> Bool {
+ guard self.isBackgrounded else {
+ self.pushWakeLogger.info("Wake no-op: app not backgrounded")
+ return false
+ }
+ guard self.gatewayAutoReconnectEnabled else {
+ self.pushWakeLogger.info("Wake no-op: auto reconnect disabled")
+ return false
+ }
+ guard self.activeGatewayConnectConfig != nil else {
+ self.pushWakeLogger.info("Wake no-op: no active gateway config")
+ return false
+ }
+
+ await self.operatorGateway.disconnect()
+ await self.nodeGateway.disconnect()
+ self.operatorConnected = false
+ self.gatewayConnected = false
+ self.gatewayStatusText = "Reconnecting…"
+ self.talkMode.updateGatewayConnected(false)
+ self.pushWakeLogger.info("Wake reconnect trigger applied")
+ return true
+ }
+}
+
#if DEBUG
extension NodeAppModel {
func _test_handleInvoke(_ req: BridgeInvokeRequest) async -> BridgeInvokeResponse {
@@ -1808,5 +2260,9 @@ extension NodeAppModel {
func _test_showLocalCanvasOnDisconnect() {
self.showLocalCanvasOnDisconnect()
}
+
+ func _test_applyTalkModeSync(enabled: Bool, phase: String? = nil) {
+ self.applyTalkModeSync(enabled: enabled, phase: phase)
+ }
}
#endif
diff --git a/apps/ios/Sources/Onboarding/GatewayOnboardingView.swift b/apps/ios/Sources/Onboarding/GatewayOnboardingView.swift
index 09c9e2429a694..bf6c0ba2d1874 100644
--- a/apps/ios/Sources/Onboarding/GatewayOnboardingView.swift
+++ b/apps/ios/Sources/Onboarding/GatewayOnboardingView.swift
@@ -257,15 +257,6 @@ private struct ManualEntryStep: View {
self.manualPassword = ""
}
- private struct SetupPayload: Codable {
- var url: String?
- var host: String?
- var port: Int?
- var tls: Bool?
- var token: String?
- var password: String?
- }
-
private func applySetupCode() {
let raw = self.setupCode.trimmingCharacters(in: .whitespacesAndNewlines)
guard !raw.isEmpty else {
@@ -273,7 +264,7 @@ private struct ManualEntryStep: View {
return
}
- guard let payload = self.decodeSetupPayload(raw: raw) else {
+ guard let payload = GatewaySetupCode.decode(raw: raw) else {
self.setupStatusText = "Setup code not recognized."
return
}
@@ -323,34 +314,7 @@ private struct ManualEntryStep: View {
}
}
- private func decodeSetupPayload(raw: String) -> SetupPayload? {
- if let payload = decodeSetupPayloadFromJSON(raw) {
- return payload
- }
- if let decoded = decodeBase64Payload(raw),
- let payload = decodeSetupPayloadFromJSON(decoded)
- {
- return payload
- }
- return nil
- }
-
- private func decodeSetupPayloadFromJSON(_ json: String) -> SetupPayload? {
- guard let data = json.data(using: .utf8) else { return nil }
- return try? JSONDecoder().decode(SetupPayload.self, from: data)
- }
-
- private func decodeBase64Payload(_ raw: String) -> String? {
- let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else { return nil }
- let normalized = trimmed
- .replacingOccurrences(of: "-", with: "+")
- .replacingOccurrences(of: "_", with: "/")
- let padding = normalized.count % 4
- let padded = padding == 0 ? normalized : normalized + String(repeating: "=", count: 4 - padding)
- guard let data = Data(base64Encoded: padded) else { return nil }
- return String(data: data, encoding: .utf8)
- }
+ // (GatewaySetupCode) decode raw setup codes.
}
private struct ConnectionStatusBox: View {
diff --git a/apps/ios/Sources/Onboarding/OnboardingStateStore.swift b/apps/ios/Sources/Onboarding/OnboardingStateStore.swift
new file mode 100644
index 0000000000000..9822ac1706fc3
--- /dev/null
+++ b/apps/ios/Sources/Onboarding/OnboardingStateStore.swift
@@ -0,0 +1,52 @@
+import Foundation
+
+enum OnboardingConnectionMode: String, CaseIterable {
+ case homeNetwork = "home_network"
+ case remoteDomain = "remote_domain"
+ case developerLocal = "developer_local"
+
+ var title: String {
+ switch self {
+ case .homeNetwork:
+ "Home Network"
+ case .remoteDomain:
+ "Remote Domain"
+ case .developerLocal:
+ "Same Machine (Dev)"
+ }
+ }
+}
+
+enum OnboardingStateStore {
+ private static let completedDefaultsKey = "onboarding.completed"
+ private static let lastModeDefaultsKey = "onboarding.last_mode"
+ private static let lastSuccessTimeDefaultsKey = "onboarding.last_success_time"
+
+ @MainActor
+ static func shouldPresentOnLaunch(appModel: NodeAppModel, defaults: UserDefaults = .standard) -> Bool {
+ if defaults.bool(forKey: Self.completedDefaultsKey) { return false }
+ // If we have a last-known connection config, don't force onboarding on launch. Auto-connect
+ // should handle reconnecting, and users can always open onboarding manually if needed.
+ if GatewaySettingsStore.loadLastGatewayConnection() != nil { return false }
+ return appModel.gatewayServerName == nil
+ }
+
+ static func markCompleted(mode: OnboardingConnectionMode? = nil, defaults: UserDefaults = .standard) {
+ defaults.set(true, forKey: Self.completedDefaultsKey)
+ if let mode {
+ defaults.set(mode.rawValue, forKey: Self.lastModeDefaultsKey)
+ }
+ defaults.set(Int(Date().timeIntervalSince1970), forKey: Self.lastSuccessTimeDefaultsKey)
+ }
+
+ static func markIncomplete(defaults: UserDefaults = .standard) {
+ defaults.set(false, forKey: Self.completedDefaultsKey)
+ }
+
+ static func lastMode(defaults: UserDefaults = .standard) -> OnboardingConnectionMode? {
+ let raw = defaults.string(forKey: Self.lastModeDefaultsKey)?
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ guard !raw.isEmpty else { return nil }
+ return OnboardingConnectionMode(rawValue: raw)
+ }
+}
diff --git a/apps/ios/Sources/Onboarding/OnboardingWizardView.swift b/apps/ios/Sources/Onboarding/OnboardingWizardView.swift
new file mode 100644
index 0000000000000..c0e872b2ceb52
--- /dev/null
+++ b/apps/ios/Sources/Onboarding/OnboardingWizardView.swift
@@ -0,0 +1,890 @@
+import CoreImage
+import Combine
+import OpenClawKit
+import PhotosUI
+import SwiftUI
+import UIKit
+
+private enum OnboardingStep: Int, CaseIterable {
+ case welcome
+ case mode
+ case connect
+ case auth
+ case success
+
+ var previous: Self? {
+ Self(rawValue: self.rawValue - 1)
+ }
+
+ var next: Self? {
+ Self(rawValue: self.rawValue + 1)
+ }
+
+ /// Progress label for the manual setup flow (mode → connect → auth → success).
+ var manualProgressTitle: String {
+ let manualSteps: [OnboardingStep] = [.mode, .connect, .auth, .success]
+ guard let idx = manualSteps.firstIndex(of: self) else { return "" }
+ return "Step \(idx + 1) of \(manualSteps.count)"
+ }
+
+ var title: String {
+ switch self {
+ case .welcome: "Welcome"
+ case .mode: "Connection Mode"
+ case .connect: "Connect"
+ case .auth: "Authentication"
+ case .success: "Connected"
+ }
+ }
+
+ var canGoBack: Bool {
+ self != .welcome && self != .success
+ }
+}
+
+struct OnboardingWizardView: View {
+ @Environment(NodeAppModel.self) private var appModel: NodeAppModel
+ @Environment(GatewayConnectionController.self) private var gatewayController: GatewayConnectionController
+ @Environment(\.scenePhase) private var scenePhase
+ @AppStorage("node.instanceId") private var instanceId: String = UUID().uuidString
+ @AppStorage("gateway.discovery.domain") private var discoveryDomain: String = ""
+ @AppStorage("onboarding.developerMode") private var developerModeEnabled: Bool = false
+ @State private var step: OnboardingStep = .welcome
+ @State private var selectedMode: OnboardingConnectionMode?
+ @State private var manualHost: String = ""
+ @State private var manualPort: Int = 18789
+ @State private var manualPortText: String = "18789"
+ @State private var manualTLS: Bool = true
+ @State private var gatewayToken: String = ""
+ @State private var gatewayPassword: String = ""
+ @State private var connectMessage: String?
+ @State private var statusLine: String = "Scan the QR code from your gateway to connect."
+ @State private var connectingGatewayID: String?
+ @State private var issue: GatewayConnectionIssue = .none
+ @State private var didMarkCompleted = false
+ @State private var didAutoPresentQR = false
+ @State private var pairingRequestId: String?
+ @State private var discoveryRestartTask: Task?
+ @State private var showQRScanner: Bool = false
+ @State private var scannerError: String?
+ @State private var selectedPhoto: PhotosPickerItem?
+ @State private var lastPairingAutoResumeAttemptAt: Date?
+ private static let pairingAutoResumeTicker = Timer.publish(every: 2.0, on: .main, in: .common).autoconnect()
+
+ let allowSkip: Bool
+ let onClose: () -> Void
+
+ private var isFullScreenStep: Bool {
+ self.step == .welcome || self.step == .success
+ }
+
+ var body: some View {
+ NavigationStack {
+ Group {
+ switch self.step {
+ case .welcome:
+ self.welcomeStep
+ case .success:
+ self.successStep
+ default:
+ Form {
+ switch self.step {
+ case .mode:
+ self.modeStep
+ case .connect:
+ self.connectStep
+ case .auth:
+ self.authStep
+ default:
+ EmptyView()
+ }
+ }
+ .scrollDismissesKeyboard(.interactively)
+ }
+ }
+ .navigationTitle(self.isFullScreenStep ? "" : self.step.title)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ if !self.isFullScreenStep {
+ ToolbarItem(placement: .principal) {
+ VStack(spacing: 2) {
+ Text(self.step.title)
+ .font(.headline)
+ Text(self.step.manualProgressTitle)
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ ToolbarItem(placement: .topBarLeading) {
+ if self.step.canGoBack {
+ Button {
+ self.navigateBack()
+ } label: {
+ Label("Back", systemImage: "chevron.left")
+ }
+ } else if self.allowSkip {
+ Button("Close") {
+ self.onClose()
+ }
+ }
+ }
+ ToolbarItemGroup(placement: .keyboard) {
+ Spacer()
+ Button("Done") {
+ UIApplication.shared.sendAction(
+ #selector(UIResponder.resignFirstResponder),
+ to: nil, from: nil, for: nil)
+ }
+ }
+ }
+ }
+ .gatewayTrustPromptAlert()
+ .alert("QR Scanner Unavailable", isPresented: Binding(
+ get: { self.scannerError != nil },
+ set: { if !$0 { self.scannerError = nil } }
+ )) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(self.scannerError ?? "")
+ }
+ .sheet(isPresented: self.$showQRScanner) {
+ NavigationStack {
+ QRScannerView(
+ onGatewayLink: { link in
+ self.handleScannedLink(link)
+ },
+ onError: { error in
+ self.showQRScanner = false
+ self.statusLine = "Scanner error: \(error)"
+ self.scannerError = error
+ },
+ onDismiss: {
+ self.showQRScanner = false
+ })
+ .ignoresSafeArea()
+ .navigationTitle("Scan QR Code")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .topBarLeading) {
+ Button("Cancel") { self.showQRScanner = false }
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ PhotosPicker(selection: self.$selectedPhoto, matching: .images) {
+ Label("Photos", systemImage: "photo")
+ }
+ }
+ }
+ }
+ .onChange(of: self.selectedPhoto) { _, newValue in
+ guard let item = newValue else { return }
+ self.selectedPhoto = nil
+ Task {
+ guard let data = try? await item.loadTransferable(type: Data.self) else {
+ self.showQRScanner = false
+ self.scannerError = "Could not load the selected image."
+ return
+ }
+ if let message = self.detectQRCode(from: data) {
+ if let link = GatewayConnectDeepLink.fromSetupCode(message) {
+ self.handleScannedLink(link)
+ return
+ }
+ if let url = URL(string: message),
+ let route = DeepLinkParser.parse(url),
+ case let .gateway(link) = route
+ {
+ self.handleScannedLink(link)
+ return
+ }
+ }
+ self.showQRScanner = false
+ self.scannerError = "No valid QR code found in the selected image."
+ }
+ }
+ }
+ .onAppear {
+ self.initializeState()
+ }
+ .onDisappear {
+ self.discoveryRestartTask?.cancel()
+ self.discoveryRestartTask = nil
+ }
+ .onChange(of: self.discoveryDomain) { _, _ in
+ self.scheduleDiscoveryRestart()
+ }
+ .onChange(of: self.manualPortText) { _, newValue in
+ let digits = newValue.filter(\.isNumber)
+ if digits != newValue {
+ self.manualPortText = digits
+ return
+ }
+ guard let parsed = Int(digits), parsed > 0 else {
+ self.manualPort = 0
+ return
+ }
+ self.manualPort = min(parsed, 65535)
+ }
+ .onChange(of: self.manualPort) { _, newValue in
+ let normalized = newValue > 0 ? String(newValue) : ""
+ if self.manualPortText != normalized {
+ self.manualPortText = normalized
+ }
+ }
+ .onChange(of: self.gatewayToken) { _, newValue in
+ self.saveGatewayCredentials(token: newValue, password: self.gatewayPassword)
+ }
+ .onChange(of: self.gatewayPassword) { _, newValue in
+ self.saveGatewayCredentials(token: self.gatewayToken, password: newValue)
+ }
+ .onChange(of: self.appModel.gatewayStatusText) { _, newValue in
+ let next = GatewayConnectionIssue.detect(from: newValue)
+ // Avoid "flip-flopping" the UI by clearing actionable issues when the underlying connection
+ // transitions through intermediate statuses (e.g. Offline/Connecting while reconnect churns).
+ if self.issue.needsPairing, next.needsPairing {
+ // Keep the requestId sticky even if the status line omits it after we pause.
+ let mergedRequestId = next.requestId ?? self.issue.requestId ?? self.pairingRequestId
+ self.issue = .pairingRequired(requestId: mergedRequestId)
+ } else if self.issue.needsPairing, !next.needsPairing {
+ // Ignore non-pairing statuses until the user explicitly retries/scans again, or we connect.
+ } else if self.issue.needsAuthToken, !next.needsAuthToken, !next.needsPairing {
+ // Same idea for auth: once we learn credentials are missing/rejected, keep that sticky until
+ // the user retries/scans again or we successfully connect.
+ } else {
+ self.issue = next
+ }
+
+ if let requestId = next.requestId, !requestId.isEmpty {
+ self.pairingRequestId = requestId
+ }
+
+ // If the gateway tells us auth is missing/rejected, stop reconnect churn until the user intervenes.
+ if next.needsAuthToken {
+ self.appModel.gatewayAutoReconnectEnabled = false
+ }
+
+ if self.issue.needsAuthToken || self.issue.needsPairing {
+ self.step = .auth
+ }
+ if !newValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ self.connectMessage = newValue
+ self.statusLine = newValue
+ }
+ }
+ .onChange(of: self.appModel.gatewayServerName) { _, newValue in
+ guard newValue != nil else { return }
+ self.showQRScanner = false
+ self.statusLine = "Connected."
+ if !self.didMarkCompleted, let selectedMode {
+ OnboardingStateStore.markCompleted(mode: selectedMode)
+ self.didMarkCompleted = true
+ }
+ self.onClose()
+ }
+ .onChange(of: self.scenePhase) { _, newValue in
+ guard newValue == .active else { return }
+ self.attemptAutomaticPairingResumeIfNeeded()
+ }
+ .onReceive(Self.pairingAutoResumeTicker) { _ in
+ self.attemptAutomaticPairingResumeIfNeeded()
+ }
+ }
+
+ @ViewBuilder
+ private var welcomeStep: some View {
+ VStack(spacing: 0) {
+ Spacer()
+
+ Image(systemName: "qrcode.viewfinder")
+ .font(.system(size: 64))
+ .foregroundStyle(.tint)
+ .padding(.bottom, 20)
+
+ Text("Welcome")
+ .font(.largeTitle.weight(.bold))
+ .padding(.bottom, 8)
+
+ Text("Connect to your OpenClaw gateway")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 32)
+
+ Spacer()
+
+ VStack(spacing: 12) {
+ Button {
+ self.statusLine = "Opening QR scanner…"
+ self.showQRScanner = true
+ } label: {
+ Label("Scan QR Code", systemImage: "qrcode")
+ .frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.large)
+
+ Button {
+ self.step = .mode
+ } label: {
+ Text("Set Up Manually")
+ .frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.large)
+ }
+ .padding(.bottom, 12)
+
+ Text(self.statusLine)
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 24)
+ .padding(.horizontal, 24)
+ .padding(.bottom, 48)
+ }
+ }
+
+ @ViewBuilder
+ private var modeStep: some View {
+ Section("Connection Mode") {
+ OnboardingModeRow(
+ title: OnboardingConnectionMode.homeNetwork.title,
+ subtitle: "LAN or Tailscale host",
+ selected: self.selectedMode == .homeNetwork)
+ {
+ self.selectMode(.homeNetwork)
+ }
+
+ OnboardingModeRow(
+ title: OnboardingConnectionMode.remoteDomain.title,
+ subtitle: "VPS with domain",
+ selected: self.selectedMode == .remoteDomain)
+ {
+ self.selectMode(.remoteDomain)
+ }
+
+ Toggle(
+ "Developer mode",
+ isOn: Binding(
+ get: { self.developerModeEnabled },
+ set: { newValue in
+ self.developerModeEnabled = newValue
+ if !newValue, self.selectedMode == .developerLocal {
+ self.selectedMode = nil
+ }
+ }))
+
+ if self.developerModeEnabled {
+ OnboardingModeRow(
+ title: OnboardingConnectionMode.developerLocal.title,
+ subtitle: "For local iOS app development",
+ selected: self.selectedMode == .developerLocal)
+ {
+ self.selectMode(.developerLocal)
+ }
+ }
+ }
+
+ Section {
+ Button("Continue") {
+ self.step = .connect
+ }
+ .disabled(self.selectedMode == nil)
+ }
+ }
+
+ @ViewBuilder
+ private var connectStep: some View {
+ if let selectedMode {
+ Section {
+ LabeledContent("Mode", value: selectedMode.title)
+ LabeledContent("Discovery", value: self.gatewayController.discoveryStatusText)
+ LabeledContent("Status", value: self.appModel.gatewayStatusText)
+ LabeledContent("Progress", value: self.statusLine)
+ } header: {
+ Text("Status")
+ } footer: {
+ if let connectMessage {
+ Text(connectMessage)
+ }
+ }
+
+ switch selectedMode {
+ case .homeNetwork:
+ self.homeNetworkConnectSection
+ case .remoteDomain:
+ self.remoteDomainConnectSection
+ case .developerLocal:
+ self.developerConnectSection
+ }
+ } else {
+ Section {
+ Text("Choose a mode first.")
+ Button("Back to Mode Selection") {
+ self.step = .mode
+ }
+ }
+ }
+ }
+
+ private var homeNetworkConnectSection: some View {
+ Group {
+ Section("Discovered Gateways") {
+ if self.gatewayController.gateways.isEmpty {
+ Text("No gateways found yet.")
+ .foregroundStyle(.secondary)
+ } else {
+ ForEach(self.gatewayController.gateways) { gateway in
+ let hasHost = self.gatewayHasResolvableHost(gateway)
+
+ HStack {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(gateway.name)
+ if let host = gateway.lanHost ?? gateway.tailnetDns {
+ Text(host)
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+ }
+ Spacer()
+ Button {
+ Task { await self.connectDiscoveredGateway(gateway) }
+ } label: {
+ if self.connectingGatewayID == gateway.id {
+ ProgressView()
+ .progressViewStyle(.circular)
+ } else if !hasHost {
+ Text("Resolving…")
+ } else {
+ Text("Connect")
+ }
+ }
+ .disabled(self.connectingGatewayID != nil || !hasHost)
+ }
+ }
+ }
+
+ Button("Restart Discovery") {
+ self.gatewayController.restartDiscovery()
+ }
+ .disabled(self.connectingGatewayID != nil)
+ }
+
+ self.manualConnectionFieldsSection(title: "Manual Fallback")
+ }
+ }
+
+ private var remoteDomainConnectSection: some View {
+ self.manualConnectionFieldsSection(title: "Domain Settings")
+ }
+
+ private var developerConnectSection: some View {
+ Section {
+ TextField("Host", text: self.$manualHost)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ TextField("Port", text: self.$manualPortText)
+ .keyboardType(.numberPad)
+ Toggle("Use TLS", isOn: self.$manualTLS)
+
+ Button {
+ Task { await self.connectManual() }
+ } label: {
+ if self.connectingGatewayID == "manual" {
+ HStack(spacing: 8) {
+ ProgressView()
+ .progressViewStyle(.circular)
+ Text("Connecting…")
+ }
+ } else {
+ Text("Connect")
+ }
+ }
+ .disabled(!self.canConnectManual || self.connectingGatewayID != nil)
+ } header: {
+ Text("Developer Local")
+ } footer: {
+ Text("Default host is localhost. Use your Mac LAN IP if simulator networking requires it.")
+ }
+ }
+
+ private var authStep: some View {
+ Group {
+ Section("Authentication") {
+ TextField("Gateway Auth Token", text: self.$gatewayToken)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ SecureField("Gateway Password", text: self.$gatewayPassword)
+
+ if self.issue.needsAuthToken {
+ Text("Gateway rejected credentials. Scan a fresh QR code or update token/password.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ } else {
+ Text("Auth token looks valid.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+ }
+
+ if self.issue.needsPairing {
+ Section {
+ Button {
+ self.resumeAfterPairingApproval()
+ } label: {
+ Label("Resume After Approval", systemImage: "arrow.clockwise")
+ }
+ .disabled(self.connectingGatewayID != nil)
+ } header: {
+ Text("Pairing Approval")
+ } footer: {
+ let requestLine: String = {
+ if let id = self.issue.requestId, !id.isEmpty {
+ return "Request ID: \(id)"
+ }
+ return "Request ID: check `openclaw devices list`."
+ }()
+ Text(
+ "Approve this device on the gateway.\n"
+ + "1) `openclaw devices approve` (or `openclaw devices approve `)\n"
+ + "2) `/pair approve` in Telegram\n"
+ + "\(requestLine)\n"
+ + "OpenClaw will also retry automatically when you return to this app.")
+ }
+ }
+
+ Section {
+ Button {
+ self.openQRScannerFromOnboarding()
+ } label: {
+ Label("Scan QR Code Again", systemImage: "qrcode.viewfinder")
+ }
+ .disabled(self.connectingGatewayID != nil)
+
+ Button {
+ Task { await self.retryLastAttempt() }
+ } label: {
+ if self.connectingGatewayID == "retry" {
+ ProgressView()
+ .progressViewStyle(.circular)
+ } else {
+ Text("Retry Connection")
+ }
+ }
+ .disabled(self.connectingGatewayID != nil)
+ }
+ }
+ }
+
+ private var successStep: some View {
+ VStack(spacing: 0) {
+ Spacer()
+
+ Image(systemName: "checkmark.circle.fill")
+ .font(.system(size: 64))
+ .foregroundStyle(.green)
+ .padding(.bottom, 20)
+
+ Text("Connected")
+ .font(.largeTitle.weight(.bold))
+ .padding(.bottom, 8)
+
+ let server = self.appModel.gatewayServerName ?? "gateway"
+ Text(server)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .padding(.bottom, 4)
+
+ if let addr = self.appModel.gatewayRemoteAddress {
+ Text(addr)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+
+ Button {
+ self.onClose()
+ } label: {
+ Text("Open OpenClaw")
+ .frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.large)
+ .padding(.horizontal, 24)
+ .padding(.bottom, 48)
+ }
+ }
+
+ @ViewBuilder
+ private func manualConnectionFieldsSection(title: String) -> some View {
+ Section(title) {
+ TextField("Host", text: self.$manualHost)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ TextField("Port", text: self.$manualPortText)
+ .keyboardType(.numberPad)
+ Toggle("Use TLS", isOn: self.$manualTLS)
+ TextField("Discovery Domain (optional)", text: self.$discoveryDomain)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+
+ Button {
+ Task { await self.connectManual() }
+ } label: {
+ if self.connectingGatewayID == "manual" {
+ HStack(spacing: 8) {
+ ProgressView()
+ .progressViewStyle(.circular)
+ Text("Connecting…")
+ }
+ } else {
+ Text("Connect")
+ }
+ }
+ .disabled(!self.canConnectManual || self.connectingGatewayID != nil)
+ }
+ }
+
+ private func handleScannedLink(_ link: GatewayConnectDeepLink) {
+ self.manualHost = link.host
+ self.manualPort = link.port
+ self.manualTLS = link.tls
+ if let token = link.token {
+ self.gatewayToken = token
+ }
+ if let password = link.password {
+ self.gatewayPassword = password
+ }
+ self.saveGatewayCredentials(token: self.gatewayToken, password: self.gatewayPassword)
+ self.showQRScanner = false
+ self.connectMessage = "Connecting via QR code…"
+ self.statusLine = "QR loaded. Connecting to \(link.host):\(link.port)…"
+ if self.selectedMode == nil {
+ self.selectedMode = link.tls ? .remoteDomain : .homeNetwork
+ }
+ Task { await self.connectManual() }
+ }
+
+ private func openQRScannerFromOnboarding() {
+ // Stop active reconnect loops before scanning new credentials.
+ self.appModel.disconnectGateway()
+ self.connectingGatewayID = nil
+ self.connectMessage = nil
+ self.issue = .none
+ self.pairingRequestId = nil
+ self.statusLine = "Opening QR scanner…"
+ self.showQRScanner = true
+ }
+
+ private func resumeAfterPairingApproval() {
+ // We intentionally stop reconnect churn while unpaired to avoid generating multiple pending requests.
+ self.appModel.gatewayAutoReconnectEnabled = true
+ self.appModel.gatewayPairingPaused = false
+ self.appModel.gatewayPairingRequestId = nil
+ // Pairing state is sticky to prevent UI flip-flop during reconnect churn.
+ // Once the user explicitly resumes after approving, clear the sticky issue
+ // so new status/auth errors can surface instead of being masked as pairing.
+ self.issue = .none
+ self.connectMessage = "Retrying after approval…"
+ self.statusLine = "Retrying after approval…"
+ Task { await self.retryLastAttempt() }
+ }
+
+ private func resumeAfterPairingApprovalInBackground() {
+ // Keep the pairing issue sticky to avoid visual flicker while we probe for approval.
+ self.appModel.gatewayAutoReconnectEnabled = true
+ self.appModel.gatewayPairingPaused = false
+ self.appModel.gatewayPairingRequestId = nil
+ Task { await self.retryLastAttempt(silent: true) }
+ }
+
+ private func attemptAutomaticPairingResumeIfNeeded() {
+ guard self.scenePhase == .active else { return }
+ guard self.step == .auth else { return }
+ guard self.issue.needsPairing else { return }
+ guard self.connectingGatewayID == nil else { return }
+
+ let now = Date()
+ if let last = self.lastPairingAutoResumeAttemptAt, now.timeIntervalSince(last) < 6 {
+ return
+ }
+ self.lastPairingAutoResumeAttemptAt = now
+ self.resumeAfterPairingApprovalInBackground()
+ }
+
+ private func detectQRCode(from data: Data) -> String? {
+ guard let ciImage = CIImage(data: data) else { return nil }
+ let detector = CIDetector(
+ ofType: CIDetectorTypeQRCode, context: nil,
+ options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
+ let features = detector?.features(in: ciImage) ?? []
+ for feature in features {
+ if let qr = feature as? CIQRCodeFeature, let message = qr.messageString {
+ return message
+ }
+ }
+ return nil
+ }
+
+ private func navigateBack() {
+ guard let target = self.step.previous else { return }
+ self.connectingGatewayID = nil
+ self.connectMessage = nil
+ self.step = target
+ }
+ private var canConnectManual: Bool {
+ let host = self.manualHost.trimmingCharacters(in: .whitespacesAndNewlines)
+ return !host.isEmpty && self.manualPort > 0 && self.manualPort <= 65535
+ }
+
+ private func initializeState() {
+ if self.manualHost.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ if let last = GatewaySettingsStore.loadLastGatewayConnection() {
+ switch last {
+ case let .manual(host, port, useTLS, _):
+ self.manualHost = host
+ self.manualPort = port
+ self.manualTLS = useTLS
+ case .discovered:
+ self.manualHost = "openclaw.local"
+ self.manualPort = 18789
+ self.manualTLS = true
+ }
+ } else {
+ self.manualHost = "openclaw.local"
+ self.manualPort = 18789
+ self.manualTLS = true
+ }
+ }
+ self.manualPortText = self.manualPort > 0 ? String(self.manualPort) : ""
+ if self.selectedMode == nil {
+ self.selectedMode = OnboardingStateStore.lastMode()
+ }
+ if self.selectedMode == .developerLocal && self.manualHost == "openclaw.local" {
+ self.manualHost = "localhost"
+ self.manualTLS = false
+ }
+
+ let trimmedInstanceId = self.instanceId.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmedInstanceId.isEmpty {
+ self.gatewayToken = GatewaySettingsStore.loadGatewayToken(instanceId: trimmedInstanceId) ?? ""
+ self.gatewayPassword = GatewaySettingsStore.loadGatewayPassword(instanceId: trimmedInstanceId) ?? ""
+ }
+
+ let hasSavedGateway = GatewaySettingsStore.loadLastGatewayConnection() != nil
+ let hasToken = !self.gatewayToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ let hasPassword = !self.gatewayPassword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ if !self.didAutoPresentQR, !hasSavedGateway, !hasToken, !hasPassword {
+ self.didAutoPresentQR = true
+ self.statusLine = "No saved pairing found. Scan QR code to connect."
+ self.showQRScanner = true
+ }
+ }
+
+ private func scheduleDiscoveryRestart() {
+ self.discoveryRestartTask?.cancel()
+ self.discoveryRestartTask = Task { @MainActor in
+ try? await Task.sleep(nanoseconds: 350_000_000)
+ guard !Task.isCancelled else { return }
+ self.gatewayController.restartDiscovery()
+ }
+ }
+
+ private func saveGatewayCredentials(token: String, password: String) {
+ let trimmedInstanceId = self.instanceId.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmedInstanceId.isEmpty else { return }
+ let trimmedToken = token.trimmingCharacters(in: .whitespacesAndNewlines)
+ GatewaySettingsStore.saveGatewayToken(trimmedToken, instanceId: trimmedInstanceId)
+ let trimmedPassword = password.trimmingCharacters(in: .whitespacesAndNewlines)
+ GatewaySettingsStore.saveGatewayPassword(trimmedPassword, instanceId: trimmedInstanceId)
+ }
+
+ private func connectDiscoveredGateway(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) async {
+ self.connectingGatewayID = gateway.id
+ self.issue = .none
+ self.connectMessage = "Connecting to \(gateway.name)…"
+ self.statusLine = "Connecting to \(gateway.name)…"
+ defer { self.connectingGatewayID = nil }
+ await self.gatewayController.connect(gateway)
+ }
+
+ private func selectMode(_ mode: OnboardingConnectionMode) {
+ self.selectedMode = mode
+ self.applyModeDefaults(mode)
+ }
+
+ private func applyModeDefaults(_ mode: OnboardingConnectionMode) {
+ let host = self.manualHost.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ let hostIsDefaultLike = host.isEmpty || host == "openclaw.local" || host == "localhost"
+
+ switch mode {
+ case .homeNetwork:
+ if hostIsDefaultLike { self.manualHost = "openclaw.local" }
+ self.manualTLS = true
+ if self.manualPort <= 0 || self.manualPort > 65535 { self.manualPort = 18789 }
+ case .remoteDomain:
+ if host == "openclaw.local" || host == "localhost" { self.manualHost = "" }
+ self.manualTLS = true
+ if self.manualPort <= 0 || self.manualPort > 65535 { self.manualPort = 18789 }
+ case .developerLocal:
+ if hostIsDefaultLike { self.manualHost = "localhost" }
+ self.manualTLS = false
+ if self.manualPort <= 0 || self.manualPort > 65535 { self.manualPort = 18789 }
+ }
+ }
+
+ private func gatewayHasResolvableHost(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) -> Bool {
+ let lanHost = gateway.lanHost?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ if !lanHost.isEmpty { return true }
+ let tailnetDns = gateway.tailnetDns?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ return !tailnetDns.isEmpty
+ }
+
+ private func connectManual() async {
+ let host = self.manualHost.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !host.isEmpty, self.manualPort > 0, self.manualPort <= 65535 else { return }
+ self.connectingGatewayID = "manual"
+ self.issue = .none
+ self.connectMessage = "Connecting to \(host)…"
+ self.statusLine = "Connecting to \(host):\(self.manualPort)…"
+ defer { self.connectingGatewayID = nil }
+ await self.gatewayController.connectManual(host: host, port: self.manualPort, useTLS: self.manualTLS)
+ }
+
+ private func retryLastAttempt(silent: Bool = false) async {
+ self.connectingGatewayID = silent ? "retry-auto" : "retry"
+ // Keep current auth/pairing issue sticky while retrying to avoid Step 3 UI flip-flop.
+ if !silent {
+ self.connectMessage = "Retrying…"
+ self.statusLine = "Retrying last connection…"
+ }
+ defer { self.connectingGatewayID = nil }
+ await self.gatewayController.connectLastKnown()
+ }
+}
+
+private struct OnboardingModeRow: View {
+ let title: String
+ let subtitle: String
+ let selected: Bool
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: self.action) {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(self.title)
+ .font(.body.weight(.semibold))
+ Text(self.subtitle)
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ Image(systemName: self.selected ? "checkmark.circle.fill" : "circle")
+ .foregroundStyle(self.selected ? Color.accentColor : Color.secondary)
+ }
+ }
+ .buttonStyle(.plain)
+ }
+}
diff --git a/apps/ios/Sources/Onboarding/QRScannerView.swift b/apps/ios/Sources/Onboarding/QRScannerView.swift
new file mode 100644
index 0000000000000..d326c09c42b7d
--- /dev/null
+++ b/apps/ios/Sources/Onboarding/QRScannerView.swift
@@ -0,0 +1,96 @@
+import OpenClawKit
+import SwiftUI
+import VisionKit
+
+struct QRScannerView: UIViewControllerRepresentable {
+ let onGatewayLink: (GatewayConnectDeepLink) -> Void
+ let onError: (String) -> Void
+ let onDismiss: () -> Void
+
+ func makeUIViewController(context: Context) -> UIViewController {
+ guard DataScannerViewController.isSupported else {
+ context.coordinator.reportError("QR scanning is not supported on this device.")
+ return UIViewController()
+ }
+ guard DataScannerViewController.isAvailable else {
+ context.coordinator.reportError("Camera scanning is currently unavailable.")
+ return UIViewController()
+ }
+ let scanner = DataScannerViewController(
+ recognizedDataTypes: [.barcode(symbologies: [.qr])],
+ isHighlightingEnabled: true)
+ scanner.delegate = context.coordinator
+ do {
+ try scanner.startScanning()
+ } catch {
+ context.coordinator.reportError("Could not start QR scanner.")
+ }
+ return scanner
+ }
+
+ func updateUIViewController(_: UIViewController, context _: Context) {}
+
+ static func dismantleUIViewController(_ uiViewController: UIViewController, coordinator: Coordinator) {
+ if let scanner = uiViewController as? DataScannerViewController {
+ scanner.stopScanning()
+ }
+ coordinator.parent.onDismiss()
+ }
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator(parent: self)
+ }
+
+ final class Coordinator: NSObject, DataScannerViewControllerDelegate {
+ let parent: QRScannerView
+ private var handled = false
+ private var reportedError = false
+
+ init(parent: QRScannerView) {
+ self.parent = parent
+ }
+
+ func reportError(_ message: String) {
+ guard !self.reportedError else { return }
+ self.reportedError = true
+ Task { @MainActor in
+ self.parent.onError(message)
+ }
+ }
+
+ func dataScanner(_: DataScannerViewController, didAdd items: [RecognizedItem], allItems _: [RecognizedItem]) {
+ guard !self.handled else { return }
+ for item in items {
+ guard case let .barcode(barcode) = item,
+ let payload = barcode.payloadStringValue
+ else { continue }
+
+ // Try setup code format first (base64url JSON from /pair qr).
+ if let link = GatewayConnectDeepLink.fromSetupCode(payload) {
+ self.handled = true
+ self.parent.onGatewayLink(link)
+ return
+ }
+
+ // Fall back to deep link URL format (openclaw://gateway?...).
+ if let url = URL(string: payload),
+ let route = DeepLinkParser.parse(url),
+ case let .gateway(link) = route
+ {
+ self.handled = true
+ self.parent.onGatewayLink(link)
+ return
+ }
+ }
+ }
+
+ func dataScanner(_: DataScannerViewController, didRemove _: [RecognizedItem], allItems _: [RecognizedItem]) {}
+
+ func dataScanner(
+ _: DataScannerViewController,
+ becameUnavailableWithError _: DataScannerViewController.ScanningUnavailable)
+ {
+ self.reportError("Camera is not available on this device.")
+ }
+ }
+}
diff --git a/apps/ios/Sources/OpenClaw.entitlements b/apps/ios/Sources/OpenClaw.entitlements
new file mode 100644
index 0000000000000..a2663ce930be4
--- /dev/null
+++ b/apps/ios/Sources/OpenClaw.entitlements
@@ -0,0 +1,9 @@
+
+
+
+
+ aps-environment
+ development
+
+
+
diff --git a/apps/ios/Sources/OpenClawApp.swift b/apps/ios/Sources/OpenClawApp.swift
index 8ad23ae20a10a..091c1b90fdf27 100644
--- a/apps/ios/Sources/OpenClawApp.swift
+++ b/apps/ios/Sources/OpenClawApp.swift
@@ -1,12 +1,73 @@
import SwiftUI
+import Foundation
+import os
+import UIKit
+
+final class OpenClawAppDelegate: NSObject, UIApplicationDelegate {
+ private let logger = Logger(subsystem: "ai.openclaw.ios", category: "Push")
+ private var pendingAPNsDeviceToken: Data?
+ weak var appModel: NodeAppModel? {
+ didSet {
+ guard let model = self.appModel, let token = self.pendingAPNsDeviceToken else { return }
+ self.pendingAPNsDeviceToken = nil
+ Task { @MainActor in
+ model.updateAPNsDeviceToken(token)
+ }
+ }
+ }
+
+ func application(
+ _ application: UIApplication,
+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
+ ) -> Bool
+ {
+ application.registerForRemoteNotifications()
+ return true
+ }
+
+ func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
+ if let appModel = self.appModel {
+ Task { @MainActor in
+ appModel.updateAPNsDeviceToken(deviceToken)
+ }
+ return
+ }
+
+ self.pendingAPNsDeviceToken = deviceToken
+ }
+
+ func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: any Error) {
+ self.logger.error("APNs registration failed: \(error.localizedDescription, privacy: .public)")
+ }
+
+ func application(
+ _ application: UIApplication,
+ didReceiveRemoteNotification userInfo: [AnyHashable: Any],
+ fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
+ {
+ self.logger.info("APNs remote notification received keys=\(userInfo.keys.count, privacy: .public)")
+ Task { @MainActor in
+ guard let appModel = self.appModel else {
+ self.logger.info("APNs wake skipped: appModel unavailable")
+ completionHandler(.noData)
+ return
+ }
+ let handled = await appModel.handleSilentPushWake(userInfo)
+ self.logger.info("APNs wake handled=\(handled, privacy: .public)")
+ completionHandler(handled ? .newData : .noData)
+ }
+ }
+}
@main
struct OpenClawApp: App {
@State private var appModel: NodeAppModel
@State private var gatewayController: GatewayConnectionController
+ @UIApplicationDelegateAdaptor(OpenClawAppDelegate.self) private var appDelegate
@Environment(\.scenePhase) private var scenePhase
init() {
+ Self.installUncaughtExceptionLogger()
GatewaySettingsStore.bootstrapPersistence()
let appModel = NodeAppModel()
_appModel = State(initialValue: appModel)
@@ -19,6 +80,9 @@ struct OpenClawApp: App {
.environment(self.appModel)
.environment(self.appModel.voiceWake)
.environment(self.gatewayController)
+ .task {
+ self.appDelegate.appModel = self.appModel
+ }
.onOpenURL { url in
Task { await self.appModel.handleDeepLink(url: url) }
}
@@ -29,3 +93,18 @@ struct OpenClawApp: App {
}
}
}
+
+extension OpenClawApp {
+ private static func installUncaughtExceptionLogger() {
+ NSLog("OpenClaw: installing uncaught exception handler")
+ NSSetUncaughtExceptionHandler { exception in
+ // Useful when the app hits NSExceptions from SwiftUI/WebKit internals; these do not
+ // produce a normal Swift error backtrace.
+ let reason = exception.reason ?? "(no reason)"
+ NSLog("UNCAUGHT EXCEPTION: %@ %@", exception.name.rawValue, reason)
+ for line in exception.callStackSymbols {
+ NSLog(" %@", line)
+ }
+ }
+ }
+}
diff --git a/apps/ios/Sources/Reminders/RemindersService.swift b/apps/ios/Sources/Reminders/RemindersService.swift
index 36eea52217894..249f439fb1799 100644
--- a/apps/ios/Sources/Reminders/RemindersService.swift
+++ b/apps/ios/Sources/Reminders/RemindersService.swift
@@ -6,7 +6,7 @@ final class RemindersService: RemindersServicing {
func list(params: OpenClawRemindersListParams) async throws -> OpenClawRemindersListPayload {
let store = EKEventStore()
let status = EKEventStore.authorizationStatus(for: .reminder)
- let authorized = await Self.ensureAuthorization(store: store, status: status)
+ let authorized = EventKitAuthorization.allowsRead(status: status)
guard authorized else {
throw NSError(domain: "Reminders", code: 1, userInfo: [
NSLocalizedDescriptionKey: "REMINDERS_PERMISSION_REQUIRED: grant Reminders permission",
@@ -50,7 +50,7 @@ final class RemindersService: RemindersServicing {
func add(params: OpenClawRemindersAddParams) async throws -> OpenClawRemindersAddPayload {
let store = EKEventStore()
let status = EKEventStore.authorizationStatus(for: .reminder)
- let authorized = await Self.ensureWriteAuthorization(store: store, status: status)
+ let authorized = EventKitAuthorization.allowsWrite(status: status)
guard authorized else {
throw NSError(domain: "Reminders", code: 2, userInfo: [
NSLocalizedDescriptionKey: "REMINDERS_PERMISSION_REQUIRED: grant Reminders permission",
@@ -100,38 +100,6 @@ final class RemindersService: RemindersServicing {
return OpenClawRemindersAddPayload(reminder: payload)
}
- private static func ensureAuthorization(store: EKEventStore, status: EKAuthorizationStatus) async -> Bool {
- switch status {
- case .authorized:
- return true
- case .notDetermined:
- // Don’t prompt during node.invoke; prompts block the invoke and lead to timeouts.
- return false
- case .restricted, .denied:
- return false
- case .fullAccess:
- return true
- case .writeOnly:
- return false
- @unknown default:
- return false
- }
- }
-
- private static func ensureWriteAuthorization(store: EKEventStore, status: EKAuthorizationStatus) async -> Bool {
- switch status {
- case .authorized, .fullAccess, .writeOnly:
- return true
- case .notDetermined:
- // Don’t prompt during node.invoke; prompts block the invoke and lead to timeouts.
- return false
- case .restricted, .denied:
- return false
- @unknown default:
- return false
- }
- }
-
private static func resolveList(
store: EKEventStore,
listId: String?,
diff --git a/apps/ios/Sources/RootCanvas.swift b/apps/ios/Sources/RootCanvas.swift
index 514e1b4cc47ce..70ba9cdb96fe0 100644
--- a/apps/ios/Sources/RootCanvas.swift
+++ b/apps/ios/Sources/RootCanvas.swift
@@ -3,34 +3,69 @@ import UIKit
struct RootCanvas: View {
@Environment(NodeAppModel.self) private var appModel
+ @Environment(GatewayConnectionController.self) private var gatewayController
@Environment(VoiceWakeManager.self) private var voiceWake
@Environment(\.colorScheme) private var systemColorScheme
@Environment(\.scenePhase) private var scenePhase
@AppStorage(VoiceWakePreferences.enabledKey) private var voiceWakeEnabled: Bool = false
@AppStorage("screen.preventSleep") private var preventSleep: Bool = true
@AppStorage("canvas.debugStatusEnabled") private var canvasDebugStatusEnabled: Bool = false
+ @AppStorage("onboarding.requestID") private var onboardingRequestID: Int = 0
@AppStorage("gateway.onboardingComplete") private var onboardingComplete: Bool = false
@AppStorage("gateway.hasConnectedOnce") private var hasConnectedOnce: Bool = false
@AppStorage("gateway.preferredStableID") private var preferredGatewayStableID: String = ""
@AppStorage("gateway.manual.enabled") private var manualGatewayEnabled: Bool = false
@AppStorage("gateway.manual.host") private var manualGatewayHost: String = ""
+ @AppStorage("onboarding.quickSetupDismissed") private var quickSetupDismissed: Bool = false
@State private var presentedSheet: PresentedSheet?
@State private var voiceWakeToastText: String?
@State private var toastDismissTask: Task?
+ @State private var showOnboarding: Bool = false
+ @State private var onboardingAllowSkip: Bool = true
+ @State private var didEvaluateOnboarding: Bool = false
@State private var didAutoOpenSettings: Bool = false
private enum PresentedSheet: Identifiable {
case settings
case chat
+ case quickSetup
var id: Int {
switch self {
case .settings: 0
case .chat: 1
+ case .quickSetup: 2
}
}
}
+ enum StartupPresentationRoute: Equatable {
+ case none
+ case onboarding
+ case settings
+ }
+
+ static func startupPresentationRoute(
+ gatewayConnected: Bool,
+ hasConnectedOnce: Bool,
+ onboardingComplete: Bool,
+ hasExistingGatewayConfig: Bool,
+ shouldPresentOnLaunch: Bool) -> StartupPresentationRoute
+ {
+ if gatewayConnected {
+ return .none
+ }
+ // On first run or explicit launch onboarding state, onboarding always wins.
+ if shouldPresentOnLaunch || !hasConnectedOnce || !onboardingComplete {
+ return .onboarding
+ }
+ // Settings auto-open is a recovery path for previously-connected installs only.
+ if !hasExistingGatewayConfig {
+ return .settings
+ }
+ return .none
+ }
+
var body: some View {
ZStack {
CanvasContent(
@@ -57,30 +92,63 @@ struct RootCanvas: View {
switch sheet {
case .settings:
SettingsTab()
+ .environment(self.appModel)
+ .environment(self.appModel.voiceWake)
+ .environment(self.gatewayController)
case .chat:
ChatSheet(
+ // Chat RPCs run on the operator session (read/write scopes).
gateway: self.appModel.operatorSession,
sessionKey: self.appModel.mainSessionKey,
agentName: self.appModel.activeAgentName,
userAccent: self.appModel.seamColor)
+ case .quickSetup:
+ GatewayQuickSetupSheet()
+ .environment(self.appModel)
+ .environment(self.gatewayController)
}
}
+ .fullScreenCover(isPresented: self.$showOnboarding) {
+ OnboardingWizardView(
+ allowSkip: self.onboardingAllowSkip,
+ onClose: {
+ self.showOnboarding = false
+ })
+ .environment(self.appModel)
+ .environment(self.appModel.voiceWake)
+ .environment(self.gatewayController)
+ }
.onAppear { self.updateIdleTimer() }
+ .onAppear { self.evaluateOnboardingPresentation(force: false) }
.onAppear { self.maybeAutoOpenSettings() }
.onChange(of: self.preventSleep) { _, _ in self.updateIdleTimer() }
.onChange(of: self.scenePhase) { _, _ in self.updateIdleTimer() }
+ .onAppear { self.maybeShowQuickSetup() }
+ .onChange(of: self.gatewayController.gateways.count) { _, _ in self.maybeShowQuickSetup() }
.onAppear { self.updateCanvasDebugStatus() }
.onChange(of: self.canvasDebugStatusEnabled) { _, _ in self.updateCanvasDebugStatus() }
.onChange(of: self.appModel.gatewayStatusText) { _, _ in self.updateCanvasDebugStatus() }
.onChange(of: self.appModel.gatewayServerName) { _, _ in self.updateCanvasDebugStatus() }
+ .onChange(of: self.appModel.gatewayServerName) { _, newValue in
+ if newValue != nil {
+ self.showOnboarding = false
+ }
+ }
+ .onChange(of: self.onboardingRequestID) { _, _ in
+ self.evaluateOnboardingPresentation(force: true)
+ }
.onChange(of: self.appModel.gatewayRemoteAddress) { _, _ in self.updateCanvasDebugStatus() }
.onChange(of: self.appModel.gatewayServerName) { _, newValue in
if newValue != nil {
self.onboardingComplete = true
self.hasConnectedOnce = true
+ OnboardingStateStore.markCompleted(mode: nil)
}
self.maybeAutoOpenSettings()
}
+ .onChange(of: self.appModel.openChatRequestID) { _, _ in
+ self.presentedSheet = .chat
+ }
.onChange(of: self.voiceWake.lastTriggeredCommand) { _, newValue in
guard let newValue else { return }
let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -136,11 +204,31 @@ struct RootCanvas: View {
self.appModel.screen.updateDebugStatus(title: title, subtitle: subtitle)
}
- private func shouldAutoOpenSettings() -> Bool {
- if self.appModel.gatewayServerName != nil { return false }
- if !self.hasConnectedOnce { return true }
- if !self.onboardingComplete { return true }
- return !self.hasExistingGatewayConfig()
+ private func evaluateOnboardingPresentation(force: Bool) {
+ if force {
+ self.onboardingAllowSkip = true
+ self.showOnboarding = true
+ return
+ }
+
+ guard !self.didEvaluateOnboarding else { return }
+ self.didEvaluateOnboarding = true
+ let route = Self.startupPresentationRoute(
+ gatewayConnected: self.appModel.gatewayServerName != nil,
+ hasConnectedOnce: self.hasConnectedOnce,
+ onboardingComplete: self.onboardingComplete,
+ hasExistingGatewayConfig: self.hasExistingGatewayConfig(),
+ shouldPresentOnLaunch: OnboardingStateStore.shouldPresentOnLaunch(appModel: self.appModel))
+ switch route {
+ case .none:
+ break
+ case .onboarding:
+ self.onboardingAllowSkip = true
+ self.showOnboarding = true
+ case .settings:
+ self.didAutoOpenSettings = true
+ self.presentedSheet = .settings
+ }
}
private func hasExistingGatewayConfig() -> Bool {
@@ -151,10 +239,26 @@ struct RootCanvas: View {
private func maybeAutoOpenSettings() {
guard !self.didAutoOpenSettings else { return }
- guard self.shouldAutoOpenSettings() else { return }
+ guard !self.showOnboarding else { return }
+ let route = Self.startupPresentationRoute(
+ gatewayConnected: self.appModel.gatewayServerName != nil,
+ hasConnectedOnce: self.hasConnectedOnce,
+ onboardingComplete: self.onboardingComplete,
+ hasExistingGatewayConfig: self.hasExistingGatewayConfig(),
+ shouldPresentOnLaunch: false)
+ guard route == .settings else { return }
self.didAutoOpenSettings = true
self.presentedSheet = .settings
}
+
+ private func maybeShowQuickSetup() {
+ guard !self.quickSetupDismissed else { return }
+ guard !self.showOnboarding else { return }
+ guard self.presentedSheet == nil else { return }
+ guard self.appModel.gatewayServerName == nil else { return }
+ guard !self.gatewayController.gateways.isEmpty else { return }
+ self.presentedSheet = .quickSetup
+ }
}
private struct CanvasContent: View {
diff --git a/apps/ios/Sources/RootTabs.swift b/apps/ios/Sources/RootTabs.swift
index 278e56d6150d2..4733a4a30fcb8 100644
--- a/apps/ios/Sources/RootTabs.swift
+++ b/apps/ios/Sources/RootTabs.swift
@@ -3,6 +3,7 @@ import SwiftUI
struct RootTabs: View {
@Environment(NodeAppModel.self) private var appModel
@Environment(VoiceWakeManager.self) private var voiceWake
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
@AppStorage(VoiceWakePreferences.enabledKey) private var voiceWakeEnabled: Bool = false
@State private var selectedTab: Int = 0
@State private var voiceWakeToastText: String?
@@ -52,14 +53,14 @@ struct RootTabs: View {
guard !trimmed.isEmpty else { return }
self.toastDismissTask?.cancel()
- withAnimation(.spring(response: 0.25, dampingFraction: 0.85)) {
+ withAnimation(self.reduceMotion ? .none : .spring(response: 0.25, dampingFraction: 0.85)) {
self.voiceWakeToastText = trimmed
}
self.toastDismissTask = Task {
try? await Task.sleep(nanoseconds: 2_300_000_000)
await MainActor.run {
- withAnimation(.easeOut(duration: 0.25)) {
+ withAnimation(self.reduceMotion ? .none : .easeOut(duration: 0.25)) {
self.voiceWakeToastText = nil
}
}
@@ -104,66 +105,10 @@ struct RootTabs: View {
}
private var statusActivity: StatusPill.Activity? {
- // Keep the top pill consistent across tabs (camera + voice wake + pairing states).
- if self.appModel.isBackgrounded {
- return StatusPill.Activity(
- title: "Foreground required",
- systemImage: "exclamationmark.triangle.fill",
- tint: .orange)
- }
-
- let gatewayStatus = self.appModel.gatewayStatusText.trimmingCharacters(in: .whitespacesAndNewlines)
- let gatewayLower = gatewayStatus.lowercased()
- if gatewayLower.contains("repair") {
- return StatusPill.Activity(title: "Repairing…", systemImage: "wrench.and.screwdriver", tint: .orange)
- }
- if gatewayLower.contains("approval") || gatewayLower.contains("pairing") {
- return StatusPill.Activity(title: "Approval pending", systemImage: "person.crop.circle.badge.clock")
- }
- // Avoid duplicating the primary gateway status ("Connecting…") in the activity slot.
-
- if self.appModel.screenRecordActive {
- return StatusPill.Activity(title: "Recording screen…", systemImage: "record.circle.fill", tint: .red)
- }
-
- if let cameraHUDText = self.appModel.cameraHUDText,
- let cameraHUDKind = self.appModel.cameraHUDKind,
- !cameraHUDText.isEmpty
- {
- let systemImage: String
- let tint: Color?
- switch cameraHUDKind {
- case .photo:
- systemImage = "camera.fill"
- tint = nil
- case .recording:
- systemImage = "video.fill"
- tint = .red
- case .success:
- systemImage = "checkmark.circle.fill"
- tint = .green
- case .error:
- systemImage = "exclamationmark.triangle.fill"
- tint = .red
- }
- return StatusPill.Activity(title: cameraHUDText, systemImage: systemImage, tint: tint)
- }
-
- if self.voiceWakeEnabled {
- let voiceStatus = self.appModel.voiceWake.statusText
- if voiceStatus.localizedCaseInsensitiveContains("microphone permission") {
- return StatusPill.Activity(title: "Mic permission", systemImage: "mic.slash", tint: .orange)
- }
- if voiceStatus == "Paused" {
- // Talk mode intentionally pauses voice wake to release the mic. Don't spam the HUD for that case.
- if self.appModel.talkMode.isEnabled {
- return nil
- }
- let suffix = self.appModel.isBackgrounded ? " (background)" : ""
- return StatusPill.Activity(title: "Voice Wake paused\(suffix)", systemImage: "pause.circle.fill")
- }
- }
-
- return nil
+ StatusActivityBuilder.build(
+ appModel: self.appModel,
+ voiceWakeEnabled: self.voiceWakeEnabled,
+ cameraHUDText: self.appModel.cameraHUDText,
+ cameraHUDKind: self.appModel.cameraHUDKind)
}
}
diff --git a/apps/ios/Sources/Screen/ScreenController.swift b/apps/ios/Sources/Screen/ScreenController.swift
index 506b78a230815..0045232362bde 100644
--- a/apps/ios/Sources/Screen/ScreenController.swift
+++ b/apps/ios/Sources/Screen/ScreenController.swift
@@ -1,14 +1,12 @@
import OpenClawKit
import Observation
-import SwiftUI
+import UIKit
import WebKit
@MainActor
@Observable
final class ScreenController {
- let webView: WKWebView
- private let navigationDelegate: ScreenNavigationDelegate
- private let a2uiActionHandler: CanvasA2UIActionMessageHandler
+ private weak var activeWebView: WKWebView?
var urlString: String = ""
var errorText: String?
@@ -24,29 +22,6 @@ final class ScreenController {
private var debugStatusSubtitle: String?
init() {
- let config = WKWebViewConfiguration()
- config.websiteDataStore = .nonPersistent()
- let a2uiActionHandler = CanvasA2UIActionMessageHandler()
- let userContentController = WKUserContentController()
- for name in CanvasA2UIActionMessageHandler.handlerNames {
- userContentController.add(a2uiActionHandler, name: name)
- }
- config.userContentController = userContentController
- self.navigationDelegate = ScreenNavigationDelegate()
- self.a2uiActionHandler = a2uiActionHandler
- self.webView = WKWebView(frame: .zero, configuration: config)
- // Canvas scaffold is a fully self-contained HTML page; avoid relying on transparency underlays.
- self.webView.isOpaque = true
- self.webView.backgroundColor = .black
- self.webView.scrollView.backgroundColor = .black
- self.webView.scrollView.contentInsetAdjustmentBehavior = .never
- self.webView.scrollView.contentInset = .zero
- self.webView.scrollView.scrollIndicatorInsets = .zero
- self.webView.scrollView.automaticallyAdjustsScrollIndicatorInsets = false
- self.applyScrollBehavior()
- self.webView.navigationDelegate = self.navigationDelegate
- self.navigationDelegate.controller = self
- a2uiActionHandler.controller = self
self.reload()
}
@@ -71,24 +46,26 @@ final class ScreenController {
}
func reload() {
- let trimmed = self.urlString.trimmingCharacters(in: .whitespacesAndNewlines)
self.applyScrollBehavior()
+ guard let webView = self.activeWebView else { return }
+
+ let trimmed = self.urlString.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
guard let url = Self.canvasScaffoldURL else { return }
self.errorText = nil
- self.webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
+ webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
+ return
+ }
+
+ guard let url = URL(string: trimmed) else {
+ self.errorText = "Invalid URL: \(trimmed)"
return
+ }
+ self.errorText = nil
+ if url.isFileURL {
+ webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
} else {
- guard let url = URL(string: trimmed) else {
- self.errorText = "Invalid URL: \(trimmed)"
- return
- }
- self.errorText = nil
- if url.isFileURL {
- self.webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
- } else {
- self.webView.load(URLRequest(url: url))
- }
+ webView.load(URLRequest(url: url))
}
}
@@ -108,7 +85,8 @@ final class ScreenController {
self.applyDebugStatusIfNeeded()
}
- fileprivate func applyDebugStatusIfNeeded() {
+ func applyDebugStatusIfNeeded() {
+ guard let webView = self.activeWebView else { return }
let enabled = self.debugStatusEnabled
let title = self.debugStatusTitle
let subtitle = self.debugStatusSubtitle
@@ -127,7 +105,7 @@ final class ScreenController {
} catch (_) {}
})()
"""
- self.webView.evaluateJavaScript(js) { _, _ in }
+ webView.evaluateJavaScript(js) { _, _ in }
}
func waitForA2UIReady(timeoutMs: Int) async -> Bool {
@@ -154,8 +132,13 @@ final class ScreenController {
}
func eval(javaScript: String) async throws -> String {
- try await withCheckedThrowingContinuation { cont in
- self.webView.evaluateJavaScript(javaScript) { result, error in
+ guard let webView = self.activeWebView else {
+ throw NSError(domain: "Screen", code: 3, userInfo: [
+ NSLocalizedDescriptionKey: "web view unavailable",
+ ])
+ }
+ return try await withCheckedThrowingContinuation { cont in
+ webView.evaluateJavaScript(javaScript) { result, error in
if let error {
cont.resume(throwing: error)
return
@@ -174,8 +157,13 @@ final class ScreenController {
if let maxWidth {
config.snapshotWidth = NSNumber(value: Double(maxWidth))
}
+ guard let webView = self.activeWebView else {
+ throw NSError(domain: "Screen", code: 3, userInfo: [
+ NSLocalizedDescriptionKey: "web view unavailable",
+ ])
+ }
let image: UIImage = try await withCheckedThrowingContinuation { cont in
- self.webView.takeSnapshot(with: config) { image, error in
+ webView.takeSnapshot(with: config) { image, error in
if let error {
cont.resume(throwing: error)
return
@@ -206,8 +194,13 @@ final class ScreenController {
if let maxWidth {
config.snapshotWidth = NSNumber(value: Double(maxWidth))
}
+ guard let webView = self.activeWebView else {
+ throw NSError(domain: "Screen", code: 3, userInfo: [
+ NSLocalizedDescriptionKey: "web view unavailable",
+ ])
+ }
let image: UIImage = try await withCheckedThrowingContinuation { cont in
- self.webView.takeSnapshot(with: config) { image, error in
+ webView.takeSnapshot(with: config) { image, error in
if let error {
cont.resume(throwing: error)
return
@@ -238,6 +231,17 @@ final class ScreenController {
return data.base64EncodedString()
}
+ func attachWebView(_ webView: WKWebView) {
+ self.activeWebView = webView
+ self.reload()
+ self.applyDebugStatusIfNeeded()
+ }
+
+ func detachWebView(_ webView: WKWebView) {
+ guard self.activeWebView === webView else { return }
+ self.activeWebView = nil
+ }
+
private static func bundledResourceURL(
name: String,
ext: String,
@@ -277,9 +281,10 @@ final class ScreenController {
}
private func applyScrollBehavior() {
+ guard let webView = self.activeWebView else { return }
let trimmed = self.urlString.trimmingCharacters(in: .whitespacesAndNewlines)
let allowScroll = !trimmed.isEmpty
- let scrollView = self.webView.scrollView
+ let scrollView = webView.scrollView
// Default canvas needs raw touch events; external pages should scroll.
scrollView.isScrollEnabled = allowScroll
scrollView.bounces = allowScroll
@@ -366,72 +371,3 @@ extension Double {
return self
}
}
-
-// MARK: - Navigation Delegate
-
-/// Handles navigation policy to intercept openclaw:// deep links from canvas
-@MainActor
-private final class ScreenNavigationDelegate: NSObject, WKNavigationDelegate {
- weak var controller: ScreenController?
-
- func webView(
- _ webView: WKWebView,
- decidePolicyFor navigationAction: WKNavigationAction,
- decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void)
- {
- guard let url = navigationAction.request.url else {
- decisionHandler(.allow)
- return
- }
-
- // Intercept openclaw:// deep links.
- if url.scheme?.lowercased() == "openclaw" {
- decisionHandler(.cancel)
- self.controller?.onDeepLink?(url)
- return
- }
-
- decisionHandler(.allow)
- }
-
- func webView(
- _: WKWebView,
- didFailProvisionalNavigation _: WKNavigation?,
- withError error: any Error)
- {
- self.controller?.errorText = error.localizedDescription
- }
-
- func webView(_: WKWebView, didFinish _: WKNavigation?) {
- self.controller?.errorText = nil
- self.controller?.applyDebugStatusIfNeeded()
- }
-
- func webView(_: WKWebView, didFail _: WKNavigation?, withError error: any Error) {
- self.controller?.errorText = error.localizedDescription
- }
-}
-
-private final class CanvasA2UIActionMessageHandler: NSObject, WKScriptMessageHandler {
- static let messageName = "openclawCanvasA2UIAction"
- static let handlerNames = [messageName]
-
- weak var controller: ScreenController?
-
- func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
- guard Self.handlerNames.contains(message.name) else { return }
- guard let controller else { return }
-
- guard let url = message.webView?.url else { return }
- if url.isFileURL {
- guard controller.isTrustedCanvasUIURL(url) else { return }
- } else {
- // For security, only accept actions from local-network pages (e.g. the canvas host).
- guard controller.isLocalNetworkCanvasURL(url) else { return }
- }
-
- guard let body = ScreenController.parseA2UIActionBody(message.body) else { return }
-
- controller.onA2UIAction?(body)
- }
-}
diff --git a/apps/ios/Sources/Screen/ScreenWebView.swift b/apps/ios/Sources/Screen/ScreenWebView.swift
index c464521be5f9f..a30d78cbd0061 100644
--- a/apps/ios/Sources/Screen/ScreenWebView.swift
+++ b/apps/ios/Sources/Screen/ScreenWebView.swift
@@ -5,11 +5,189 @@ import WebKit
struct ScreenWebView: UIViewRepresentable {
var controller: ScreenController
- func makeUIView(context: Context) -> WKWebView {
- self.controller.webView
+ func makeCoordinator() -> ScreenWebViewCoordinator {
+ ScreenWebViewCoordinator(controller: self.controller)
}
- func updateUIView(_ webView: WKWebView, context: Context) {
- // State changes are driven by ScreenController.
+ func makeUIView(context: Context) -> UIView {
+ context.coordinator.makeContainerView()
+ }
+
+ func updateUIView(_: UIView, context: Context) {
+ context.coordinator.updateController(self.controller)
+ }
+
+ static func dismantleUIView(_: UIView, coordinator: ScreenWebViewCoordinator) {
+ coordinator.teardown()
+ }
+}
+
+@MainActor
+final class ScreenWebViewCoordinator: NSObject {
+ private weak var controller: ScreenController?
+ private let navigationDelegate = ScreenNavigationDelegate()
+ private let a2uiActionHandler = CanvasA2UIActionMessageHandler()
+ private let userContentController = WKUserContentController()
+
+ private(set) var managedWebView: WKWebView?
+ private weak var containerView: UIView?
+
+ init(controller: ScreenController) {
+ self.controller = controller
+ super.init()
+ self.navigationDelegate.controller = controller
+ self.a2uiActionHandler.controller = controller
+ }
+
+ func makeContainerView() -> UIView {
+ if let containerView {
+ return containerView
+ }
+
+ let container = UIView(frame: .zero)
+ container.backgroundColor = .black
+
+ let webView = Self.makeWebView(userContentController: self.userContentController)
+ webView.navigationDelegate = self.navigationDelegate
+ self.installA2UIHandlers()
+
+ webView.translatesAutoresizingMaskIntoConstraints = false
+ container.addSubview(webView)
+ NSLayoutConstraint.activate([
+ webView.leadingAnchor.constraint(equalTo: container.leadingAnchor),
+ webView.trailingAnchor.constraint(equalTo: container.trailingAnchor),
+ webView.topAnchor.constraint(equalTo: container.topAnchor),
+ webView.bottomAnchor.constraint(equalTo: container.bottomAnchor),
+ ])
+
+ self.managedWebView = webView
+ self.containerView = container
+ self.controller?.attachWebView(webView)
+ return container
+ }
+
+ func updateController(_ controller: ScreenController) {
+ let previousController = self.controller
+ let controllerChanged = self.controller !== controller
+ self.controller = controller
+ self.navigationDelegate.controller = controller
+ self.a2uiActionHandler.controller = controller
+ if controllerChanged, let managedWebView {
+ previousController?.detachWebView(managedWebView)
+ controller.attachWebView(managedWebView)
+ }
+ }
+
+ func teardown() {
+ if let managedWebView {
+ self.controller?.detachWebView(managedWebView)
+ managedWebView.navigationDelegate = nil
+ }
+ self.removeA2UIHandlers()
+ self.navigationDelegate.controller = nil
+ self.a2uiActionHandler.controller = nil
+ self.managedWebView = nil
+ self.containerView = nil
+ }
+
+ private static func makeWebView(userContentController: WKUserContentController) -> WKWebView {
+ let config = WKWebViewConfiguration()
+ config.websiteDataStore = .nonPersistent()
+ config.userContentController = userContentController
+
+ let webView = WKWebView(frame: .zero, configuration: config)
+ // Canvas scaffold is a fully self-contained HTML page; avoid relying on transparency underlays.
+ webView.isOpaque = true
+ webView.backgroundColor = .black
+
+ let scrollView = webView.scrollView
+ scrollView.backgroundColor = .black
+ scrollView.contentInsetAdjustmentBehavior = .never
+ scrollView.contentInset = .zero
+ scrollView.scrollIndicatorInsets = .zero
+ scrollView.automaticallyAdjustsScrollIndicatorInsets = false
+
+ return webView
+ }
+
+ private func installA2UIHandlers() {
+ for name in CanvasA2UIActionMessageHandler.handlerNames {
+ self.userContentController.add(self.a2uiActionHandler, name: name)
+ }
+ }
+
+ private func removeA2UIHandlers() {
+ for name in CanvasA2UIActionMessageHandler.handlerNames {
+ self.userContentController.removeScriptMessageHandler(forName: name)
+ }
+ }
+}
+
+// MARK: - Navigation Delegate
+
+/// Handles navigation policy to intercept openclaw:// deep links from canvas
+@MainActor
+private final class ScreenNavigationDelegate: NSObject, WKNavigationDelegate {
+ weak var controller: ScreenController?
+
+ func webView(
+ _: WKWebView,
+ decidePolicyFor navigationAction: WKNavigationAction,
+ decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void)
+ {
+ guard let url = navigationAction.request.url else {
+ decisionHandler(.allow)
+ return
+ }
+
+ // Intercept openclaw:// deep links.
+ if url.scheme?.lowercased() == "openclaw" {
+ decisionHandler(.cancel)
+ self.controller?.onDeepLink?(url)
+ return
+ }
+
+ decisionHandler(.allow)
+ }
+
+ func webView(
+ _: WKWebView,
+ didFailProvisionalNavigation _: WKNavigation?,
+ withError error: any Error)
+ {
+ self.controller?.errorText = error.localizedDescription
+ }
+
+ func webView(_: WKWebView, didFinish _: WKNavigation?) {
+ self.controller?.errorText = nil
+ self.controller?.applyDebugStatusIfNeeded()
+ }
+
+ func webView(_: WKWebView, didFail _: WKNavigation?, withError error: any Error) {
+ self.controller?.errorText = error.localizedDescription
+ }
+}
+
+private final class CanvasA2UIActionMessageHandler: NSObject, WKScriptMessageHandler {
+ static let messageName = "openclawCanvasA2UIAction"
+ static let handlerNames = [messageName]
+
+ weak var controller: ScreenController?
+
+ func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
+ guard Self.handlerNames.contains(message.name) else { return }
+ guard let controller else { return }
+
+ guard let url = message.webView?.url else { return }
+ if url.isFileURL {
+ guard controller.isTrustedCanvasUIURL(url) else { return }
+ } else {
+ // For security, only accept actions from local-network pages (e.g. the canvas host).
+ guard controller.isLocalNetworkCanvasURL(url) else { return }
+ }
+
+ guard let body = ScreenController.parseA2UIActionBody(message.body) else { return }
+
+ controller.onA2UIAction?(body)
}
}
diff --git a/apps/ios/Sources/Services/NodeServiceProtocols.swift b/apps/ios/Sources/Services/NodeServiceProtocols.swift
index 002c87ad9ca08..6f882e82a11fb 100644
--- a/apps/ios/Sources/Services/NodeServiceProtocols.swift
+++ b/apps/ios/Sources/Services/NodeServiceProtocols.swift
@@ -28,6 +28,12 @@ protocol LocationServicing: Sendable {
desiredAccuracy: OpenClawLocationAccuracy,
maxAgeMs: Int?,
timeoutMs: Int?) async throws -> CLLocation
+ func startLocationUpdates(
+ desiredAccuracy: OpenClawLocationAccuracy,
+ significantChangesOnly: Bool) -> AsyncStream
+ func stopLocationUpdates()
+ func startMonitoringSignificantLocationChanges(onUpdate: @escaping @Sendable (CLLocation) -> Void)
+ func stopMonitoringSignificantLocationChanges()
}
protocol DeviceStatusServicing: Sendable {
@@ -59,6 +65,29 @@ protocol MotionServicing: Sendable {
func pedometer(params: OpenClawPedometerParams) async throws -> OpenClawPedometerPayload
}
+struct WatchMessagingStatus: Sendable, Equatable {
+ var supported: Bool
+ var paired: Bool
+ var appInstalled: Bool
+ var reachable: Bool
+ var activationState: String
+}
+
+struct WatchNotificationSendResult: Sendable, Equatable {
+ var deliveredImmediately: Bool
+ var queuedForDelivery: Bool
+ var transport: String
+}
+
+protocol WatchMessagingServicing: AnyObject, Sendable {
+ func status() async -> WatchMessagingStatus
+ func sendNotification(
+ id: String,
+ title: String,
+ body: String,
+ priority: OpenClawNotificationPriority?) async throws -> WatchNotificationSendResult
+}
+
extension CameraController: CameraServicing {}
extension ScreenRecordService: ScreenRecordingServicing {}
extension LocationService: LocationServicing {}
diff --git a/apps/ios/Sources/Services/WatchMessagingService.swift b/apps/ios/Sources/Services/WatchMessagingService.swift
new file mode 100644
index 0000000000000..8332fb5882d7f
--- /dev/null
+++ b/apps/ios/Sources/Services/WatchMessagingService.swift
@@ -0,0 +1,176 @@
+import Foundation
+import OpenClawKit
+import OSLog
+@preconcurrency import WatchConnectivity
+
+enum WatchMessagingError: LocalizedError {
+ case unsupported
+ case notPaired
+ case watchAppNotInstalled
+
+ var errorDescription: String? {
+ switch self {
+ case .unsupported:
+ "WATCH_UNAVAILABLE: WatchConnectivity is not supported on this device"
+ case .notPaired:
+ "WATCH_UNAVAILABLE: no paired Apple Watch"
+ case .watchAppNotInstalled:
+ "WATCH_UNAVAILABLE: OpenClaw watch companion app is not installed"
+ }
+ }
+}
+
+final class WatchMessagingService: NSObject, WatchMessagingServicing, @unchecked Sendable {
+ private static let logger = Logger(subsystem: "ai.openclaw", category: "watch.messaging")
+ private let session: WCSession?
+
+ override init() {
+ if WCSession.isSupported() {
+ self.session = WCSession.default
+ } else {
+ self.session = nil
+ }
+ super.init()
+ if let session = self.session {
+ session.delegate = self
+ session.activate()
+ }
+ }
+
+ static func isSupportedOnDevice() -> Bool {
+ WCSession.isSupported()
+ }
+
+ static func currentStatusSnapshot() -> WatchMessagingStatus {
+ guard WCSession.isSupported() else {
+ return WatchMessagingStatus(
+ supported: false,
+ paired: false,
+ appInstalled: false,
+ reachable: false,
+ activationState: "unsupported")
+ }
+ let session = WCSession.default
+ return status(for: session)
+ }
+
+ func status() async -> WatchMessagingStatus {
+ await self.ensureActivated()
+ guard let session = self.session else {
+ return WatchMessagingStatus(
+ supported: false,
+ paired: false,
+ appInstalled: false,
+ reachable: false,
+ activationState: "unsupported")
+ }
+ return Self.status(for: session)
+ }
+
+ func sendNotification(
+ id: String,
+ title: String,
+ body: String,
+ priority: OpenClawNotificationPriority?) async throws -> WatchNotificationSendResult
+ {
+ await self.ensureActivated()
+ guard let session = self.session else {
+ throw WatchMessagingError.unsupported
+ }
+
+ let snapshot = Self.status(for: session)
+ guard snapshot.paired else { throw WatchMessagingError.notPaired }
+ guard snapshot.appInstalled else { throw WatchMessagingError.watchAppNotInstalled }
+
+ let payload: [String: Any] = [
+ "type": "watch.notify",
+ "id": id,
+ "title": title,
+ "body": body,
+ "priority": priority?.rawValue ?? OpenClawNotificationPriority.active.rawValue,
+ "sentAtMs": Int(Date().timeIntervalSince1970 * 1000),
+ ]
+
+ if snapshot.reachable {
+ do {
+ try await self.sendReachableMessage(payload, with: session)
+ return WatchNotificationSendResult(
+ deliveredImmediately: true,
+ queuedForDelivery: false,
+ transport: "sendMessage")
+ } catch {
+ Self.logger.error("watch sendMessage failed: \(error.localizedDescription, privacy: .public)")
+ }
+ }
+
+ _ = session.transferUserInfo(payload)
+ return WatchNotificationSendResult(
+ deliveredImmediately: false,
+ queuedForDelivery: true,
+ transport: "transferUserInfo")
+ }
+
+ private func sendReachableMessage(_ payload: [String: Any], with session: WCSession) async throws {
+ try await withCheckedThrowingContinuation { continuation in
+ session.sendMessage(payload, replyHandler: { _ in
+ continuation.resume()
+ }, errorHandler: { error in
+ continuation.resume(throwing: error)
+ })
+ }
+ }
+
+ private func ensureActivated() async {
+ guard let session = self.session else { return }
+ if session.activationState == .activated { return }
+ session.activate()
+ for _ in 0..<8 {
+ if session.activationState == .activated { return }
+ try? await Task.sleep(nanoseconds: 100_000_000)
+ }
+ }
+
+ private static func status(for session: WCSession) -> WatchMessagingStatus {
+ WatchMessagingStatus(
+ supported: true,
+ paired: session.isPaired,
+ appInstalled: session.isWatchAppInstalled,
+ reachable: session.isReachable,
+ activationState: activationStateLabel(session.activationState))
+ }
+
+ private static func activationStateLabel(_ state: WCSessionActivationState) -> String {
+ switch state {
+ case .notActivated:
+ "notActivated"
+ case .inactive:
+ "inactive"
+ case .activated:
+ "activated"
+ @unknown default:
+ "unknown"
+ }
+ }
+}
+
+extension WatchMessagingService: WCSessionDelegate {
+ func session(
+ _ session: WCSession,
+ activationDidCompleteWith activationState: WCSessionActivationState,
+ error: (any Error)?)
+ {
+ if let error {
+ Self.logger.error("watch activation failed: \(error.localizedDescription, privacy: .public)")
+ return
+ }
+ Self.logger.debug("watch activation state=\(Self.activationStateLabel(activationState), privacy: .public)")
+ }
+
+ func sessionDidBecomeInactive(_ session: WCSession) {}
+
+ func sessionDidDeactivate(_ session: WCSession) {
+ session.activate()
+ }
+
+ func sessionReachabilityDidChange(_ session: WCSession) {}
+}
diff --git a/apps/ios/Sources/Settings/SettingsTab.swift b/apps/ios/Sources/Settings/SettingsTab.swift
index 662a22cb04952..7825b45cb8d6f 100644
--- a/apps/ios/Sources/Settings/SettingsTab.swift
+++ b/apps/ios/Sources/Settings/SettingsTab.swift
@@ -6,6 +6,12 @@ import SwiftUI
import UIKit
struct SettingsTab: View {
+ private struct FeatureHelp: Identifiable {
+ let id = UUID()
+ let title: String
+ let message: String
+ }
+
@Environment(NodeAppModel.self) private var appModel: NodeAppModel
@Environment(VoiceWakeManager.self) private var voiceWake: VoiceWakeManager
@Environment(GatewayConnectionController.self) private var gatewayController: GatewayConnectionController
@@ -15,9 +21,10 @@ struct SettingsTab: View {
@AppStorage("voiceWake.enabled") private var voiceWakeEnabled: Bool = false
@AppStorage("talk.enabled") private var talkEnabled: Bool = false
@AppStorage("talk.button.enabled") private var talkButtonEnabled: Bool = true
+ @AppStorage("talk.background.enabled") private var talkBackgroundEnabled: Bool = false
+ @AppStorage("talk.voiceDirectiveHint.enabled") private var talkVoiceDirectiveHintEnabled: Bool = true
@AppStorage("camera.enabled") private var cameraEnabled: Bool = true
@AppStorage("location.enabledMode") private var locationEnabledModeRaw: String = OpenClawLocationMode.off.rawValue
- @AppStorage("location.preciseEnabled") private var locationPreciseEnabled: Bool = true
@AppStorage("screen.preventSleep") private var preventSleep: Bool = true
@AppStorage("gateway.preferredStableID") private var preferredGatewayStableID: String = ""
@AppStorage("gateway.lastDiscoveredStableID") private var lastDiscoveredGatewayStableID: String = ""
@@ -28,17 +35,27 @@ struct SettingsTab: View {
@AppStorage("gateway.manual.tls") private var manualGatewayTLS: Bool = true
@AppStorage("gateway.discovery.debugLogs") private var discoveryDebugLogsEnabled: Bool = false
@AppStorage("canvas.debugStatusEnabled") private var canvasDebugStatusEnabled: Bool = false
+
+ // Onboarding control (RootCanvas listens to onboarding.requestID and force-opens the wizard).
+ @AppStorage("onboarding.requestID") private var onboardingRequestID: Int = 0
+ @AppStorage("gateway.onboardingComplete") private var onboardingComplete: Bool = false
+ @AppStorage("gateway.hasConnectedOnce") private var hasConnectedOnce: Bool = false
+
@State private var connectingGatewayID: String?
- @State private var localIPAddress: String?
@State private var lastLocationModeRaw: String = OpenClawLocationMode.off.rawValue
@State private var gatewayToken: String = ""
@State private var gatewayPassword: String = ""
+ @State private var defaultShareInstruction: String = ""
@AppStorage("gateway.setupCode") private var setupCode: String = ""
@State private var setupStatusText: String?
@State private var manualGatewayPortText: String = ""
@State private var gatewayExpanded: Bool = true
@State private var selectedAgentPickerId: String = ""
+ @State private var showResetOnboardingAlert: Bool = false
+ @State private var activeFeatureHelp: FeatureHelp?
+ @State private var suppressCredentialPersist: Bool = false
+
private let gatewayLogger = Logger(subsystem: "ai.openclaw.ios", category: "GatewaySettings")
var body: some View {
@@ -103,7 +120,6 @@ struct SettingsTab: View {
.foregroundStyle(.secondary)
}
- DisclosureGroup("Advanced") {
if self.appModel.gatewayServerName == nil {
LabeledContent("Discovery", value: self.gatewayController.discoveryStatusText)
}
@@ -148,69 +164,74 @@ struct SettingsTab: View {
self.gatewayList(showing: .all)
}
- Toggle("Use Manual Gateway", isOn: self.$manualGatewayEnabled)
+ DisclosureGroup("Advanced") {
+ Toggle("Use Manual Gateway", isOn: self.$manualGatewayEnabled)
- TextField("Host", text: self.$manualGatewayHost)
- .textInputAutocapitalization(.never)
- .autocorrectionDisabled()
+ TextField("Host", text: self.$manualGatewayHost)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
- TextField("Port (optional)", text: self.manualPortBinding)
- .keyboardType(.numberPad)
+ TextField("Port (optional)", text: self.manualPortBinding)
+ .keyboardType(.numberPad)
- Toggle("Use TLS", isOn: self.$manualGatewayTLS)
+ Toggle("Use TLS", isOn: self.$manualGatewayTLS)
- Button {
- Task { await self.connectManual() }
- } label: {
- if self.connectingGatewayID == "manual" {
- HStack(spacing: 8) {
- ProgressView()
- .progressViewStyle(.circular)
- Text("Connecting…")
+ Button {
+ Task { await self.connectManual() }
+ } label: {
+ if self.connectingGatewayID == "manual" {
+ HStack(spacing: 8) {
+ ProgressView()
+ .progressViewStyle(.circular)
+ Text("Connecting…")
+ }
+ } else {
+ Text("Connect (Manual)")
}
- } else {
- Text("Connect (Manual)")
}
- }
- .disabled(self.connectingGatewayID != nil || self.manualGatewayHost
- .trimmingCharacters(in: .whitespacesAndNewlines)
- .isEmpty || !self.manualPortIsValid)
+ .disabled(self.connectingGatewayID != nil || self.manualGatewayHost
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ .isEmpty || !self.manualPortIsValid)
- Text(
- "Use this when mDNS/Bonjour discovery is blocked. "
- + "Leave port empty for 443 on tailnet DNS (TLS) or 18789 otherwise.")
- .font(.footnote)
- .foregroundStyle(.secondary)
+ Text(
+ "Use this when mDNS/Bonjour discovery is blocked. "
+ + "Leave port empty for 443 on tailnet DNS (TLS) or 18789 otherwise.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+
+ Toggle("Discovery Debug Logs", isOn: self.$discoveryDebugLogsEnabled)
+ .onChange(of: self.discoveryDebugLogsEnabled) { _, newValue in
+ self.gatewayController.setDiscoveryDebugLoggingEnabled(newValue)
+ }
- Toggle("Discovery Debug Logs", isOn: self.$discoveryDebugLogsEnabled)
- .onChange(of: self.discoveryDebugLogsEnabled) { _, newValue in
- self.gatewayController.setDiscoveryDebugLoggingEnabled(newValue)
+ NavigationLink("Discovery Logs") {
+ GatewayDiscoveryDebugLogView()
}
- NavigationLink("Discovery Logs") {
- GatewayDiscoveryDebugLogView()
- }
+ Toggle("Debug Canvas Status", isOn: self.$canvasDebugStatusEnabled)
- Toggle("Debug Canvas Status", isOn: self.$canvasDebugStatusEnabled)
+ TextField("Gateway Auth Token", text: self.$gatewayToken)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
- TextField("Gateway Token", text: self.$gatewayToken)
- .textInputAutocapitalization(.never)
- .autocorrectionDisabled()
+ SecureField("Gateway Password", text: self.$gatewayPassword)
- SecureField("Gateway Password", text: self.$gatewayPassword)
+ Button("Reset Onboarding", role: .destructive) {
+ self.showResetOnboardingAlert = true
+ }
- VStack(alignment: .leading, spacing: 6) {
- Text("Debug")
- .font(.footnote.weight(.semibold))
- .foregroundStyle(.secondary)
- Text(self.gatewayDebugText())
- .font(.system(size: 12, weight: .regular, design: .monospaced))
- .foregroundStyle(.secondary)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(10)
- .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 10, style: .continuous))
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Debug")
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(.secondary)
+ Text(self.gatewayDebugText())
+ .font(.system(size: 12, weight: .regular, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(10)
+ .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 10, style: .continuous))
+ }
}
- }
} label: {
HStack(spacing: 10) {
Circle()
@@ -227,16 +248,22 @@ struct SettingsTab: View {
Section("Device") {
DisclosureGroup("Features") {
- Toggle("Voice Wake", isOn: self.$voiceWakeEnabled)
- .onChange(of: self.voiceWakeEnabled) { _, newValue in
+ self.featureToggle(
+ "Voice Wake",
+ isOn: self.$voiceWakeEnabled,
+ help: "Enables wake-word activation to start a hands-free session.") { newValue in
self.appModel.setVoiceWakeEnabled(newValue)
}
- Toggle("Talk Mode", isOn: self.$talkEnabled)
- .onChange(of: self.talkEnabled) { _, newValue in
+ self.featureToggle(
+ "Talk Mode",
+ isOn: self.$talkEnabled,
+ help: "Enables voice conversation mode with your connected OpenClaw agent.") { newValue in
self.appModel.setTalkEnabled(newValue)
}
- // Keep this separate so users can hide the side bubble without disabling Talk Mode.
- Toggle("Show Talk Button", isOn: self.$talkButtonEnabled)
+ self.featureToggle(
+ "Background Listening",
+ isOn: self.$talkBackgroundEnabled,
+ help: "Keeps listening while the app is backgrounded. Uses more battery.")
NavigationLink {
VoiceWakeWordsSettingsView()
@@ -246,29 +273,78 @@ struct SettingsTab: View {
value: VoiceWakePreferences.displayString(for: self.voiceWake.triggerWords))
}
- Toggle("Allow Camera", isOn: self.$cameraEnabled)
- Text("Allows the gateway to request photos or short video clips (foreground only).")
- .font(.footnote)
- .foregroundStyle(.secondary)
+ self.featureToggle(
+ "Allow Camera",
+ isOn: self.$cameraEnabled,
+ help: "Allows the gateway to request photos or short video clips while OpenClaw is foregrounded.")
+ HStack(spacing: 8) {
+ Text("Location Access")
+ Spacer()
+ Button {
+ self.activeFeatureHelp = FeatureHelp(
+ title: "Location Access",
+ message: "Controls location permissions for OpenClaw. Off disables location tools, While Using enables foreground location, and Always enables background location.")
+ } label: {
+ Image(systemName: "info.circle")
+ .foregroundStyle(.secondary)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Location Access info")
+ }
Picker("Location Access", selection: self.$locationEnabledModeRaw) {
Text("Off").tag(OpenClawLocationMode.off.rawValue)
Text("While Using").tag(OpenClawLocationMode.whileUsing.rawValue)
Text("Always").tag(OpenClawLocationMode.always.rawValue)
}
+ .labelsHidden()
.pickerStyle(.segmented)
- Toggle("Precise Location", isOn: self.$locationPreciseEnabled)
- .disabled(self.locationMode == .off)
+ self.featureToggle(
+ "Prevent Sleep",
+ isOn: self.$preventSleep,
+ help: "Keeps the screen awake while OpenClaw is open.")
- Text("Always requires system permission and may prompt to open Settings.")
- .font(.footnote)
- .foregroundStyle(.secondary)
+ DisclosureGroup("Advanced") {
+ self.featureToggle(
+ "Voice Directive Hint",
+ isOn: self.$talkVoiceDirectiveHintEnabled,
+ help: "Adds voice-switching instructions to Talk prompts. Disable to reduce prompt size.")
+ self.featureToggle(
+ "Show Talk Button",
+ isOn: self.$talkButtonEnabled,
+ help: "Shows the floating Talk button in the main interface.")
+ TextField("Default Share Instruction", text: self.$defaultShareInstruction, axis: .vertical)
+ .lineLimit(2 ... 6)
+ .textInputAutocapitalization(.sentences)
+ HStack(spacing: 8) {
+ Text("Default Share Instruction")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ Spacer()
+ Button {
+ self.activeFeatureHelp = FeatureHelp(
+ title: "Default Share Instruction",
+ message: "Appends this instruction when sharing content into OpenClaw from iOS.")
+ } label: {
+ Image(systemName: "info.circle")
+ .foregroundStyle(.secondary)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Default Share Instruction info")
+ }
- Toggle("Prevent Sleep", isOn: self.$preventSleep)
- Text("Keeps the screen awake while OpenClaw is open.")
- .font(.footnote)
- .foregroundStyle(.secondary)
+ VStack(alignment: .leading, spacing: 8) {
+ Button {
+ Task { await self.appModel.runSharePipelineSelfTest() }
+ } label: {
+ Label("Run Share Self-Test", systemImage: "checkmark.seal")
+ }
+ Text(self.appModel.lastShareEventText)
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+ }
}
DisclosureGroup("Device Info") {
@@ -276,19 +352,11 @@ struct SettingsTab: View {
Text(self.instanceId)
.font(.footnote)
.foregroundStyle(.secondary)
- LabeledContent("IP", value: self.localIPAddress ?? "—")
- .contextMenu {
- if let ip = self.localIPAddress {
- Button {
- UIPasteboard.general.string = ip
- } label: {
- Label("Copy", systemImage: "doc.on.doc")
- }
- }
- }
+ .lineLimit(1)
+ .truncationMode(.middle)
+ LabeledContent("Device", value: self.deviceFamily())
LabeledContent("Platform", value: self.platformString())
- LabeledContent("Version", value: self.appVersion())
- LabeledContent("Model", value: self.modelIdentifier())
+ LabeledContent("OpenClaw", value: self.openClawVersionString())
}
}
}
@@ -303,8 +371,22 @@ struct SettingsTab: View {
.accessibilityLabel("Close")
}
}
+ .alert("Reset Onboarding?", isPresented: self.$showResetOnboardingAlert) {
+ Button("Reset", role: .destructive) {
+ self.resetOnboarding()
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text(
+ "This will disconnect, clear saved gateway connection + credentials, and reopen the onboarding wizard.")
+ }
+ .alert(item: self.$activeFeatureHelp) { help in
+ Alert(
+ title: Text(help.title),
+ message: Text(help.message),
+ dismissButton: .default(Text("OK")))
+ }
.onAppear {
- self.localIPAddress = Self.primaryIPv4Address()
self.lastLocationModeRaw = self.locationEnabledModeRaw
self.syncManualPortText()
let trimmedInstanceId = self.instanceId.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -312,6 +394,8 @@ struct SettingsTab: View {
self.gatewayToken = GatewaySettingsStore.loadGatewayToken(instanceId: trimmedInstanceId) ?? ""
self.gatewayPassword = GatewaySettingsStore.loadGatewayPassword(instanceId: trimmedInstanceId) ?? ""
}
+ self.defaultShareInstruction = ShareToAgentSettings.loadDefaultInstruction()
+ self.appModel.refreshLastShareEventFromRelay()
// Keep setup front-and-center when disconnected; keep things compact once connected.
self.gatewayExpanded = !self.isGatewayConnected
self.selectedAgentPickerId = self.appModel.selectedAgentId ?? ""
@@ -331,17 +415,22 @@ struct SettingsTab: View {
GatewaySettingsStore.savePreferredGatewayStableID(trimmed)
}
.onChange(of: self.gatewayToken) { _, newValue in
+ guard !self.suppressCredentialPersist else { return }
let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
let instanceId = self.instanceId.trimmingCharacters(in: .whitespacesAndNewlines)
guard !instanceId.isEmpty else { return }
GatewaySettingsStore.saveGatewayToken(trimmed, instanceId: instanceId)
}
.onChange(of: self.gatewayPassword) { _, newValue in
+ guard !self.suppressCredentialPersist else { return }
let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
let instanceId = self.instanceId.trimmingCharacters(in: .whitespacesAndNewlines)
guard !instanceId.isEmpty else { return }
GatewaySettingsStore.saveGatewayPassword(trimmed, instanceId: instanceId)
}
+ .onChange(of: self.defaultShareInstruction) { _, newValue in
+ ShareToAgentSettings.saveDefaultInstruction(newValue)
+ }
.onChange(of: self.manualGatewayPort) { _, _ in
self.syncManualPortText()
}
@@ -421,10 +510,11 @@ struct SettingsTab: View {
ForEach(rows) { gateway in
HStack {
VStack(alignment: .leading, spacing: 2) {
- Text(gateway.name)
+ // Avoid localized-string formatting edge cases from Bonjour-advertised names.
+ Text(verbatim: gateway.name)
let detailLines = self.gatewayDetailLines(gateway)
ForEach(detailLines, id: \.self) { line in
- Text(line)
+ Text(verbatim: line)
.font(.footnote)
.foregroundStyle(.secondary)
}
@@ -472,14 +562,6 @@ struct SettingsTab: View {
return "iOS \(v.majorVersion).\(v.minorVersion).\(v.patchVersion)"
}
- private var locationMode: OpenClawLocationMode {
- OpenClawLocationMode(rawValue: self.locationEnabledModeRaw) ?? .off
- }
-
- private func appVersion() -> String {
- Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev"
- }
-
private func deviceFamily() -> String {
switch UIDevice.current.userInterfaceIdiom {
case .pad:
@@ -491,14 +573,36 @@ struct SettingsTab: View {
}
}
- private func modelIdentifier() -> String {
- var systemInfo = utsname()
- uname(&systemInfo)
- let machine = withUnsafeBytes(of: &systemInfo.machine) { ptr in
- String(bytes: ptr.prefix { $0 != 0 }, encoding: .utf8)
+ private func openClawVersionString() -> String {
+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev"
+ let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? ""
+ let trimmedBuild = build.trimmingCharacters(in: .whitespacesAndNewlines)
+ if trimmedBuild.isEmpty || trimmedBuild == version {
+ return version
+ }
+ return "\(version) (\(trimmedBuild))"
+ }
+
+ private func featureToggle(
+ _ title: String,
+ isOn: Binding,
+ help: String,
+ onChange: ((Bool) -> Void)? = nil
+ ) -> some View {
+ HStack(spacing: 8) {
+ Toggle(title, isOn: isOn)
+ Button {
+ self.activeFeatureHelp = FeatureHelp(title: title, message: help)
+ } label: {
+ Image(systemName: "info.circle")
+ .foregroundStyle(.secondary)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("\(title) info")
+ }
+ .onChange(of: isOn.wrappedValue) { _, newValue in
+ onChange?(newValue)
}
- let trimmed = machine?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
- return trimmed.isEmpty ? "unknown" : trimmed
}
private func connect(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) async {
@@ -510,7 +614,10 @@ struct SettingsTab: View {
GatewaySettingsStore.saveLastDiscoveredGatewayStableID(gateway.stableID)
defer { self.connectingGatewayID = nil }
- await self.gatewayController.connect(gateway)
+ let err = await self.gatewayController.connectWithDiagnostics(gateway)
+ if let err {
+ self.setupStatusText = err
+ }
}
private func connectLastKnown() async {
@@ -590,15 +697,6 @@ struct SettingsTab: View {
}
}
- private struct SetupPayload: Codable {
- var url: String?
- var host: String?
- var port: Int?
- var tls: Bool?
- var token: String?
- var password: String?
- }
-
private func applySetupCodeAndConnect() async {
self.setupStatusText = nil
guard self.applySetupCode() else { return }
@@ -626,7 +724,7 @@ struct SettingsTab: View {
return false
}
- guard let payload = self.decodeSetupPayload(raw: raw) else {
+ guard let payload = GatewaySetupCode.decode(raw: raw) else {
self.setupStatusText = "Setup code not recognized."
return false
}
@@ -727,67 +825,14 @@ struct SettingsTab: View {
}
private static func probeTCP(host: String, port: Int, timeoutSeconds: Double) async -> Bool {
- guard let nwPort = NWEndpoint.Port(rawValue: UInt16(port)) else { return false }
- let endpointHost = NWEndpoint.Host(host)
- let connection = NWConnection(host: endpointHost, port: nwPort, using: .tcp)
- return await withCheckedContinuation { cont in
- let queue = DispatchQueue(label: "gateway.preflight")
- let finished = OSAllocatedUnfairLock(initialState: false)
- let finish: @Sendable (Bool) -> Void = { ok in
- let shouldResume = finished.withLock { flag -> Bool in
- if flag { return false }
- flag = true
- return true
- }
- guard shouldResume else { return }
- connection.cancel()
- cont.resume(returning: ok)
- }
- connection.stateUpdateHandler = { state in
- switch state {
- case .ready:
- finish(true)
- case .failed, .cancelled:
- finish(false)
- default:
- break
- }
- }
- connection.start(queue: queue)
- queue.asyncAfter(deadline: .now() + timeoutSeconds) {
- finish(false)
- }
- }
- }
-
- private func decodeSetupPayload(raw: String) -> SetupPayload? {
- if let payload = decodeSetupPayloadFromJSON(raw) {
- return payload
- }
- if let decoded = decodeBase64Payload(raw),
- let payload = decodeSetupPayloadFromJSON(decoded)
- {
- return payload
- }
- return nil
- }
-
- private func decodeSetupPayloadFromJSON(_ json: String) -> SetupPayload? {
- guard let data = json.data(using: .utf8) else { return nil }
- return try? JSONDecoder().decode(SetupPayload.self, from: data)
+ await TCPProbe.probe(
+ host: host,
+ port: port,
+ timeoutSeconds: timeoutSeconds,
+ queueLabel: "gateway.preflight")
}
- private func decodeBase64Payload(_ raw: String) -> String? {
- let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else { return nil }
- let normalized = trimmed
- .replacingOccurrences(of: "-", with: "+")
- .replacingOccurrences(of: "_", with: "/")
- let padding = normalized.count % 4
- let padded = padding == 0 ? normalized : normalized + String(repeating: "=", count: 4 - padding)
- guard let data = Data(base64Encoded: padded) else { return nil }
- return String(data: data, encoding: .utf8)
- }
+ // (GatewaySetupCode) decode raw setup codes.
private func connectManual() async {
let host = self.manualGatewayHost.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -852,44 +897,6 @@ struct SettingsTab: View {
return nil
}
- private static func primaryIPv4Address() -> String? {
- var addrList: UnsafeMutablePointer?
- guard getifaddrs(&addrList) == 0, let first = addrList else { return nil }
- defer { freeifaddrs(addrList) }
-
- var fallback: String?
- var en0: String?
-
- for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) {
- let flags = Int32(ptr.pointee.ifa_flags)
- let isUp = (flags & IFF_UP) != 0
- let isLoopback = (flags & IFF_LOOPBACK) != 0
- let name = String(cString: ptr.pointee.ifa_name)
- let family = ptr.pointee.ifa_addr.pointee.sa_family
- if !isUp || isLoopback || family != UInt8(AF_INET) { continue }
-
- var addr = ptr.pointee.ifa_addr.pointee
- var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
- let result = getnameinfo(
- &addr,
- socklen_t(ptr.pointee.ifa_addr.pointee.sa_len),
- &buffer,
- socklen_t(buffer.count),
- nil,
- 0,
- NI_NUMERICHOST)
- guard result == 0 else { continue }
- let len = buffer.prefix { $0 != 0 }
- let bytes = len.map { UInt8(bitPattern: $0) }
- guard let ip = String(bytes: bytes, encoding: .utf8) else { continue }
-
- if name == "en0" { en0 = ip; break }
- if fallback == nil { fallback = ip }
- }
-
- return en0 ?? fallback
- }
-
private static func hasTailnetIPv4() -> Bool {
var addrList: UnsafeMutablePointer?
guard getifaddrs(&addrList) == 0, let first = addrList else { return false }
@@ -949,6 +956,43 @@ struct SettingsTab: View {
SettingsNetworkingHelpers.httpURLString(host: host, port: port, fallback: fallback)
}
+ private func resetOnboarding() {
+ // Disconnect first so RootCanvas doesn't instantly mark onboarding complete again.
+ self.appModel.disconnectGateway()
+ self.connectingGatewayID = nil
+ self.setupStatusText = nil
+ self.setupCode = ""
+ self.gatewayAutoConnect = false
+
+ self.suppressCredentialPersist = true
+ defer { self.suppressCredentialPersist = false }
+
+ self.gatewayToken = ""
+ self.gatewayPassword = ""
+
+ let trimmedInstanceId = self.instanceId.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmedInstanceId.isEmpty {
+ GatewaySettingsStore.deleteGatewayCredentials(instanceId: trimmedInstanceId)
+ }
+
+ // Reset onboarding state + clear saved gateway connection (the two things RootCanvas checks).
+ GatewaySettingsStore.clearLastGatewayConnection()
+
+ // RootCanvas also short-circuits onboarding when these are true.
+ self.onboardingComplete = false
+ self.hasConnectedOnce = false
+
+ // Clear manual override so it doesn't count as an existing gateway config.
+ self.manualGatewayEnabled = false
+ self.manualGatewayHost = ""
+
+ // Force re-present even without app restart.
+ self.onboardingRequestID += 1
+
+ // The onboarding wizard is presented from RootCanvas; dismiss Settings so it can show.
+ self.dismiss()
+ }
+
private func gatewayDetailLines(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) -> [String] {
var lines: [String] = []
if let lanHost = gateway.lanHost { lines.append("LAN: \(lanHost)") }
diff --git a/apps/ios/Sources/Status/StatusActivityBuilder.swift b/apps/ios/Sources/Status/StatusActivityBuilder.swift
new file mode 100644
index 0000000000000..381b3d2b9e8a8
--- /dev/null
+++ b/apps/ios/Sources/Status/StatusActivityBuilder.swift
@@ -0,0 +1,71 @@
+import SwiftUI
+
+enum StatusActivityBuilder {
+ @MainActor
+ static func build(
+ appModel: NodeAppModel,
+ voiceWakeEnabled: Bool,
+ cameraHUDText: String?,
+ cameraHUDKind: NodeAppModel.CameraHUDKind?
+ ) -> StatusPill.Activity? {
+ // Keep the top pill consistent across tabs (camera + voice wake + pairing states).
+ if appModel.isBackgrounded {
+ return StatusPill.Activity(
+ title: "Foreground required",
+ systemImage: "exclamationmark.triangle.fill",
+ tint: .orange)
+ }
+
+ let gatewayStatus = appModel.gatewayStatusText.trimmingCharacters(in: .whitespacesAndNewlines)
+ let gatewayLower = gatewayStatus.lowercased()
+ if gatewayLower.contains("repair") {
+ return StatusPill.Activity(title: "Repairing…", systemImage: "wrench.and.screwdriver", tint: .orange)
+ }
+ if gatewayLower.contains("approval") || gatewayLower.contains("pairing") {
+ return StatusPill.Activity(title: "Approval pending", systemImage: "person.crop.circle.badge.clock")
+ }
+ // Avoid duplicating the primary gateway status ("Connecting…") in the activity slot.
+
+ if appModel.screenRecordActive {
+ return StatusPill.Activity(title: "Recording screen…", systemImage: "record.circle.fill", tint: .red)
+ }
+
+ if let cameraHUDText, !cameraHUDText.isEmpty, let cameraHUDKind {
+ let systemImage: String
+ let tint: Color?
+ switch cameraHUDKind {
+ case .photo:
+ systemImage = "camera.fill"
+ tint = nil
+ case .recording:
+ systemImage = "video.fill"
+ tint = .red
+ case .success:
+ systemImage = "checkmark.circle.fill"
+ tint = .green
+ case .error:
+ systemImage = "exclamationmark.triangle.fill"
+ tint = .red
+ }
+ return StatusPill.Activity(title: cameraHUDText, systemImage: systemImage, tint: tint)
+ }
+
+ if voiceWakeEnabled {
+ let voiceStatus = appModel.voiceWake.statusText
+ if voiceStatus.localizedCaseInsensitiveContains("microphone permission") {
+ return StatusPill.Activity(title: "Mic permission", systemImage: "mic.slash", tint: .orange)
+ }
+ if voiceStatus == "Paused" {
+ // Talk mode intentionally pauses voice wake to release the mic. Don't spam the HUD for that case.
+ if appModel.talkMode.isEnabled {
+ return nil
+ }
+ let suffix = appModel.isBackgrounded ? " (background)" : ""
+ return StatusPill.Activity(title: "Voice Wake paused\(suffix)", systemImage: "pause.circle.fill")
+ }
+ }
+
+ return nil
+ }
+}
+
diff --git a/apps/ios/Sources/Status/StatusPill.swift b/apps/ios/Sources/Status/StatusPill.swift
index cd81c011bb1da..ea5e425c49d4c 100644
--- a/apps/ios/Sources/Status/StatusPill.swift
+++ b/apps/ios/Sources/Status/StatusPill.swift
@@ -2,6 +2,8 @@ import SwiftUI
struct StatusPill: View {
@Environment(\.scenePhase) private var scenePhase
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.colorSchemeContrast) private var contrast
enum GatewayState: Equatable {
case connected
@@ -49,11 +51,11 @@ struct StatusPill: View {
Circle()
.fill(self.gateway.color)
.frame(width: 9, height: 9)
- .scaleEffect(self.gateway == .connecting ? (self.pulse ? 1.15 : 0.85) : 1.0)
- .opacity(self.gateway == .connecting ? (self.pulse ? 1.0 : 0.6) : 1.0)
+ .scaleEffect(self.gateway == .connecting && !self.reduceMotion ? (self.pulse ? 1.15 : 0.85) : 1.0)
+ .opacity(self.gateway == .connecting && !self.reduceMotion ? (self.pulse ? 1.0 : 0.6) : 1.0)
Text(self.gateway.title)
- .font(.system(size: 13, weight: .semibold))
+ .font(.subheadline.weight(.semibold))
.foregroundStyle(.primary)
}
@@ -64,17 +66,17 @@ struct StatusPill: View {
if let activity {
HStack(spacing: 6) {
Image(systemName: activity.systemImage)
- .font(.system(size: 13, weight: .semibold))
+ .font(.subheadline.weight(.semibold))
.foregroundStyle(activity.tint ?? .primary)
Text(activity.title)
- .font(.system(size: 13, weight: .semibold))
+ .font(.subheadline.weight(.semibold))
.foregroundStyle(.primary)
.lineLimit(1)
}
.transition(.opacity.combined(with: .move(edge: .top)))
} else {
Image(systemName: self.voiceWakeEnabled ? "mic.fill" : "mic.slash")
- .font(.system(size: 13, weight: .semibold))
+ .font(.subheadline.weight(.semibold))
.foregroundStyle(self.voiceWakeEnabled ? .primary : .secondary)
.accessibilityLabel(self.voiceWakeEnabled ? "Voice Wake enabled" : "Voice Wake disabled")
.transition(.opacity.combined(with: .move(edge: .top)))
@@ -87,21 +89,28 @@ struct StatusPill: View {
.fill(.ultraThinMaterial)
.overlay {
RoundedRectangle(cornerRadius: 14, style: .continuous)
- .strokeBorder(.white.opacity(self.brighten ? 0.24 : 0.18), lineWidth: 0.5)
+ .strokeBorder(
+ .white.opacity(self.contrast == .increased ? 0.5 : (self.brighten ? 0.24 : 0.18)),
+ lineWidth: self.contrast == .increased ? 1.0 : 0.5
+ )
}
.shadow(color: .black.opacity(0.25), radius: 12, y: 6)
}
}
.buttonStyle(.plain)
- .accessibilityLabel("Status")
+ .accessibilityLabel("Connection Status")
.accessibilityValue(self.accessibilityValue)
- .onAppear { self.updatePulse(for: self.gateway, scenePhase: self.scenePhase) }
+ .accessibilityHint("Double tap to open settings")
+ .onAppear { self.updatePulse(for: self.gateway, scenePhase: self.scenePhase, reduceMotion: self.reduceMotion) }
.onDisappear { self.pulse = false }
.onChange(of: self.gateway) { _, newValue in
- self.updatePulse(for: newValue, scenePhase: self.scenePhase)
+ self.updatePulse(for: newValue, scenePhase: self.scenePhase, reduceMotion: self.reduceMotion)
}
.onChange(of: self.scenePhase) { _, newValue in
- self.updatePulse(for: self.gateway, scenePhase: newValue)
+ self.updatePulse(for: self.gateway, scenePhase: newValue, reduceMotion: self.reduceMotion)
+ }
+ .onChange(of: self.reduceMotion) { _, newValue in
+ self.updatePulse(for: self.gateway, scenePhase: self.scenePhase, reduceMotion: newValue)
}
.animation(.easeInOut(duration: 0.18), value: self.activity?.title)
}
@@ -113,9 +122,9 @@ struct StatusPill: View {
return "\(self.gateway.title), Voice Wake \(self.voiceWakeEnabled ? "enabled" : "disabled")"
}
- private func updatePulse(for gateway: GatewayState, scenePhase: ScenePhase) {
- guard gateway == .connecting, scenePhase == .active else {
- withAnimation(.easeOut(duration: 0.2)) { self.pulse = false }
+ private func updatePulse(for gateway: GatewayState, scenePhase: ScenePhase, reduceMotion: Bool) {
+ guard gateway == .connecting, scenePhase == .active, !reduceMotion else {
+ withAnimation(reduceMotion ? .none : .easeOut(duration: 0.2)) { self.pulse = false }
return
}
diff --git a/apps/ios/Sources/Status/VoiceWakeToast.swift b/apps/ios/Sources/Status/VoiceWakeToast.swift
index b7942f2036f5a..ef6fc1295a76e 100644
--- a/apps/ios/Sources/Status/VoiceWakeToast.swift
+++ b/apps/ios/Sources/Status/VoiceWakeToast.swift
@@ -1,17 +1,19 @@
import SwiftUI
struct VoiceWakeToast: View {
+ @Environment(\.colorSchemeContrast) private var contrast
+
var command: String
var brighten: Bool = false
var body: some View {
HStack(spacing: 10) {
Image(systemName: "mic.fill")
- .font(.system(size: 14, weight: .semibold))
+ .font(.subheadline.weight(.semibold))
.foregroundStyle(.primary)
Text(self.command)
- .font(.system(size: 14, weight: .semibold))
+ .font(.subheadline.weight(.semibold))
.foregroundStyle(.primary)
.lineLimit(1)
.truncationMode(.tail)
@@ -23,11 +25,14 @@ struct VoiceWakeToast: View {
.fill(.ultraThinMaterial)
.overlay {
RoundedRectangle(cornerRadius: 14, style: .continuous)
- .strokeBorder(.white.opacity(self.brighten ? 0.24 : 0.18), lineWidth: 0.5)
+ .strokeBorder(
+ .white.opacity(self.contrast == .increased ? 0.5 : (self.brighten ? 0.24 : 0.18)),
+ lineWidth: self.contrast == .increased ? 1.0 : 0.5
+ )
}
.shadow(color: .black.opacity(0.25), radius: 12, y: 6)
}
- .accessibilityLabel("Voice Wake")
- .accessibilityValue(self.command)
+ .accessibilityLabel("Voice Wake triggered")
+ .accessibilityValue("Command: \(self.command)")
}
}
diff --git a/apps/ios/Sources/Voice/TalkModeManager.swift b/apps/ios/Sources/Voice/TalkModeManager.swift
index 8351a6d5f9ad0..be90208af4788 100644
--- a/apps/ios/Sources/Voice/TalkModeManager.swift
+++ b/apps/ios/Sources/Voice/TalkModeManager.swift
@@ -16,6 +16,7 @@ import Speech
final class TalkModeManager: NSObject {
private typealias SpeechRequest = SFSpeechAudioBufferRecognitionRequest
private static let defaultModelIdFallback = "eleven_v3"
+ private static let redactedConfigSentinel = "__OPENCLAW_REDACTED__"
var isEnabled: Bool = false
var isListening: Bool = false
var isSpeaking: Bool = false
@@ -218,8 +219,12 @@ final class TalkModeManager: NSObject {
/// Suspends microphone usage without disabling Talk Mode.
/// Used when the app backgrounds (or when we need to temporarily release the mic).
- func suspendForBackground() -> Bool {
+ func suspendForBackground(keepActive: Bool = false) -> Bool {
guard self.isEnabled else { return false }
+ if keepActive {
+ self.statusText = self.isListening ? "Listening" : self.statusText
+ return false
+ }
let wasActive = self.isListening || self.isSpeaking || self.isPushToTalkActive
self.isListening = false
@@ -246,7 +251,8 @@ final class TalkModeManager: NSObject {
return wasActive
}
- func resumeAfterBackground(wasSuspended: Bool) async {
+ func resumeAfterBackground(wasSuspended: Bool, wasKeptActive: Bool = false) async {
+ if wasKeptActive { return }
guard wasSuspended else { return }
guard self.isEnabled else { return }
await self.start()
@@ -814,29 +820,24 @@ final class TalkModeManager: NSObject {
private func subscribeChatIfNeeded(sessionKey: String) async {
let key = sessionKey.trimmingCharacters(in: .whitespacesAndNewlines)
guard !key.isEmpty else { return }
- guard let gateway else { return }
guard !self.chatSubscribedSessionKeys.contains(key) else { return }
- let payload = "{\"sessionKey\":\"\(key)\"}"
- await gateway.sendEvent(event: "chat.subscribe", payloadJSON: payload)
+ // Operator clients receive chat events without node-style subscriptions.
self.chatSubscribedSessionKeys.insert(key)
- self.logger.info("chat.subscribe ok sessionKey=\(key, privacy: .public)")
}
private func unsubscribeAllChats() async {
- guard let gateway else { return }
- let keys = self.chatSubscribedSessionKeys
self.chatSubscribedSessionKeys.removeAll()
- for key in keys {
- let payload = "{\"sessionKey\":\"\(key)\"}"
- await gateway.sendEvent(event: "chat.unsubscribe", payloadJSON: payload)
- }
}
private func buildPrompt(transcript: String) -> String {
let interrupted = self.lastInterruptedAtSeconds
self.lastInterruptedAtSeconds = nil
- return TalkPromptBuilder.build(transcript: transcript, interruptedAtSeconds: interrupted)
+ let includeVoiceDirectiveHint = (UserDefaults.standard.object(forKey: "talk.voiceDirectiveHint.enabled") as? Bool) ?? true
+ return TalkPromptBuilder.build(
+ transcript: transcript,
+ interruptedAtSeconds: interrupted,
+ includeVoiceDirectiveHint: includeVoiceDirectiveHint)
}
private enum ChatCompletionState: CustomStringConvertible {
@@ -1114,6 +1115,7 @@ final class TalkModeManager: NSObject {
}
private func shouldInterrupt(with transcript: String) -> Bool {
+ guard self.shouldAllowSpeechInterruptForCurrentRoute() else { return false }
let trimmed = transcript.trimmingCharacters(in: .whitespacesAndNewlines)
guard trimmed.count >= 3 else { return false }
if let spoken = self.lastSpokenText?.lowercased(), spoken.contains(trimmed.lowercased()) {
@@ -1122,6 +1124,20 @@ final class TalkModeManager: NSObject {
return true
}
+ private func shouldAllowSpeechInterruptForCurrentRoute() -> Bool {
+ let route = AVAudioSession.sharedInstance().currentRoute
+ // Built-in speaker/receiver often feeds TTS back into STT, causing false interrupts.
+ // Allow barge-in for isolated outputs (headphones/Bluetooth/USB/CarPlay/AirPlay).
+ return !route.outputs.contains { output in
+ switch output.portType {
+ case .builtInSpeaker, .builtInReceiver:
+ return true
+ default:
+ return false
+ }
+ }
+ }
+
private func shouldUseIncrementalTTS() -> Bool {
true
}
@@ -1668,6 +1684,15 @@ extension TalkModeManager {
return value.allSatisfy { $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" }
}
+ private static func normalizedTalkApiKey(_ raw: String?) -> String? {
+ let trimmed = (raw ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return nil }
+ guard trimmed != Self.redactedConfigSentinel else { return nil }
+ // Config values may be env placeholders (for example `${ELEVENLABS_API_KEY}`).
+ if trimmed.hasPrefix("${"), trimmed.hasSuffix("}") { return nil }
+ return trimmed
+ }
+
func reloadConfig() async {
guard let gateway else { return }
do {
@@ -1699,7 +1724,15 @@ extension TalkModeManager {
}
self.defaultOutputFormat = (talk?["outputFormat"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
- self.apiKey = (talk?["apiKey"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
+ let rawConfigApiKey = (talk?["apiKey"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
+ let configApiKey = Self.normalizedTalkApiKey(rawConfigApiKey)
+ let localApiKey = Self.normalizedTalkApiKey(GatewaySettingsStore.loadTalkElevenLabsApiKey())
+ if rawConfigApiKey == Self.redactedConfigSentinel {
+ self.apiKey = (localApiKey?.isEmpty == false) ? localApiKey : nil
+ GatewayDiagnostics.log("talk config apiKey redacted; using local override if present")
+ } else {
+ self.apiKey = (localApiKey?.isEmpty == false) ? localApiKey : configApiKey
+ }
if let interrupt = talk?["interruptOnSpeech"] as? Bool {
self.interruptOnSpeech = interrupt
}
diff --git a/apps/ios/Tests/DeepLinkParserTests.swift b/apps/ios/Tests/DeepLinkParserTests.swift
index 9a3d861873870..ea8b2a81203eb 100644
--- a/apps/ios/Tests/DeepLinkParserTests.swift
+++ b/apps/ios/Tests/DeepLinkParserTests.swift
@@ -76,4 +76,52 @@ import Testing
timeoutSeconds: nil,
key: nil)))
}
+
+ @Test func parseGatewayLinkParsesCommonFields() {
+ let url = URL(
+ string: "openclaw://gateway?host=openclaw.local&port=18789&tls=1&token=abc&password=def")!
+ #expect(
+ DeepLinkParser.parse(url) == .gateway(
+ .init(host: "openclaw.local", port: 18789, tls: true, token: "abc", password: "def")))
+ }
+
+ @Test func parseGatewaySetupCodeParsesBase64UrlPayload() {
+ let payload = #"{"url":"wss://gateway.example.com:443","token":"tok","password":"pw"}"#
+ let encoded = Data(payload.utf8)
+ .base64EncodedString()
+ .replacingOccurrences(of: "+", with: "-")
+ .replacingOccurrences(of: "/", with: "_")
+ .replacingOccurrences(of: "=", with: "")
+
+ let link = GatewayConnectDeepLink.fromSetupCode(encoded)
+
+ #expect(link == .init(
+ host: "gateway.example.com",
+ port: 443,
+ tls: true,
+ token: "tok",
+ password: "pw"))
+ }
+
+ @Test func parseGatewaySetupCodeRejectsInvalidInput() {
+ #expect(GatewayConnectDeepLink.fromSetupCode("not-a-valid-setup-code") == nil)
+ }
+
+ @Test func parseGatewaySetupCodeDefaultsTo443ForWssWithoutPort() {
+ let payload = #"{"url":"wss://gateway.example.com","token":"tok"}"#
+ let encoded = Data(payload.utf8)
+ .base64EncodedString()
+ .replacingOccurrences(of: "+", with: "-")
+ .replacingOccurrences(of: "/", with: "_")
+ .replacingOccurrences(of: "=", with: "")
+
+ let link = GatewayConnectDeepLink.fromSetupCode(encoded)
+
+ #expect(link == .init(
+ host: "gateway.example.com",
+ port: 443,
+ tls: true,
+ token: "tok",
+ password: nil))
+ }
}
diff --git a/apps/ios/Tests/GatewayConnectionControllerTests.swift b/apps/ios/Tests/GatewayConnectionControllerTests.swift
index 0d3bdbba0ee57..27e7aed7aea5d 100644
--- a/apps/ios/Tests/GatewayConnectionControllerTests.swift
+++ b/apps/ios/Tests/GatewayConnectionControllerTests.swift
@@ -76,4 +76,47 @@ private func withUserDefaults(_ updates: [String: Any?], _ body: () throws ->
#expect(commands.contains(OpenClawLocationCommand.get.rawValue))
}
}
+ @Test @MainActor func currentCommandsExcludeDangerousSystemExecCommands() {
+ withUserDefaults([
+ "node.instanceId": "ios-test",
+ "camera.enabled": true,
+ "location.enabledMode": OpenClawLocationMode.whileUsing.rawValue,
+ ]) {
+ let appModel = NodeAppModel()
+ let controller = GatewayConnectionController(appModel: appModel, startDiscovery: false)
+ let commands = Set(controller._test_currentCommands())
+
+ // iOS should expose notify, but not host shell/exec-approval commands.
+ #expect(commands.contains(OpenClawSystemCommand.notify.rawValue))
+ #expect(!commands.contains(OpenClawSystemCommand.run.rawValue))
+ #expect(!commands.contains(OpenClawSystemCommand.which.rawValue))
+ #expect(!commands.contains(OpenClawSystemCommand.execApprovalsGet.rawValue))
+ #expect(!commands.contains(OpenClawSystemCommand.execApprovalsSet.rawValue))
+ }
+ }
+
+ @Test @MainActor func loadLastConnectionReadsSavedValues() {
+ withUserDefaults([:]) {
+ GatewaySettingsStore.saveLastGatewayConnectionManual(
+ host: "gateway.example.com",
+ port: 443,
+ useTLS: true,
+ stableID: "manual|gateway.example.com|443")
+ let loaded = GatewaySettingsStore.loadLastGatewayConnection()
+ #expect(loaded == .manual(host: "gateway.example.com", port: 443, useTLS: true, stableID: "manual|gateway.example.com|443"))
+ }
+ }
+
+ @Test @MainActor func loadLastConnectionReturnsNilForInvalidData() {
+ withUserDefaults([
+ "gateway.last.kind": "manual",
+ "gateway.last.host": "",
+ "gateway.last.port": 0,
+ "gateway.last.tls": false,
+ "gateway.last.stableID": "manual|invalid|0",
+ ]) {
+ let loaded = GatewaySettingsStore.loadLastGatewayConnection()
+ #expect(loaded == nil)
+ }
+ }
}
diff --git a/apps/ios/Tests/GatewayConnectionIssueTests.swift b/apps/ios/Tests/GatewayConnectionIssueTests.swift
new file mode 100644
index 0000000000000..8eb63f268baea
--- /dev/null
+++ b/apps/ios/Tests/GatewayConnectionIssueTests.swift
@@ -0,0 +1,33 @@
+import Testing
+@testable import OpenClaw
+
+@Suite(.serialized) struct GatewayConnectionIssueTests {
+ @Test func detectsTokenMissing() {
+ let issue = GatewayConnectionIssue.detect(from: "unauthorized: gateway token missing")
+ #expect(issue == .tokenMissing)
+ #expect(issue.needsAuthToken)
+ }
+
+ @Test func detectsUnauthorized() {
+ let issue = GatewayConnectionIssue.detect(from: "Gateway error: unauthorized role")
+ #expect(issue == .unauthorized)
+ #expect(issue.needsAuthToken)
+ }
+
+ @Test func detectsPairingWithRequestId() {
+ let issue = GatewayConnectionIssue.detect(from: "pairing required (requestId: abc123)")
+ #expect(issue == .pairingRequired(requestId: "abc123"))
+ #expect(issue.needsPairing)
+ #expect(issue.requestId == "abc123")
+ }
+
+ @Test func detectsNetworkError() {
+ let issue = GatewayConnectionIssue.detect(from: "Gateway error: Connection refused")
+ #expect(issue == .network)
+ }
+
+ @Test func returnsNoneForBenignStatus() {
+ let issue = GatewayConnectionIssue.detect(from: "Connected")
+ #expect(issue == .none)
+ }
+}
diff --git a/apps/ios/Tests/Info.plist b/apps/ios/Tests/Info.plist
index 3c51da578a501..59d3478717363 100644
--- a/apps/ios/Tests/Info.plist
+++ b/apps/ios/Tests/Info.plist
@@ -15,10 +15,10 @@
CFBundleName$(PRODUCT_NAME)CFBundlePackageType
- BNDL
- CFBundleShortVersionString
- 2026.2.13
- CFBundleVersion
- 20260213
-
-
+ BNDL
+ CFBundleShortVersionString
+ 2026.2.19
+ CFBundleVersion
+ 20260219
+
+
diff --git a/apps/ios/Tests/NodeAppModelInvokeTests.swift b/apps/ios/Tests/NodeAppModelInvokeTests.swift
index 3041439399699..f5f40fc8b7cf8 100644
--- a/apps/ios/Tests/NodeAppModelInvokeTests.swift
+++ b/apps/ios/Tests/NodeAppModelInvokeTests.swift
@@ -29,6 +29,39 @@ private func withUserDefaults(_ updates: [String: Any?], _ body: () throws ->
return try body()
}
+@MainActor
+private final class MockWatchMessagingService: WatchMessagingServicing, @unchecked Sendable {
+ var currentStatus = WatchMessagingStatus(
+ supported: true,
+ paired: true,
+ appInstalled: true,
+ reachable: true,
+ activationState: "activated")
+ var nextSendResult = WatchNotificationSendResult(
+ deliveredImmediately: true,
+ queuedForDelivery: false,
+ transport: "sendMessage")
+ var sendError: Error?
+ var lastSent: (id: String, title: String, body: String, priority: OpenClawNotificationPriority?)?
+
+ func status() async -> WatchMessagingStatus {
+ self.currentStatus
+ }
+
+ func sendNotification(
+ id: String,
+ title: String,
+ body: String,
+ priority: OpenClawNotificationPriority?) async throws -> WatchNotificationSendResult
+ {
+ self.lastSent = (id: id, title: title, body: body, priority: priority)
+ if let sendError = self.sendError {
+ throw sendError
+ }
+ return self.nextSendResult
+ }
+}
+
@Suite(.serialized) struct NodeAppModelInvokeTests {
@Test @MainActor func decodeParamsFailsWithoutJSON() {
#expect(throws: Error.self) {
@@ -156,6 +189,96 @@ private func withUserDefaults(_ updates: [String: Any?], _ body: () throws ->
#expect(res.error?.code == .invalidRequest)
}
+ @Test @MainActor func handleInvokeWatchStatusReturnsServiceSnapshot() async throws {
+ let watchService = MockWatchMessagingService()
+ watchService.currentStatus = WatchMessagingStatus(
+ supported: true,
+ paired: true,
+ appInstalled: true,
+ reachable: false,
+ activationState: "inactive")
+ let appModel = NodeAppModel(watchMessagingService: watchService)
+ let req = BridgeInvokeRequest(id: "watch-status", command: OpenClawWatchCommand.status.rawValue)
+
+ let res = await appModel._test_handleInvoke(req)
+ #expect(res.ok == true)
+
+ let payloadData = try #require(res.payloadJSON?.data(using: .utf8))
+ let payload = try JSONDecoder().decode(OpenClawWatchStatusPayload.self, from: payloadData)
+ #expect(payload.supported == true)
+ #expect(payload.reachable == false)
+ #expect(payload.activationState == "inactive")
+ }
+
+ @Test @MainActor func handleInvokeWatchNotifyRoutesToWatchService() async throws {
+ let watchService = MockWatchMessagingService()
+ watchService.nextSendResult = WatchNotificationSendResult(
+ deliveredImmediately: false,
+ queuedForDelivery: true,
+ transport: "transferUserInfo")
+ let appModel = NodeAppModel(watchMessagingService: watchService)
+ let params = OpenClawWatchNotifyParams(
+ title: "OpenClaw",
+ body: "Meeting with Peter is at 4pm",
+ priority: .timeSensitive)
+ let paramsData = try JSONEncoder().encode(params)
+ let paramsJSON = String(decoding: paramsData, as: UTF8.self)
+ let req = BridgeInvokeRequest(
+ id: "watch-notify",
+ command: OpenClawWatchCommand.notify.rawValue,
+ paramsJSON: paramsJSON)
+
+ let res = await appModel._test_handleInvoke(req)
+ #expect(res.ok == true)
+ #expect(watchService.lastSent?.title == "OpenClaw")
+ #expect(watchService.lastSent?.body == "Meeting with Peter is at 4pm")
+ #expect(watchService.lastSent?.priority == .timeSensitive)
+
+ let payloadData = try #require(res.payloadJSON?.data(using: .utf8))
+ let payload = try JSONDecoder().decode(OpenClawWatchNotifyPayload.self, from: payloadData)
+ #expect(payload.deliveredImmediately == false)
+ #expect(payload.queuedForDelivery == true)
+ #expect(payload.transport == "transferUserInfo")
+ }
+
+ @Test @MainActor func handleInvokeWatchNotifyRejectsEmptyMessage() async throws {
+ let watchService = MockWatchMessagingService()
+ let appModel = NodeAppModel(watchMessagingService: watchService)
+ let params = OpenClawWatchNotifyParams(title: " ", body: "\n")
+ let paramsData = try JSONEncoder().encode(params)
+ let paramsJSON = String(decoding: paramsData, as: UTF8.self)
+ let req = BridgeInvokeRequest(
+ id: "watch-notify-empty",
+ command: OpenClawWatchCommand.notify.rawValue,
+ paramsJSON: paramsJSON)
+
+ let res = await appModel._test_handleInvoke(req)
+ #expect(res.ok == false)
+ #expect(res.error?.code == .invalidRequest)
+ #expect(watchService.lastSent == nil)
+ }
+
+ @Test @MainActor func handleInvokeWatchNotifyReturnsUnavailableOnDeliveryFailure() async throws {
+ let watchService = MockWatchMessagingService()
+ watchService.sendError = NSError(
+ domain: "watch",
+ code: 1,
+ userInfo: [NSLocalizedDescriptionKey: "WATCH_UNAVAILABLE: no paired Apple Watch"])
+ let appModel = NodeAppModel(watchMessagingService: watchService)
+ let params = OpenClawWatchNotifyParams(title: "OpenClaw", body: "Delivery check")
+ let paramsData = try JSONEncoder().encode(params)
+ let paramsJSON = String(decoding: paramsData, as: UTF8.self)
+ let req = BridgeInvokeRequest(
+ id: "watch-notify-fail",
+ command: OpenClawWatchCommand.notify.rawValue,
+ paramsJSON: paramsJSON)
+
+ let res = await appModel._test_handleInvoke(req)
+ #expect(res.ok == false)
+ #expect(res.error?.code == .unavailable)
+ #expect(res.error?.message.contains("WATCH_UNAVAILABLE") == true)
+ }
+
@Test @MainActor func handleDeepLinkSetsErrorWhenNotConnected() async {
let appModel = NodeAppModel()
let url = URL(string: "openclaw://agent?message=hello")!
diff --git a/apps/ios/Tests/OnboardingStateStoreTests.swift b/apps/ios/Tests/OnboardingStateStoreTests.swift
new file mode 100644
index 0000000000000..30c014647b684
--- /dev/null
+++ b/apps/ios/Tests/OnboardingStateStoreTests.swift
@@ -0,0 +1,57 @@
+import Foundation
+import Testing
+@testable import OpenClaw
+
+@Suite(.serialized) struct OnboardingStateStoreTests {
+ @Test @MainActor func shouldPresentWhenFreshAndDisconnected() {
+ let testDefaults = self.makeDefaults()
+ let defaults = testDefaults.defaults
+ defer { self.reset(testDefaults) }
+
+ let appModel = NodeAppModel()
+ appModel.gatewayServerName = nil
+ #expect(OnboardingStateStore.shouldPresentOnLaunch(appModel: appModel, defaults: defaults))
+ }
+
+ @Test @MainActor func doesNotPresentWhenConnected() {
+ let testDefaults = self.makeDefaults()
+ let defaults = testDefaults.defaults
+ defer { self.reset(testDefaults) }
+
+ let appModel = NodeAppModel()
+ appModel.gatewayServerName = "gateway"
+ #expect(!OnboardingStateStore.shouldPresentOnLaunch(appModel: appModel, defaults: defaults))
+ }
+
+ @Test @MainActor func markCompletedPersistsMode() {
+ let testDefaults = self.makeDefaults()
+ let defaults = testDefaults.defaults
+ defer { self.reset(testDefaults) }
+
+ let appModel = NodeAppModel()
+ appModel.gatewayServerName = nil
+
+ OnboardingStateStore.markCompleted(mode: .remoteDomain, defaults: defaults)
+ #expect(OnboardingStateStore.lastMode(defaults: defaults) == .remoteDomain)
+ #expect(!OnboardingStateStore.shouldPresentOnLaunch(appModel: appModel, defaults: defaults))
+
+ OnboardingStateStore.markIncomplete(defaults: defaults)
+ #expect(OnboardingStateStore.shouldPresentOnLaunch(appModel: appModel, defaults: defaults))
+ }
+
+ private struct TestDefaults {
+ var suiteName: String
+ var defaults: UserDefaults
+ }
+
+ private func makeDefaults() -> TestDefaults {
+ let suiteName = "OnboardingStateStoreTests.\(UUID().uuidString)"
+ return TestDefaults(
+ suiteName: suiteName,
+ defaults: UserDefaults(suiteName: suiteName) ?? .standard)
+ }
+
+ private func reset(_ defaults: TestDefaults) {
+ defaults.defaults.removePersistentDomain(forName: defaults.suiteName)
+ }
+}
diff --git a/apps/ios/Tests/ScreenControllerTests.swift b/apps/ios/Tests/ScreenControllerTests.swift
index 32c36acacb7b1..d0e47c84fb366 100644
--- a/apps/ios/Tests/ScreenControllerTests.swift
+++ b/apps/ios/Tests/ScreenControllerTests.swift
@@ -2,25 +2,38 @@ import Testing
import WebKit
@testable import OpenClaw
+@MainActor
+private func mountScreen(_ screen: ScreenController) throws -> (ScreenWebViewCoordinator, WKWebView) {
+ let coordinator = ScreenWebViewCoordinator(controller: screen)
+ _ = coordinator.makeContainerView()
+ let webView = try #require(coordinator.managedWebView)
+ return (coordinator, webView)
+}
+
@Suite struct ScreenControllerTests {
- @Test @MainActor func canvasModeConfiguresWebViewForTouch() {
+ @Test @MainActor func canvasModeConfiguresWebViewForTouch() throws {
let screen = ScreenController()
+ let (coordinator, webView) = try mountScreen(screen)
+ defer { coordinator.teardown() }
- #expect(screen.webView.isOpaque == true)
- #expect(screen.webView.backgroundColor == .black)
+ #expect(webView.isOpaque == true)
+ #expect(webView.backgroundColor == .black)
- let scrollView = screen.webView.scrollView
+ let scrollView = webView.scrollView
#expect(scrollView.backgroundColor == .black)
#expect(scrollView.contentInsetAdjustmentBehavior == .never)
#expect(scrollView.isScrollEnabled == false)
#expect(scrollView.bounces == false)
}
- @Test @MainActor func navigateEnablesScrollForWebPages() {
+ @Test @MainActor func navigateEnablesScrollForWebPages() throws {
let screen = ScreenController()
+ let (coordinator, webView) = try mountScreen(screen)
+ defer { coordinator.teardown() }
+
screen.navigate(to: "https://example.com")
- let scrollView = screen.webView.scrollView
+ let scrollView = webView.scrollView
#expect(scrollView.isScrollEnabled == true)
#expect(scrollView.bounces == true)
}
@@ -34,6 +47,9 @@ import WebKit
@Test @MainActor func evalExecutesJavaScript() async throws {
let screen = ScreenController()
+ let (coordinator, _) = try mountScreen(screen)
+ defer { coordinator.teardown() }
+
let deadline = ContinuousClock().now.advanced(by: .seconds(3))
while true {
diff --git a/apps/ios/Tests/ShareToAgentDeepLinkTests.swift b/apps/ios/Tests/ShareToAgentDeepLinkTests.swift
new file mode 100644
index 0000000000000..4ea178ecfa291
--- /dev/null
+++ b/apps/ios/Tests/ShareToAgentDeepLinkTests.swift
@@ -0,0 +1,51 @@
+import OpenClawKit
+import Foundation
+import Testing
+
+@Suite struct ShareToAgentDeepLinkTests {
+ @Test func buildMessageIncludesSharedFields() {
+ let payload = SharedContentPayload(
+ title: "Article",
+ url: URL(string: "https://example.com/post")!,
+ text: "Read this")
+
+ let message = ShareToAgentDeepLink.buildMessage(
+ from: payload,
+ instruction: "Summarize and give next steps.")
+ #expect(message.contains("Shared from iOS."))
+ #expect(message.contains("Title: Article"))
+ #expect(message.contains("URL: https://example.com/post"))
+ #expect(message.contains("Text:\nRead this"))
+ #expect(message.contains("Summarize and give next steps."))
+ }
+
+ @Test func buildURLEncodesAgentRoute() {
+ let payload = SharedContentPayload(
+ title: "",
+ url: URL(string: "https://example.com")!,
+ text: nil)
+
+ let url = ShareToAgentDeepLink.buildURL(from: payload)
+ let parsed = url.flatMap { DeepLinkParser.parse($0) }
+ guard case let .agent(agent)? = parsed else {
+ Issue.record("Expected openclaw://agent deep link")
+ return
+ }
+
+ #expect(agent.thinking == "low")
+ #expect(agent.message.contains("https://example.com"))
+ }
+
+ @Test func buildURLReturnsNilWhenPayloadEmpty() {
+ let payload = SharedContentPayload(title: nil, url: nil, text: nil)
+ #expect(ShareToAgentDeepLink.buildURL(from: payload) == nil)
+ }
+
+ @Test func shareInstructionSettingsRoundTrip() {
+ let value = "Focus on booking constraints and alternatives."
+ ShareToAgentSettings.saveDefaultInstruction(value)
+ defer { ShareToAgentSettings.saveDefaultInstruction(nil) }
+
+ #expect(ShareToAgentSettings.loadDefaultInstruction() == value)
+ }
+}
diff --git a/apps/ios/WatchApp/Info.plist b/apps/ios/WatchApp/Info.plist
new file mode 100644
index 0000000000000..1ad5574ff829d
--- /dev/null
+++ b/apps/ios/WatchApp/Info.plist
@@ -0,0 +1,28 @@
+
+
+
+
+ CFBundleDevelopmentRegion
+ $(DEVELOPMENT_LANGUAGE)
+ CFBundleDisplayName
+ OpenClaw
+ CFBundleExecutable
+ $(EXECUTABLE_NAME)
+ CFBundleIdentifier
+ $(PRODUCT_BUNDLE_IDENTIFIER)
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ $(PRODUCT_NAME)
+ CFBundlePackageType
+ APPL
+ CFBundleShortVersionString
+ 2026.2.19
+ CFBundleVersion
+ 20260219
+ WKCompanionAppBundleIdentifier
+ $(OPENCLAW_APP_BUNDLE_ID)
+ WKWatchKitApp
+
+
+
diff --git a/apps/ios/WatchExtension/Info.plist b/apps/ios/WatchExtension/Info.plist
new file mode 100644
index 0000000000000..f1395e24b0383
--- /dev/null
+++ b/apps/ios/WatchExtension/Info.plist
@@ -0,0 +1,32 @@
+
+
+
+
+ CFBundleDevelopmentRegion
+ $(DEVELOPMENT_LANGUAGE)
+ CFBundleDisplayName
+ OpenClaw
+ CFBundleExecutable
+ $(EXECUTABLE_NAME)
+ CFBundleIdentifier
+ $(PRODUCT_BUNDLE_IDENTIFIER)
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ $(PRODUCT_NAME)
+ CFBundleShortVersionString
+ 2026.2.19
+ CFBundleVersion
+ 20260219
+ NSExtension
+
+ NSExtensionAttributes
+
+ WKAppBundleIdentifier
+ $(OPENCLAW_WATCH_APP_BUNDLE_ID)
+
+ NSExtensionPointIdentifier
+ com.apple.watchkit
+
+
+
diff --git a/apps/ios/WatchExtension/Sources/OpenClawWatchApp.swift b/apps/ios/WatchExtension/Sources/OpenClawWatchApp.swift
new file mode 100644
index 0000000000000..6084f5744422b
--- /dev/null
+++ b/apps/ios/WatchExtension/Sources/OpenClawWatchApp.swift
@@ -0,0 +1,20 @@
+import SwiftUI
+
+@main
+struct OpenClawWatchApp: App {
+ @State private var inboxStore = WatchInboxStore()
+ @State private var receiver: WatchConnectivityReceiver?
+
+ var body: some Scene {
+ WindowGroup {
+ WatchInboxView(store: self.inboxStore)
+ .task {
+ if self.receiver == nil {
+ let receiver = WatchConnectivityReceiver(store: self.inboxStore)
+ receiver.activate()
+ self.receiver = receiver
+ }
+ }
+ }
+ }
+}
diff --git a/apps/ios/WatchExtension/Sources/WatchConnectivityReceiver.swift b/apps/ios/WatchExtension/Sources/WatchConnectivityReceiver.swift
new file mode 100644
index 0000000000000..fd0d84cc55c80
--- /dev/null
+++ b/apps/ios/WatchExtension/Sources/WatchConnectivityReceiver.swift
@@ -0,0 +1,92 @@
+import Foundation
+import WatchConnectivity
+
+final class WatchConnectivityReceiver: NSObject, @unchecked Sendable {
+ private let store: WatchInboxStore
+ private let session: WCSession?
+
+ init(store: WatchInboxStore) {
+ self.store = store
+ if WCSession.isSupported() {
+ self.session = WCSession.default
+ } else {
+ self.session = nil
+ }
+ super.init()
+ }
+
+ func activate() {
+ guard let session = self.session else { return }
+ session.delegate = self
+ session.activate()
+ }
+
+ private static func parseNotificationPayload(_ payload: [String: Any]) -> WatchNotifyMessage? {
+ guard let type = payload["type"] as? String, type == "watch.notify" else {
+ return nil
+ }
+
+ let title = (payload["title"] as? String)?
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let body = (payload["body"] as? String)?
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+
+ guard title.isEmpty == false || body.isEmpty == false else {
+ return nil
+ }
+
+ let id = (payload["id"] as? String)?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let sentAtMs = (payload["sentAtMs"] as? Int) ?? (payload["sentAtMs"] as? NSNumber)?.intValue
+
+ return WatchNotifyMessage(
+ id: id,
+ title: title,
+ body: body,
+ sentAtMs: sentAtMs)
+ }
+}
+
+extension WatchConnectivityReceiver: WCSessionDelegate {
+ func session(
+ _: WCSession,
+ activationDidCompleteWith _: WCSessionActivationState,
+ error _: (any Error)?)
+ {}
+
+ func session(_: WCSession, didReceiveMessage message: [String: Any]) {
+ guard let incoming = Self.parseNotificationPayload(message) else { return }
+ Task { @MainActor in
+ self.store.consume(message: incoming, transport: "sendMessage")
+ }
+ }
+
+ func session(
+ _: WCSession,
+ didReceiveMessage message: [String: Any],
+ replyHandler: @escaping ([String: Any]) -> Void)
+ {
+ guard let incoming = Self.parseNotificationPayload(message) else {
+ replyHandler(["ok": false])
+ return
+ }
+ replyHandler(["ok": true])
+ Task { @MainActor in
+ self.store.consume(message: incoming, transport: "sendMessage")
+ }
+ }
+
+ func session(_: WCSession, didReceiveUserInfo userInfo: [String: Any]) {
+ guard let incoming = Self.parseNotificationPayload(userInfo) else { return }
+ Task { @MainActor in
+ self.store.consume(message: incoming, transport: "transferUserInfo")
+ }
+ }
+
+ func session(_: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
+ guard let incoming = Self.parseNotificationPayload(applicationContext) else { return }
+ Task { @MainActor in
+ self.store.consume(message: incoming, transport: "applicationContext")
+ }
+ }
+}
diff --git a/apps/ios/WatchExtension/Sources/WatchInboxStore.swift b/apps/ios/WatchExtension/Sources/WatchInboxStore.swift
new file mode 100644
index 0000000000000..0a715f16b63e0
--- /dev/null
+++ b/apps/ios/WatchExtension/Sources/WatchInboxStore.swift
@@ -0,0 +1,124 @@
+import Foundation
+import Observation
+import UserNotifications
+import WatchKit
+
+struct WatchNotifyMessage: Sendable {
+ var id: String?
+ var title: String
+ var body: String
+ var sentAtMs: Int?
+}
+
+@MainActor @Observable final class WatchInboxStore {
+ private struct PersistedState: Codable {
+ var title: String
+ var body: String
+ var transport: String
+ var updatedAt: Date
+ var lastDeliveryKey: String?
+ }
+
+ private static let persistedStateKey = "watch.inbox.state.v1"
+ private let defaults: UserDefaults
+
+ var title = "OpenClaw"
+ var body = "Waiting for messages from your iPhone."
+ var transport = "none"
+ var updatedAt: Date?
+ private var lastDeliveryKey: String?
+
+ init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ self.restorePersistedState()
+ Task {
+ await self.ensureNotificationAuthorization()
+ }
+ }
+
+ func consume(message: WatchNotifyMessage, transport: String) {
+ let messageID = message.id?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let deliveryKey = self.deliveryKey(
+ messageID: messageID,
+ title: message.title,
+ body: message.body,
+ sentAtMs: message.sentAtMs)
+ guard deliveryKey != self.lastDeliveryKey else { return }
+
+ let normalizedTitle = message.title.isEmpty ? "OpenClaw" : message.title
+ self.title = normalizedTitle
+ self.body = message.body
+ self.transport = transport
+ self.updatedAt = Date()
+ self.lastDeliveryKey = deliveryKey
+ self.persistState()
+
+ Task {
+ await self.postLocalNotification(
+ identifier: deliveryKey,
+ title: normalizedTitle,
+ body: message.body)
+ }
+ }
+
+ private func restorePersistedState() {
+ guard let data = self.defaults.data(forKey: Self.persistedStateKey),
+ let state = try? JSONDecoder().decode(PersistedState.self, from: data)
+ else {
+ return
+ }
+
+ self.title = state.title
+ self.body = state.body
+ self.transport = state.transport
+ self.updatedAt = state.updatedAt
+ self.lastDeliveryKey = state.lastDeliveryKey
+ }
+
+ private func persistState() {
+ guard let updatedAt = self.updatedAt else { return }
+ let state = PersistedState(
+ title: self.title,
+ body: self.body,
+ transport: self.transport,
+ updatedAt: updatedAt,
+ lastDeliveryKey: self.lastDeliveryKey)
+ guard let data = try? JSONEncoder().encode(state) else { return }
+ self.defaults.set(data, forKey: Self.persistedStateKey)
+ }
+
+ private func deliveryKey(messageID: String?, title: String, body: String, sentAtMs: Int?) -> String {
+ if let messageID, messageID.isEmpty == false {
+ return "id:\(messageID)"
+ }
+ return "content:\(title)|\(body)|\(sentAtMs ?? 0)"
+ }
+
+ private func ensureNotificationAuthorization() async {
+ let center = UNUserNotificationCenter.current()
+ let settings = await center.notificationSettings()
+ switch settings.authorizationStatus {
+ case .notDetermined:
+ _ = try? await center.requestAuthorization(options: [.alert, .sound])
+ default:
+ break
+ }
+ }
+
+ private func postLocalNotification(identifier: String, title: String, body: String) async {
+ let content = UNMutableNotificationContent()
+ content.title = title
+ content.body = body
+ content.sound = .default
+ content.threadIdentifier = "openclaw-watch"
+
+ let request = UNNotificationRequest(
+ identifier: identifier,
+ content: content,
+ trigger: UNTimeIntervalNotificationTrigger(timeInterval: 0.2, repeats: false))
+
+ _ = try? await UNUserNotificationCenter.current().add(request)
+ WKInterfaceDevice.current().play(.notification)
+ }
+}
diff --git a/apps/ios/WatchExtension/Sources/WatchInboxView.swift b/apps/ios/WatchExtension/Sources/WatchInboxView.swift
new file mode 100644
index 0000000000000..c5ea9a9f534d9
--- /dev/null
+++ b/apps/ios/WatchExtension/Sources/WatchInboxView.swift
@@ -0,0 +1,27 @@
+import SwiftUI
+
+struct WatchInboxView: View {
+ @Bindable var store: WatchInboxStore
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(store.title)
+ .font(.headline)
+ .lineLimit(2)
+
+ Text(store.body)
+ .font(.body)
+ .fixedSize(horizontal: false, vertical: true)
+
+ if let updatedAt = store.updatedAt {
+ Text("Updated \(updatedAt.formatted(date: .omitted, time: .shortened))")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding()
+ }
+ }
+}
diff --git a/apps/ios/fastlane/Fastfile b/apps/ios/fastlane/Fastfile
index b777c25c7a516..f1dbf6df18c6c 100644
--- a/apps/ios/fastlane/Fastfile
+++ b/apps/ios/fastlane/Fastfile
@@ -66,7 +66,8 @@ platform :ios do
if team_id.nil? || team_id.strip.empty?
helper_path = File.expand_path("../../scripts/ios-team-id.sh", __dir__)
if File.exist?(helper_path)
- team_id = sh("bash #{helper_path.shellescape}").strip
+ # Keep CI/local compatibility where teams are present in keychain but not Xcode account metadata.
+ team_id = sh("IOS_ALLOW_KEYCHAIN_TEAM_FALLBACK=1 bash #{helper_path.shellescape}").strip
end
end
UI.user_error!("Missing IOS_DEVELOPMENT_TEAM (Apple Team ID). Add it to fastlane/.env or export it in your shell.") if team_id.nil? || team_id.strip.empty?
diff --git a/apps/ios/fastlane/SETUP.md b/apps/ios/fastlane/SETUP.md
index 832f1ebc15bd7..930258fcc79fb 100644
--- a/apps/ios/fastlane/SETUP.md
+++ b/apps/ios/fastlane/SETUP.md
@@ -22,7 +22,7 @@ ASC_KEY_PATH=/absolute/path/to/AuthKey_XXXXXXXXXX.p8
IOS_DEVELOPMENT_TEAM=YOUR_TEAM_ID
```
-Tip: run `scripts/ios-team-id.sh` from the repo root to print a Team ID to paste into `.env`. Fastlane falls back to this helper if `IOS_DEVELOPMENT_TEAM` is missing.
+Tip: run `scripts/ios-team-id.sh` from the repo root to print a Team ID to paste into `.env`. The helper prefers the canonical OpenClaw team (`Y5PE65HELJ`) when present locally; otherwise it prefers the first non-personal team from your Xcode account (then personal team if needed). Fastlane uses this helper automatically if `IOS_DEVELOPMENT_TEAM` is missing.
Run:
diff --git a/apps/ios/project.yml b/apps/ios/project.yml
index c4342f8f22bcf..6c3713e65de0c 100644
--- a/apps/ios/project.yml
+++ b/apps/ios/project.yml
@@ -29,9 +29,15 @@ targets:
OpenClaw:
type: application
platform: iOS
+ configFiles:
+ Debug: Signing.xcconfig
+ Release: Signing.xcconfig
sources:
- path: Sources
dependencies:
+ - target: OpenClawShareExtension
+ embed: true
+ - target: OpenClawWatchApp
- package: OpenClawKit
- package: OpenClawKit
product: OpenClawChatUI
@@ -69,10 +75,11 @@ targets:
settings:
base:
CODE_SIGN_IDENTITY: "Apple Development"
- CODE_SIGN_STYLE: Manual
- DEVELOPMENT_TEAM: Y5PE65HELJ
- PRODUCT_BUNDLE_IDENTIFIER: ai.openclaw.ios
- PROVISIONING_PROFILE_SPECIFIER: "ai.openclaw.ios Development"
+ CODE_SIGN_ENTITLEMENTS: Sources/OpenClaw.entitlements
+ CODE_SIGN_STYLE: "$(OPENCLAW_CODE_SIGN_STYLE)"
+ DEVELOPMENT_TEAM: "$(OPENCLAW_DEVELOPMENT_TEAM)"
+ PRODUCT_BUNDLE_IDENTIFIER: "$(OPENCLAW_APP_BUNDLE_ID)"
+ PROVISIONING_PROFILE_SPECIFIER: "$(OPENCLAW_APP_PROFILE)"
SWIFT_VERSION: "6.0"
SWIFT_STRICT_CONCURRENCY: complete
ENABLE_APPINTENTS_METADATA: NO
@@ -81,13 +88,18 @@ targets:
properties:
CFBundleDisplayName: OpenClaw
CFBundleIconName: AppIcon
- CFBundleShortVersionString: "2026.2.13"
- CFBundleVersion: "20260213"
+ CFBundleURLTypes:
+ - CFBundleURLName: ai.openclaw.ios
+ CFBundleURLSchemes:
+ - openclaw
+ CFBundleShortVersionString: "2026.2.19"
+ CFBundleVersion: "20260219"
UILaunchScreen: {}
UIApplicationSceneManifest:
UIApplicationSupportsMultipleScenes: false
UIBackgroundModes:
- audio
+ - remote-notification
NSLocalNetworkUsageDescription: OpenClaw discovers and connects to your OpenClaw gateway on the local network.
NSAppTransportSecurity:
NSAllowsArbitraryLoadsInWebContent: true
@@ -109,6 +121,90 @@ targets:
- UIInterfaceOrientationLandscapeLeft
- UIInterfaceOrientationLandscapeRight
+ OpenClawShareExtension:
+ type: app-extension
+ platform: iOS
+ configFiles:
+ Debug: Signing.xcconfig
+ Release: Signing.xcconfig
+ sources:
+ - path: ShareExtension
+ dependencies:
+ - package: OpenClawKit
+ settings:
+ base:
+ CODE_SIGN_IDENTITY: "Apple Development"
+ CODE_SIGN_STYLE: "$(OPENCLAW_CODE_SIGN_STYLE)"
+ DEVELOPMENT_TEAM: "$(OPENCLAW_DEVELOPMENT_TEAM)"
+ PRODUCT_BUNDLE_IDENTIFIER: "$(OPENCLAW_SHARE_BUNDLE_ID)"
+ PROVISIONING_PROFILE_SPECIFIER: "$(OPENCLAW_SHARE_PROFILE)"
+ SWIFT_VERSION: "6.0"
+ SWIFT_STRICT_CONCURRENCY: complete
+ info:
+ path: ShareExtension/Info.plist
+ properties:
+ CFBundleDisplayName: OpenClaw Share
+ CFBundleShortVersionString: "2026.2.19"
+ CFBundleVersion: "20260219"
+ NSExtension:
+ NSExtensionPointIdentifier: com.apple.share-services
+ NSExtensionPrincipalClass: "$(PRODUCT_MODULE_NAME).ShareViewController"
+ NSExtensionAttributes:
+ NSExtensionActivationRule:
+ NSExtensionActivationSupportsText: true
+ NSExtensionActivationSupportsWebURLWithMaxCount: 1
+ NSExtensionActivationSupportsImageWithMaxCount: 10
+ NSExtensionActivationSupportsMovieWithMaxCount: 1
+
+ OpenClawWatchApp:
+ type: application.watchapp2
+ platform: watchOS
+ deploymentTarget: "11.0"
+ sources:
+ - path: WatchApp
+ dependencies:
+ - target: OpenClawWatchExtension
+ configFiles:
+ Debug: Config/Signing.xcconfig
+ Release: Config/Signing.xcconfig
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: "$(OPENCLAW_WATCH_APP_BUNDLE_ID)"
+ info:
+ path: WatchApp/Info.plist
+ properties:
+ CFBundleDisplayName: OpenClaw
+ CFBundleShortVersionString: "2026.2.19"
+ CFBundleVersion: "20260219"
+ WKCompanionAppBundleIdentifier: "$(OPENCLAW_APP_BUNDLE_ID)"
+ WKWatchKitApp: true
+
+ OpenClawWatchExtension:
+ type: watchkit2-extension
+ platform: watchOS
+ deploymentTarget: "11.0"
+ sources:
+ - path: WatchExtension/Sources
+ dependencies:
+ - sdk: WatchConnectivity.framework
+ - sdk: UserNotifications.framework
+ configFiles:
+ Debug: Config/Signing.xcconfig
+ Release: Config/Signing.xcconfig
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: "$(OPENCLAW_WATCH_EXTENSION_BUNDLE_ID)"
+ info:
+ path: WatchExtension/Info.plist
+ properties:
+ CFBundleDisplayName: OpenClaw
+ CFBundleShortVersionString: "2026.2.19"
+ CFBundleVersion: "20260219"
+ NSExtension:
+ NSExtensionAttributes:
+ WKAppBundleIdentifier: "$(OPENCLAW_WATCH_APP_BUNDLE_ID)"
+ NSExtensionPointIdentifier: com.apple.watchkit
+
OpenClawTests:
type: bundle.unit-test
platform: iOS
@@ -130,5 +226,5 @@ targets:
path: Tests/Info.plist
properties:
CFBundleDisplayName: OpenClawTests
- CFBundleShortVersionString: "2026.2.13"
- CFBundleVersion: "20260213"
+ CFBundleShortVersionString: "2026.2.19"
+ CFBundleVersion: "20260219"
diff --git a/apps/macos/Sources/OpenClaw/AboutSettings.swift b/apps/macos/Sources/OpenClaw/AboutSettings.swift
index ede898ebac2e3..b61cfee89a57b 100644
--- a/apps/macos/Sources/OpenClaw/AboutSettings.swift
+++ b/apps/macos/Sources/OpenClaw/AboutSettings.swift
@@ -110,8 +110,8 @@ struct AboutSettings: View {
private var buildTimestamp: String? {
guard
let raw =
- (Bundle.main.object(forInfoDictionaryKey: "OpenClawBuildTimestamp") as? String) ??
- (Bundle.main.object(forInfoDictionaryKey: "OpenClawBuildTimestamp") as? String)
+ (Bundle.main.object(forInfoDictionaryKey: "OpenClawBuildTimestamp") as? String) ??
+ (Bundle.main.object(forInfoDictionaryKey: "OpenClawBuildTimestamp") as? String)
else { return nil }
let parser = ISO8601DateFormatter()
parser.formatOptions = [.withInternetDateTime]
diff --git a/apps/macos/Sources/OpenClaw/AgeFormatting.swift b/apps/macos/Sources/OpenClaw/AgeFormatting.swift
index f992c2d95e3c5..5bb46bf459db5 100644
--- a/apps/macos/Sources/OpenClaw/AgeFormatting.swift
+++ b/apps/macos/Sources/OpenClaw/AgeFormatting.swift
@@ -1,6 +1,6 @@
import Foundation
-// Human-friendly age string (e.g., "2m ago").
+/// Human-friendly age string (e.g., "2m ago").
func age(from date: Date, now: Date = .init()) -> String {
let seconds = max(0, Int(now.timeIntervalSince(date)))
let minutes = seconds / 60
diff --git a/apps/macos/Sources/OpenClaw/AgentWorkspace.swift b/apps/macos/Sources/OpenClaw/AgentWorkspace.swift
index 603f837f45e5e..57164ebb892de 100644
--- a/apps/macos/Sources/OpenClaw/AgentWorkspace.swift
+++ b/apps/macos/Sources/OpenClaw/AgentWorkspace.swift
@@ -19,7 +19,7 @@ enum AgentWorkspace {
]
enum BootstrapSafety: Equatable {
case safe
- case unsafe(reason: String)
+ case unsafe (reason: String)
}
static func displayPath(for url: URL) -> String {
@@ -72,7 +72,7 @@ enum AgentWorkspace {
return .safe
}
if !isDir.boolValue {
- return .unsafe(reason: "Workspace path points to a file.")
+ return .unsafe (reason: "Workspace path points to a file.")
}
let agentsURL = self.agentsURL(workspaceURL: workspaceURL)
if fm.fileExists(atPath: agentsURL.path) {
@@ -82,9 +82,9 @@ enum AgentWorkspace {
let entries = try self.workspaceEntries(workspaceURL: workspaceURL)
return entries.isEmpty
? .safe
- : .unsafe(reason: "Folder isn't empty. Choose a new folder or add AGENTS.md first.")
+ : .unsafe (reason: "Folder isn't empty. Choose a new folder or add AGENTS.md first.")
} catch {
- return .unsafe(reason: "Couldn't inspect the workspace folder.")
+ return .unsafe (reason: "Couldn't inspect the workspace folder.")
}
}
diff --git a/apps/macos/Sources/OpenClaw/AnthropicOAuth.swift b/apps/macos/Sources/OpenClaw/AnthropicOAuth.swift
index 408b881ba8fc6..f594cc04c3114 100644
--- a/apps/macos/Sources/OpenClaw/AnthropicOAuth.swift
+++ b/apps/macos/Sources/OpenClaw/AnthropicOAuth.swift
@@ -234,9 +234,8 @@ enum OpenClawOAuthStore {
return URL(fileURLWithPath: expanded, isDirectory: true)
}
let home = FileManager().homeDirectoryForCurrentUser
- let preferred = home.appendingPathComponent(".openclaw", isDirectory: true)
+ return home.appendingPathComponent(".openclaw", isDirectory: true)
.appendingPathComponent("credentials", isDirectory: true)
- return preferred
}
static func oauthURL() -> URL {
diff --git a/apps/macos/Sources/OpenClaw/AnyCodable+Helpers.swift b/apps/macos/Sources/OpenClaw/AnyCodable+Helpers.swift
index acc54a0a14eb7..3cb8f54e39660 100644
--- a/apps/macos/Sources/OpenClaw/AnyCodable+Helpers.swift
+++ b/apps/macos/Sources/OpenClaw/AnyCodable+Helpers.swift
@@ -1,44 +1,40 @@
-import OpenClawKit
-import OpenClawProtocol
import Foundation
+import OpenClawKit
// Prefer the OpenClawKit wrapper to keep gateway request payloads consistent.
typealias AnyCodable = OpenClawKit.AnyCodable
typealias InstanceIdentity = OpenClawKit.InstanceIdentity
extension AnyCodable {
- var stringValue: String? { self.value as? String }
- var boolValue: Bool? { self.value as? Bool }
- var intValue: Int? { self.value as? Int }
- var doubleValue: Double? { self.value as? Double }
- var dictionaryValue: [String: AnyCodable]? { self.value as? [String: AnyCodable] }
- var arrayValue: [AnyCodable]? { self.value as? [AnyCodable] }
+ var stringValue: String? {
+ self.value as? String
+ }
- var foundationValue: Any {
- switch self.value {
- case let dict as [String: AnyCodable]:
- dict.mapValues { $0.foundationValue }
- case let array as [AnyCodable]:
- array.map(\.foundationValue)
- default:
- self.value
- }
+ var boolValue: Bool? {
+ self.value as? Bool
+ }
+
+ var intValue: Int? {
+ self.value as? Int
}
-}
-extension OpenClawProtocol.AnyCodable {
- var stringValue: String? { self.value as? String }
- var boolValue: Bool? { self.value as? Bool }
- var intValue: Int? { self.value as? Int }
- var doubleValue: Double? { self.value as? Double }
- var dictionaryValue: [String: OpenClawProtocol.AnyCodable]? { self.value as? [String: OpenClawProtocol.AnyCodable] }
- var arrayValue: [OpenClawProtocol.AnyCodable]? { self.value as? [OpenClawProtocol.AnyCodable] }
+ var doubleValue: Double? {
+ self.value as? Double
+ }
+
+ var dictionaryValue: [String: AnyCodable]? {
+ self.value as? [String: AnyCodable]
+ }
+
+ var arrayValue: [AnyCodable]? {
+ self.value as? [AnyCodable]
+ }
var foundationValue: Any {
switch self.value {
- case let dict as [String: OpenClawProtocol.AnyCodable]:
+ case let dict as [String: AnyCodable]:
dict.mapValues { $0.foundationValue }
- case let array as [OpenClawProtocol.AnyCodable]:
+ case let array as [AnyCodable]:
array.map(\.foundationValue)
default:
self.value
diff --git a/apps/macos/Sources/OpenClaw/AppState.swift b/apps/macos/Sources/OpenClaw/AppState.swift
index ce2a251cfc961..d960d3c038a75 100644
--- a/apps/macos/Sources/OpenClaw/AppState.swift
+++ b/apps/macos/Sources/OpenClaw/AppState.swift
@@ -422,11 +422,10 @@ final class AppState {
let trimmedUser = parsed.user?.trimmingCharacters(in: .whitespacesAndNewlines)
let user = (trimmedUser?.isEmpty ?? true) ? nil : trimmedUser
let port = parsed.port
- let assembled: String
- if let user {
- assembled = port == 22 ? "\(user)@\(host)" : "\(user)@\(host):\(port)"
+ let assembled: String = if let user {
+ port == 22 ? "\(user)@\(host)" : "\(user)@\(host):\(port)"
} else {
- assembled = port == 22 ? host : "\(host):\(port)"
+ port == 22 ? host : "\(host):\(port)"
}
if assembled != self.remoteTarget {
self.remoteTarget = assembled
@@ -698,7 +697,9 @@ extension AppState {
@MainActor
enum AppStateStore {
static let shared = AppState()
- static var isPausedFlag: Bool { UserDefaults.standard.bool(forKey: pauseDefaultsKey) }
+ static var isPausedFlag: Bool {
+ UserDefaults.standard.bool(forKey: pauseDefaultsKey)
+ }
static func updateLaunchAtLogin(enabled: Bool) {
Task.detached(priority: .utility) {
diff --git a/apps/macos/Sources/OpenClaw/CameraCaptureService.swift b/apps/macos/Sources/OpenClaw/CameraCaptureService.swift
index 8653b05dcbb2a..4e3749d6a68da 100644
--- a/apps/macos/Sources/OpenClaw/CameraCaptureService.swift
+++ b/apps/macos/Sources/OpenClaw/CameraCaptureService.swift
@@ -1,8 +1,8 @@
import AVFoundation
-import OpenClawIPC
-import OpenClawKit
import CoreGraphics
import Foundation
+import OpenClawIPC
+import OpenClawKit
import OSLog
actor CameraCaptureService {
@@ -106,14 +106,16 @@ actor CameraCaptureService {
}
withExtendedLifetime(delegate) {}
- let maxPayloadBytes = 5 * 1024 * 1024
- // Base64 inflates payloads by ~4/3; cap encoded bytes so the payload stays under 5MB (API limit).
- let maxEncodedBytes = (maxPayloadBytes / 4) * 3
- let res = try JPEGTranscoder.transcodeToJPEG(
- imageData: rawData,
- maxWidthPx: maxWidth,
- quality: quality,
- maxBytes: maxEncodedBytes)
+ let res: (data: Data, widthPx: Int, heightPx: Int)
+ do {
+ res = try PhotoCapture.transcodeJPEGForGateway(
+ rawData: rawData,
+ maxWidthPx: maxWidth,
+ quality: quality)
+ } catch {
+ throw CameraError.captureFailed(error.localizedDescription)
+ }
+
return (data: res.data, size: CGSize(width: res.widthPx, height: res.heightPx))
}
diff --git a/apps/macos/Sources/OpenClaw/CanvasA2UIActionMessageHandler.swift b/apps/macos/Sources/OpenClaw/CanvasA2UIActionMessageHandler.swift
index 2faca73c18f7a..40f443c5c8b8f 100644
--- a/apps/macos/Sources/OpenClaw/CanvasA2UIActionMessageHandler.swift
+++ b/apps/macos/Sources/OpenClaw/CanvasA2UIActionMessageHandler.swift
@@ -1,7 +1,7 @@
import AppKit
+import Foundation
import OpenClawIPC
import OpenClawKit
-import Foundation
import WebKit
final class CanvasA2UIActionMessageHandler: NSObject, WKScriptMessageHandler {
diff --git a/apps/macos/Sources/OpenClaw/CanvasChromeContainerView.swift b/apps/macos/Sources/OpenClaw/CanvasChromeContainerView.swift
index 89c19ef138564..b4158167dcf8e 100644
--- a/apps/macos/Sources/OpenClaw/CanvasChromeContainerView.swift
+++ b/apps/macos/Sources/OpenClaw/CanvasChromeContainerView.swift
@@ -39,7 +39,9 @@ final class HoverChromeContainerView: NSView {
}
@available(*, unavailable)
- required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) is not supported")
+ }
override func updateTrackingAreas() {
super.updateTrackingAreas()
@@ -60,14 +62,18 @@ final class HoverChromeContainerView: NSView {
self.window?.performDrag(with: event)
}
- override func acceptsFirstMouse(for _: NSEvent?) -> Bool { true }
+ override func acceptsFirstMouse(for _: NSEvent?) -> Bool {
+ true
+ }
}
private final class CanvasResizeHandleView: NSView {
private var startPoint: NSPoint = .zero
private var startFrame: NSRect = .zero
- override func acceptsFirstMouse(for _: NSEvent?) -> Bool { true }
+ override func acceptsFirstMouse(for _: NSEvent?) -> Bool {
+ true
+ }
override func mouseDown(with event: NSEvent) {
guard let window else { return }
@@ -102,7 +108,9 @@ final class HoverChromeContainerView: NSView {
private let resizeHandle = CanvasResizeHandleView(frame: .zero)
private final class PassthroughVisualEffectView: NSVisualEffectView {
- override func hitTest(_: NSPoint) -> NSView? { nil }
+ override func hitTest(_: NSPoint) -> NSView? {
+ nil
+ }
}
private let closeBackground: NSVisualEffectView = {
@@ -190,7 +198,9 @@ final class HoverChromeContainerView: NSView {
}
@available(*, unavailable)
- required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) is not supported")
+ }
override func hitTest(_ point: NSPoint) -> NSView? {
// When the chrome is hidden, do not intercept any mouse events (let the WKWebView receive them).
diff --git a/apps/macos/Sources/OpenClaw/CanvasFileWatcher.swift b/apps/macos/Sources/OpenClaw/CanvasFileWatcher.swift
index 3cf800fd10849..3ed0d67ffbcbc 100644
--- a/apps/macos/Sources/OpenClaw/CanvasFileWatcher.swift
+++ b/apps/macos/Sources/OpenClaw/CanvasFileWatcher.swift
@@ -1,17 +1,13 @@
-import CoreServices
import Foundation
final class CanvasFileWatcher: @unchecked Sendable {
- private let url: URL
- private let queue: DispatchQueue
- private var stream: FSEventStreamRef?
- private var pending = false
- private let onChange: () -> Void
+ private let watcher: CoalescingFSEventsWatcher
init(url: URL, onChange: @escaping () -> Void) {
- self.url = url
- self.queue = DispatchQueue(label: "ai.openclaw.canvaswatcher")
- self.onChange = onChange
+ self.watcher = CoalescingFSEventsWatcher(
+ paths: [url.path],
+ queueLabel: "ai.openclaw.canvaswatcher",
+ onChange: onChange)
}
deinit {
@@ -19,76 +15,10 @@ final class CanvasFileWatcher: @unchecked Sendable {
}
func start() {
- guard self.stream == nil else { return }
-
- let retainedSelf = Unmanaged.passRetained(self)
- var context = FSEventStreamContext(
- version: 0,
- info: retainedSelf.toOpaque(),
- retain: nil,
- release: { pointer in
- guard let pointer else { return }
- Unmanaged.fromOpaque(pointer).release()
- },
- copyDescription: nil)
-
- let paths = [self.url.path] as CFArray
- let flags = FSEventStreamCreateFlags(
- kFSEventStreamCreateFlagFileEvents |
- kFSEventStreamCreateFlagUseCFTypes |
- kFSEventStreamCreateFlagNoDefer)
-
- guard let stream = FSEventStreamCreate(
- kCFAllocatorDefault,
- Self.callback,
- &context,
- paths,
- FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
- 0.05,
- flags)
- else {
- retainedSelf.release()
- return
- }
-
- self.stream = stream
- FSEventStreamSetDispatchQueue(stream, self.queue)
- if FSEventStreamStart(stream) == false {
- self.stream = nil
- FSEventStreamSetDispatchQueue(stream, nil)
- FSEventStreamInvalidate(stream)
- FSEventStreamRelease(stream)
- }
+ self.watcher.start()
}
func stop() {
- guard let stream = self.stream else { return }
- self.stream = nil
- FSEventStreamStop(stream)
- FSEventStreamSetDispatchQueue(stream, nil)
- FSEventStreamInvalidate(stream)
- FSEventStreamRelease(stream)
- }
-}
-
-extension CanvasFileWatcher {
- private static let callback: FSEventStreamCallback = { _, info, numEvents, _, eventFlags, _ in
- guard let info else { return }
- let watcher = Unmanaged.fromOpaque(info).takeUnretainedValue()
- watcher.handleEvents(numEvents: numEvents, eventFlags: eventFlags)
- }
-
- private func handleEvents(numEvents: Int, eventFlags: UnsafePointer?) {
- guard numEvents > 0 else { return }
- guard eventFlags != nil else { return }
-
- // Coalesce rapid changes (common during builds/atomic saves).
- if self.pending { return }
- self.pending = true
- self.queue.asyncAfter(deadline: .now() + 0.12) { [weak self] in
- guard let self else { return }
- self.pending = false
- self.onChange()
- }
+ self.watcher.stop()
}
}
diff --git a/apps/macos/Sources/OpenClaw/CanvasManager.swift b/apps/macos/Sources/OpenClaw/CanvasManager.swift
index 0055ffcfe210e..843f78842bdf6 100644
--- a/apps/macos/Sources/OpenClaw/CanvasManager.swift
+++ b/apps/macos/Sources/OpenClaw/CanvasManager.swift
@@ -1,7 +1,7 @@
import AppKit
+import Foundation
import OpenClawIPC
import OpenClawKit
-import Foundation
import OSLog
@MainActor
diff --git a/apps/macos/Sources/OpenClaw/CanvasSchemeHandler.swift b/apps/macos/Sources/OpenClaw/CanvasSchemeHandler.swift
index 3241c08e0d271..6905af500146b 100644
--- a/apps/macos/Sources/OpenClaw/CanvasSchemeHandler.swift
+++ b/apps/macos/Sources/OpenClaw/CanvasSchemeHandler.swift
@@ -1,5 +1,5 @@
-import OpenClawKit
import Foundation
+import OpenClawKit
import OSLog
import WebKit
diff --git a/apps/macos/Sources/OpenClaw/CanvasWindow.swift b/apps/macos/Sources/OpenClaw/CanvasWindow.swift
index 0cb3b7c0769af..a87f325617038 100644
--- a/apps/macos/Sources/OpenClaw/CanvasWindow.swift
+++ b/apps/macos/Sources/OpenClaw/CanvasWindow.swift
@@ -11,8 +11,13 @@ enum CanvasLayout {
}
final class CanvasPanel: NSPanel {
- override var canBecomeKey: Bool { true }
- override var canBecomeMain: Bool { true }
+ override var canBecomeKey: Bool {
+ true
+ }
+
+ override var canBecomeMain: Bool {
+ true
+ }
}
enum CanvasPresentation {
diff --git a/apps/macos/Sources/OpenClaw/CanvasWindowController+Navigation.swift b/apps/macos/Sources/OpenClaw/CanvasWindowController+Navigation.swift
index 7139b6834d409..16e0b01d294c1 100644
--- a/apps/macos/Sources/OpenClaw/CanvasWindowController+Navigation.swift
+++ b/apps/macos/Sources/OpenClaw/CanvasWindowController+Navigation.swift
@@ -19,7 +19,8 @@ extension CanvasWindowController {
// Deep links: allow local Canvas content to invoke the agent without bouncing through NSWorkspace.
if scheme == "openclaw" {
if let currentScheme = self.webView.url?.scheme,
- CanvasScheme.allSchemes.contains(currentScheme) {
+ CanvasScheme.allSchemes.contains(currentScheme)
+ {
Task { await DeepLinkHandler.shared.handle(url: url) }
} else {
canvasWindowLogger
diff --git a/apps/macos/Sources/OpenClaw/CanvasWindowController.swift b/apps/macos/Sources/OpenClaw/CanvasWindowController.swift
index ee15a6abb671b..d30f54186aee6 100644
--- a/apps/macos/Sources/OpenClaw/CanvasWindowController.swift
+++ b/apps/macos/Sources/OpenClaw/CanvasWindowController.swift
@@ -1,7 +1,7 @@
import AppKit
+import Foundation
import OpenClawIPC
import OpenClawKit
-import Foundation
import WebKit
@MainActor
@@ -183,7 +183,9 @@ final class CanvasWindowController: NSWindowController, WKNavigationDelegate, NS
}
@available(*, unavailable)
- required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) is not supported")
+ }
@MainActor deinit {
for name in CanvasA2UIActionMessageHandler.allMessageNames {
diff --git a/apps/macos/Sources/OpenClaw/ChannelsSettings+ChannelSections.swift b/apps/macos/Sources/OpenClaw/ChannelsSettings+ChannelSections.swift
index ea82aac013d32..2bef47f2dea88 100644
--- a/apps/macos/Sources/OpenClaw/ChannelsSettings+ChannelSections.swift
+++ b/apps/macos/Sources/OpenClaw/ChannelsSettings+ChannelSections.swift
@@ -10,7 +10,6 @@ extension ChannelsSettings {
}
}
- @ViewBuilder
func channelHeaderActions(_ channel: ChannelItem) -> some View {
HStack(spacing: 8) {
if channel.id == "whatsapp" {
@@ -88,7 +87,6 @@ extension ChannelsSettings {
}
}
- @ViewBuilder
func genericChannelSection(_ channel: ChannelItem) -> some View {
VStack(alignment: .leading, spacing: 16) {
self.configEditorSection(channelId: channel.id)
diff --git a/apps/macos/Sources/OpenClaw/ChannelsStore+Config.swift b/apps/macos/Sources/OpenClaw/ChannelsStore+Config.swift
index c56cb32078548..703c7efed63e3 100644
--- a/apps/macos/Sources/OpenClaw/ChannelsStore+Config.swift
+++ b/apps/macos/Sources/OpenClaw/ChannelsStore+Config.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Foundation
+import OpenClawProtocol
extension ChannelsStore {
func loadConfigSchema() async {
diff --git a/apps/macos/Sources/OpenClaw/ChannelsStore+Lifecycle.swift b/apps/macos/Sources/OpenClaw/ChannelsStore+Lifecycle.swift
index 0610fe46438f3..fd516480f965d 100644
--- a/apps/macos/Sources/OpenClaw/ChannelsStore+Lifecycle.swift
+++ b/apps/macos/Sources/OpenClaw/ChannelsStore+Lifecycle.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Foundation
+import OpenClawProtocol
extension ChannelsStore {
func start() {
diff --git a/apps/macos/Sources/OpenClaw/ChannelsStore.swift b/apps/macos/Sources/OpenClaw/ChannelsStore.swift
index 724862efd72dc..09b9b75a532ff 100644
--- a/apps/macos/Sources/OpenClaw/ChannelsStore.swift
+++ b/apps/macos/Sources/OpenClaw/ChannelsStore.swift
@@ -1,6 +1,6 @@
-import OpenClawProtocol
import Foundation
import Observation
+import OpenClawProtocol
struct ChannelsStatusSnapshot: Codable {
struct WhatsAppSelf: Codable {
diff --git a/apps/macos/Sources/OpenClaw/CoalescingFSEventsWatcher.swift b/apps/macos/Sources/OpenClaw/CoalescingFSEventsWatcher.swift
new file mode 100644
index 0000000000000..f9e38d81170fd
--- /dev/null
+++ b/apps/macos/Sources/OpenClaw/CoalescingFSEventsWatcher.swift
@@ -0,0 +1,110 @@
+import CoreServices
+import Foundation
+
+final class CoalescingFSEventsWatcher: @unchecked Sendable {
+ private let queue: DispatchQueue
+ private var stream: FSEventStreamRef?
+ private var pending = false
+
+ private let paths: [String]
+ private let shouldNotify: (Int, UnsafeMutableRawPointer?) -> Bool
+ private let onChange: () -> Void
+ private let coalesceDelay: TimeInterval
+
+ init(
+ paths: [String],
+ queueLabel: String,
+ coalesceDelay: TimeInterval = 0.12,
+ shouldNotify: @escaping (Int, UnsafeMutableRawPointer?) -> Bool = { _, _ in true },
+ onChange: @escaping () -> Void)
+ {
+ self.paths = paths
+ self.queue = DispatchQueue(label: queueLabel)
+ self.coalesceDelay = coalesceDelay
+ self.shouldNotify = shouldNotify
+ self.onChange = onChange
+ }
+
+ deinit {
+ self.stop()
+ }
+
+ func start() {
+ guard self.stream == nil else { return }
+
+ let retainedSelf = Unmanaged.passRetained(self)
+ var context = FSEventStreamContext(
+ version: 0,
+ info: retainedSelf.toOpaque(),
+ retain: nil,
+ release: { pointer in
+ guard let pointer else { return }
+ Unmanaged.fromOpaque(pointer).release()
+ },
+ copyDescription: nil)
+
+ let paths = self.paths as CFArray
+ let flags = FSEventStreamCreateFlags(
+ kFSEventStreamCreateFlagFileEvents |
+ kFSEventStreamCreateFlagUseCFTypes |
+ kFSEventStreamCreateFlagNoDefer)
+
+ guard let stream = FSEventStreamCreate(
+ kCFAllocatorDefault,
+ Self.callback,
+ &context,
+ paths,
+ FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
+ 0.05,
+ flags)
+ else {
+ retainedSelf.release()
+ return
+ }
+
+ self.stream = stream
+ FSEventStreamSetDispatchQueue(stream, self.queue)
+ if FSEventStreamStart(stream) == false {
+ self.stream = nil
+ FSEventStreamSetDispatchQueue(stream, nil)
+ FSEventStreamInvalidate(stream)
+ FSEventStreamRelease(stream)
+ }
+ }
+
+ func stop() {
+ guard let stream = self.stream else { return }
+ self.stream = nil
+ FSEventStreamStop(stream)
+ FSEventStreamSetDispatchQueue(stream, nil)
+ FSEventStreamInvalidate(stream)
+ FSEventStreamRelease(stream)
+ }
+}
+
+extension CoalescingFSEventsWatcher {
+ private static let callback: FSEventStreamCallback = { _, info, numEvents, eventPaths, eventFlags, _ in
+ guard let info else { return }
+ let watcher = Unmanaged.fromOpaque(info).takeUnretainedValue()
+ watcher.handleEvents(numEvents: numEvents, eventPaths: eventPaths, eventFlags: eventFlags)
+ }
+
+ private func handleEvents(
+ numEvents: Int,
+ eventPaths: UnsafeMutableRawPointer?,
+ eventFlags: UnsafePointer?)
+ {
+ guard numEvents > 0 else { return }
+ guard eventFlags != nil else { return }
+ guard self.shouldNotify(numEvents, eventPaths) else { return }
+
+ // Coalesce rapid changes (common during builds/atomic saves).
+ if self.pending { return }
+ self.pending = true
+ self.queue.asyncAfter(deadline: .now() + self.coalesceDelay) { [weak self] in
+ guard let self else { return }
+ self.pending = false
+ self.onChange()
+ }
+ }
+}
diff --git a/apps/macos/Sources/OpenClaw/ConfigFileWatcher.swift b/apps/macos/Sources/OpenClaw/ConfigFileWatcher.swift
index 23689f1fb9d90..4434443497e73 100644
--- a/apps/macos/Sources/OpenClaw/ConfigFileWatcher.swift
+++ b/apps/macos/Sources/OpenClaw/ConfigFileWatcher.swift
@@ -1,23 +1,34 @@
-import CoreServices
import Foundation
final class ConfigFileWatcher: @unchecked Sendable {
private let url: URL
- private let queue: DispatchQueue
- private var stream: FSEventStreamRef?
- private var pending = false
- private let onChange: () -> Void
private let watchedDir: URL
private let targetPath: String
private let targetName: String
+ private let watcher: CoalescingFSEventsWatcher
init(url: URL, onChange: @escaping () -> Void) {
self.url = url
- self.queue = DispatchQueue(label: "ai.openclaw.configwatcher")
- self.onChange = onChange
self.watchedDir = url.deletingLastPathComponent()
self.targetPath = url.path
self.targetName = url.lastPathComponent
+ let watchedDirPath = self.watchedDir.path
+ let targetPath = self.targetPath
+ let targetName = self.targetName
+ self.watcher = CoalescingFSEventsWatcher(
+ paths: [watchedDirPath],
+ queueLabel: "ai.openclaw.configwatcher",
+ shouldNotify: { _, eventPaths in
+ guard let eventPaths else { return true }
+ let paths = unsafeBitCast(eventPaths, to: NSArray.self)
+ for case let path as String in paths {
+ if path == targetPath { return true }
+ if path.hasSuffix("/\(targetName)") { return true }
+ if path == watchedDirPath { return true }
+ }
+ return false
+ },
+ onChange: onChange)
}
deinit {
@@ -25,94 +36,10 @@ final class ConfigFileWatcher: @unchecked Sendable {
}
func start() {
- guard self.stream == nil else { return }
-
- let retainedSelf = Unmanaged.passRetained(self)
- var context = FSEventStreamContext(
- version: 0,
- info: retainedSelf.toOpaque(),
- retain: nil,
- release: { pointer in
- guard let pointer else { return }
- Unmanaged.fromOpaque(pointer).release()
- },
- copyDescription: nil)
-
- let paths = [self.watchedDir.path] as CFArray
- let flags = FSEventStreamCreateFlags(
- kFSEventStreamCreateFlagFileEvents |
- kFSEventStreamCreateFlagUseCFTypes |
- kFSEventStreamCreateFlagNoDefer)
-
- guard let stream = FSEventStreamCreate(
- kCFAllocatorDefault,
- Self.callback,
- &context,
- paths,
- FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
- 0.05,
- flags)
- else {
- retainedSelf.release()
- return
- }
-
- self.stream = stream
- FSEventStreamSetDispatchQueue(stream, self.queue)
- if FSEventStreamStart(stream) == false {
- self.stream = nil
- FSEventStreamSetDispatchQueue(stream, nil)
- FSEventStreamInvalidate(stream)
- FSEventStreamRelease(stream)
- }
+ self.watcher.start()
}
func stop() {
- guard let stream = self.stream else { return }
- self.stream = nil
- FSEventStreamStop(stream)
- FSEventStreamSetDispatchQueue(stream, nil)
- FSEventStreamInvalidate(stream)
- FSEventStreamRelease(stream)
- }
-}
-
-extension ConfigFileWatcher {
- private static let callback: FSEventStreamCallback = { _, info, numEvents, eventPaths, eventFlags, _ in
- guard let info else { return }
- let watcher = Unmanaged.fromOpaque(info).takeUnretainedValue()
- watcher.handleEvents(
- numEvents: numEvents,
- eventPaths: eventPaths,
- eventFlags: eventFlags)
- }
-
- private func handleEvents(
- numEvents: Int,
- eventPaths: UnsafeMutableRawPointer?,
- eventFlags: UnsafePointer?)
- {
- guard numEvents > 0 else { return }
- guard eventFlags != nil else { return }
- guard self.matchesTarget(eventPaths: eventPaths) else { return }
-
- if self.pending { return }
- self.pending = true
- self.queue.asyncAfter(deadline: .now() + 0.12) { [weak self] in
- guard let self else { return }
- self.pending = false
- self.onChange()
- }
- }
-
- private func matchesTarget(eventPaths: UnsafeMutableRawPointer?) -> Bool {
- guard let eventPaths else { return true }
- let paths = unsafeBitCast(eventPaths, to: NSArray.self)
- for case let path as String in paths {
- if path == self.targetPath { return true }
- if path.hasSuffix("/\(self.targetName)") { return true }
- if path == self.watchedDir.path { return true }
- }
- return false
+ self.watcher.stop()
}
}
diff --git a/apps/macos/Sources/OpenClaw/ConfigSchemaSupport.swift b/apps/macos/Sources/OpenClaw/ConfigSchemaSupport.swift
index 4a7d4e0a48af1..406d908d0b72e 100644
--- a/apps/macos/Sources/OpenClaw/ConfigSchemaSupport.swift
+++ b/apps/macos/Sources/OpenClaw/ConfigSchemaSupport.swift
@@ -39,11 +39,26 @@ struct ConfigSchemaNode {
self.raw = dict
}
- var title: String? { self.raw["title"] as? String }
- var description: String? { self.raw["description"] as? String }
- var enumValues: [Any]? { self.raw["enum"] as? [Any] }
- var constValue: Any? { self.raw["const"] }
- var explicitDefault: Any? { self.raw["default"] }
+ var title: String? {
+ self.raw["title"] as? String
+ }
+
+ var description: String? {
+ self.raw["description"] as? String
+ }
+
+ var enumValues: [Any]? {
+ self.raw["enum"] as? [Any]
+ }
+
+ var constValue: Any? {
+ self.raw["const"]
+ }
+
+ var explicitDefault: Any? {
+ self.raw["default"]
+ }
+
var requiredKeys: Set {
Set((self.raw["required"] as? [String]) ?? [])
}
diff --git a/apps/macos/Sources/OpenClaw/ConfigSettings.swift b/apps/macos/Sources/OpenClaw/ConfigSettings.swift
index f64a6bce94ebd..096ae3f714978 100644
--- a/apps/macos/Sources/OpenClaw/ConfigSettings.swift
+++ b/apps/macos/Sources/OpenClaw/ConfigSettings.swift
@@ -45,7 +45,9 @@ extension ConfigSettings {
let help: String?
let node: ConfigSchemaNode
- var id: String { self.key }
+ var id: String {
+ self.key
+ }
}
private struct ConfigSubsection: Identifiable {
@@ -55,7 +57,9 @@ extension ConfigSettings {
let node: ConfigSchemaNode
let path: ConfigPath
- var id: String { self.key }
+ var id: String {
+ self.key
+ }
}
private var sections: [ConfigSection] {
diff --git a/apps/macos/Sources/OpenClaw/ConfigStore.swift b/apps/macos/Sources/OpenClaw/ConfigStore.swift
index 4e9437ff86eb4..8fd779c645674 100644
--- a/apps/macos/Sources/OpenClaw/ConfigStore.swift
+++ b/apps/macos/Sources/OpenClaw/ConfigStore.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Foundation
+import OpenClawProtocol
enum ConfigStore {
struct Overrides: Sendable {
diff --git a/apps/macos/Sources/OpenClaw/ContextMenuCardView.swift b/apps/macos/Sources/OpenClaw/ContextMenuCardView.swift
index 41005e8260e41..f9a11b9e51298 100644
--- a/apps/macos/Sources/OpenClaw/ContextMenuCardView.swift
+++ b/apps/macos/Sources/OpenClaw/ContextMenuCardView.swift
@@ -70,7 +70,6 @@ struct ContextMenuCardView: View {
return "\(count) sessions · 24h"
}
- @ViewBuilder
private func sessionRow(_ row: SessionRow) -> some View {
VStack(alignment: .leading, spacing: 5) {
ContextUsageBar(
diff --git a/apps/macos/Sources/OpenClaw/ControlChannel.swift b/apps/macos/Sources/OpenClaw/ControlChannel.swift
index 9436b22ecb848..16b4d6d3ad456 100644
--- a/apps/macos/Sources/OpenClaw/ControlChannel.swift
+++ b/apps/macos/Sources/OpenClaw/ControlChannel.swift
@@ -1,7 +1,7 @@
-import OpenClawKit
-import OpenClawProtocol
import Foundation
import Observation
+import OpenClawKit
+import OpenClawProtocol
import SwiftUI
struct ControlHeartbeatEvent: Codable {
@@ -15,7 +15,10 @@ struct ControlHeartbeatEvent: Codable {
}
struct ControlAgentEvent: Codable, Sendable, Identifiable {
- var id: String { "\(self.runId)-\(self.seq)" }
+ var id: String {
+ "\(self.runId)-\(self.seq)"
+ }
+
let runId: String
let seq: Int
let stream: String
diff --git a/apps/macos/Sources/OpenClaw/CronJobEditor+Helpers.swift b/apps/macos/Sources/OpenClaw/CronJobEditor+Helpers.swift
index 544c9a7c6c8cc..6b3fc85a7c0e3 100644
--- a/apps/macos/Sources/OpenClaw/CronJobEditor+Helpers.swift
+++ b/apps/macos/Sources/OpenClaw/CronJobEditor+Helpers.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Foundation
+import OpenClawProtocol
import SwiftUI
extension CronJobEditor {
diff --git a/apps/macos/Sources/OpenClaw/CronJobEditor.swift b/apps/macos/Sources/OpenClaw/CronJobEditor.swift
index 517d32df44502..a7d88a4f2fb3b 100644
--- a/apps/macos/Sources/OpenClaw/CronJobEditor.swift
+++ b/apps/macos/Sources/OpenClaw/CronJobEditor.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Observation
+import OpenClawProtocol
import SwiftUI
struct CronJobEditor: View {
@@ -32,18 +32,24 @@ struct CronJobEditor: View {
@State var wakeMode: CronWakeMode = .now
@State var deleteAfterRun: Bool = false
- enum ScheduleKind: String, CaseIterable, Identifiable { case at, every, cron; var id: String { rawValue } }
+ enum ScheduleKind: String, CaseIterable, Identifiable { case at, every, cron; var id: String {
+ rawValue
+ } }
@State var scheduleKind: ScheduleKind = .every
@State var atDate: Date = .init().addingTimeInterval(60 * 5)
@State var everyText: String = "1h"
@State var cronExpr: String = "0 9 * * 3"
@State var cronTz: String = ""
- enum PayloadKind: String, CaseIterable, Identifiable { case systemEvent, agentTurn; var id: String { rawValue } }
+ enum PayloadKind: String, CaseIterable, Identifiable { case systemEvent, agentTurn; var id: String {
+ rawValue
+ } }
@State var payloadKind: PayloadKind = .systemEvent
@State var systemEventText: String = ""
@State var agentMessage: String = ""
- enum DeliveryChoice: String, CaseIterable, Identifiable { case announce, none; var id: String { rawValue } }
+ enum DeliveryChoice: String, CaseIterable, Identifiable { case announce, none; var id: String {
+ rawValue
+ } }
@State var deliveryMode: DeliveryChoice = .announce
@State var channel: String = "last"
@State var to: String = ""
@@ -244,7 +250,6 @@ struct CronJobEditor: View {
}
}
}
-
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, 2)
diff --git a/apps/macos/Sources/OpenClaw/CronJobsStore.swift b/apps/macos/Sources/OpenClaw/CronJobsStore.swift
index cb84a2b41fd05..21c70ded58479 100644
--- a/apps/macos/Sources/OpenClaw/CronJobsStore.swift
+++ b/apps/macos/Sources/OpenClaw/CronJobsStore.swift
@@ -1,7 +1,7 @@
-import OpenClawKit
-import OpenClawProtocol
import Foundation
import Observation
+import OpenClawKit
+import OpenClawProtocol
import OSLog
@MainActor
diff --git a/apps/macos/Sources/OpenClaw/CronModels.swift b/apps/macos/Sources/OpenClaw/CronModels.swift
index 4c977c9c12871..cbfbc061d6ae4 100644
--- a/apps/macos/Sources/OpenClaw/CronModels.swift
+++ b/apps/macos/Sources/OpenClaw/CronModels.swift
@@ -4,21 +4,28 @@ enum CronSessionTarget: String, CaseIterable, Identifiable, Codable {
case main
case isolated
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
}
enum CronWakeMode: String, CaseIterable, Identifiable, Codable {
case now
case nextHeartbeat = "next-heartbeat"
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
}
enum CronDeliveryMode: String, CaseIterable, Identifiable, Codable {
case none
case announce
+ case webhook
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
}
struct CronDelivery: Codable, Equatable {
@@ -98,11 +105,11 @@ enum CronSchedule: Codable, Equatable {
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty { return nil }
if let date = makeIsoFormatter(withFractional: true).date(from: trimmed) { return date }
- return makeIsoFormatter(withFractional: false).date(from: trimmed)
+ return self.makeIsoFormatter(withFractional: false).date(from: trimmed)
}
static func formatIsoDate(_ date: Date) -> String {
- makeIsoFormatter(withFractional: false).string(from: date)
+ self.makeIsoFormatter(withFractional: false).string(from: date)
}
private static func makeIsoFormatter(withFractional: Bool) -> ISO8601DateFormatter {
@@ -231,7 +238,9 @@ struct CronEvent: Codable, Sendable {
}
struct CronRunLogEntry: Codable, Identifiable, Sendable {
- var id: String { "\(self.jobId)-\(self.ts)" }
+ var id: String {
+ "\(self.jobId)-\(self.ts)"
+ }
let ts: Int
let jobId: String
@@ -243,7 +252,10 @@ struct CronRunLogEntry: Codable, Identifiable, Sendable {
let durationMs: Int?
let nextRunAtMs: Int?
- var date: Date { Date(timeIntervalSince1970: TimeInterval(self.ts) / 1000) }
+ var date: Date {
+ Date(timeIntervalSince1970: TimeInterval(self.ts) / 1000)
+ }
+
var runDate: Date? {
guard let runAtMs else { return nil }
return Date(timeIntervalSince1970: TimeInterval(runAtMs) / 1000)
diff --git a/apps/macos/Sources/OpenClaw/CronSettings+Actions.swift b/apps/macos/Sources/OpenClaw/CronSettings+Actions.swift
index d5fe92ae01007..3fffaf90fd5c4 100644
--- a/apps/macos/Sources/OpenClaw/CronSettings+Actions.swift
+++ b/apps/macos/Sources/OpenClaw/CronSettings+Actions.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Foundation
+import OpenClawProtocol
extension CronSettings {
func save(payload: [String: AnyCodable]) async {
diff --git a/apps/macos/Sources/OpenClaw/DeepLinks.swift b/apps/macos/Sources/OpenClaw/DeepLinks.swift
index bb1fd73b66085..d11d4d524c360 100644
--- a/apps/macos/Sources/OpenClaw/DeepLinks.swift
+++ b/apps/macos/Sources/OpenClaw/DeepLinks.swift
@@ -1,13 +1,13 @@
import AppKit
-import OpenClawKit
import Foundation
+import OpenClawKit
import OSLog
import Security
private let deepLinkLogger = Logger(subsystem: "ai.openclaw", category: "DeepLink")
enum DeepLinkAgentPolicy {
- static let maxMessageChars = 20_000
+ static let maxMessageChars = 20000
static let maxUnkeyedConfirmChars = 240
enum ValidationError: Error, Equatable, LocalizedError {
@@ -16,7 +16,7 @@ enum DeepLinkAgentPolicy {
var errorDescription: String? {
switch self {
case let .messageTooLongForConfirmation(max, actual):
- return "Message is too long to confirm safely (\(actual) chars; max \(max) without key)."
+ "Message is too long to confirm safely (\(actual) chars; max \(max) without key)."
}
}
}
@@ -49,9 +49,9 @@ final class DeepLinkHandler {
private var lastPromptAt: Date = .distantPast
- // Ephemeral, in-memory key used for unattended deep links originating from the in-app Canvas.
- // This avoids blocking Canvas init on UserDefaults and doesn't weaken the external deep-link prompt:
- // outside callers can't know this randomly generated key.
+ /// Ephemeral, in-memory key used for unattended deep links originating from the in-app Canvas.
+ /// This avoids blocking Canvas init on UserDefaults and doesn't weaken the external deep-link prompt:
+ /// outside callers can't know this randomly generated key.
private nonisolated static let canvasUnattendedKey: String = DeepLinkHandler.generateRandomKey()
func handle(url: URL) async {
@@ -67,6 +67,8 @@ final class DeepLinkHandler {
switch route {
case let .agent(link):
await self.handleAgent(link: link, originalURL: url)
+ case .gateway:
+ break
}
}
diff --git a/apps/macos/Sources/OpenClaw/DevicePairingApprovalPrompter.swift b/apps/macos/Sources/OpenClaw/DevicePairingApprovalPrompter.swift
index 73ae0188a39f3..f85e8d1a5df3f 100644
--- a/apps/macos/Sources/OpenClaw/DevicePairingApprovalPrompter.swift
+++ b/apps/macos/Sources/OpenClaw/DevicePairingApprovalPrompter.swift
@@ -1,8 +1,8 @@
import AppKit
-import OpenClawKit
-import OpenClawProtocol
import Foundation
import Observation
+import OpenClawKit
+import OpenClawProtocol
import OSLog
@MainActor
@@ -22,11 +22,6 @@ final class DevicePairingApprovalPrompter {
private var alertHostWindow: NSWindow?
private var resolvedByRequestId: Set = []
- private final class AlertHostWindow: NSWindow {
- override var canBecomeKey: Bool { true }
- override var canBecomeMain: Bool { true }
- }
-
private struct PairingList: Codable {
let pending: [PendingRequest]
let paired: [PairedDevice]?
@@ -55,7 +50,9 @@ final class DevicePairingApprovalPrompter {
let isRepair: Bool?
let ts: Double
- var id: String { self.requestId }
+ var id: String {
+ self.requestId
+ }
}
private struct PairingResolvedEvent: Codable {
@@ -231,35 +228,11 @@ final class DevicePairingApprovalPrompter {
}
private func endActiveAlert() {
- guard let alert = self.activeAlert else { return }
- if let parent = alert.window.sheetParent {
- parent.endSheet(alert.window, returnCode: .abort)
- }
- self.activeAlert = nil
- self.activeRequestId = nil
+ PairingAlertSupport.endActiveAlert(activeAlert: &self.activeAlert, activeRequestId: &self.activeRequestId)
}
private func requireAlertHostWindow() -> NSWindow {
- if let alertHostWindow {
- return alertHostWindow
- }
-
- let window = AlertHostWindow(
- contentRect: NSRect(x: 0, y: 0, width: 520, height: 1),
- styleMask: [.borderless],
- backing: .buffered,
- defer: false)
- window.title = ""
- window.isReleasedWhenClosed = false
- window.level = .floating
- window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
- window.isOpaque = false
- window.hasShadow = false
- window.backgroundColor = .clear
- window.ignoresMouseEvents = true
-
- self.alertHostWindow = window
- return window
+ PairingAlertSupport.requireAlertHostWindow(alertHostWindow: &self.alertHostWindow)
}
private func handle(push: GatewayPush) {
diff --git a/apps/macos/Sources/OpenClaw/ExecApprovals.swift b/apps/macos/Sources/OpenClaw/ExecApprovals.swift
index 21ab5b1749f53..f6bc839250385 100644
--- a/apps/macos/Sources/OpenClaw/ExecApprovals.swift
+++ b/apps/macos/Sources/OpenClaw/ExecApprovals.swift
@@ -8,7 +8,9 @@ enum ExecSecurity: String, CaseIterable, Codable, Identifiable {
case allowlist
case full
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var title: String {
switch self {
@@ -24,7 +26,9 @@ enum ExecApprovalQuickMode: String, CaseIterable, Identifiable {
case ask
case allow
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var title: String {
switch self {
@@ -67,7 +71,9 @@ enum ExecAsk: String, CaseIterable, Codable, Identifiable {
case onMiss = "on-miss"
case always
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var title: String {
switch self {
diff --git a/apps/macos/Sources/OpenClaw/ExecApprovalsGatewayPrompter.swift b/apps/macos/Sources/OpenClaw/ExecApprovalsGatewayPrompter.swift
index add04c73087ba..670fa891c5b1e 100644
--- a/apps/macos/Sources/OpenClaw/ExecApprovalsGatewayPrompter.swift
+++ b/apps/macos/Sources/OpenClaw/ExecApprovalsGatewayPrompter.swift
@@ -1,7 +1,7 @@
-import OpenClawKit
-import OpenClawProtocol
import CoreGraphics
import Foundation
+import OpenClawKit
+import OpenClawProtocol
import OSLog
@MainActor
diff --git a/apps/macos/Sources/OpenClaw/ExecApprovalsSocket.swift b/apps/macos/Sources/OpenClaw/ExecApprovalsSocket.swift
index c87dd1e5884f3..e1432aaea1c2c 100644
--- a/apps/macos/Sources/OpenClaw/ExecApprovalsSocket.swift
+++ b/apps/macos/Sources/OpenClaw/ExecApprovalsSocket.swift
@@ -1,8 +1,8 @@
import AppKit
-import OpenClawKit
import CryptoKit
import Darwin
import Foundation
+import OpenClawKit
import OSLog
struct ExecApprovalPromptRequest: Codable, Sendable {
@@ -76,7 +76,9 @@ private struct ExecHostResponse: Codable {
enum ExecApprovalsSocketClient {
private struct TimeoutError: LocalizedError {
var message: String
- var errorDescription: String? { self.message }
+ var errorDescription: String? {
+ self.message
+ }
}
static func requestDecision(
diff --git a/apps/macos/Sources/OpenClaw/GatewayConnection.swift b/apps/macos/Sources/OpenClaw/GatewayConnection.swift
index 4cf4d18b15111..0d7d582dd3357 100644
--- a/apps/macos/Sources/OpenClaw/GatewayConnection.swift
+++ b/apps/macos/Sources/OpenClaw/GatewayConnection.swift
@@ -1,7 +1,7 @@
+import Foundation
import OpenClawChatUI
import OpenClawKit
import OpenClawProtocol
-import Foundation
import OSLog
private let gatewayConnectionLogger = Logger(subsystem: "ai.openclaw", category: "gateway.connection")
@@ -24,9 +24,13 @@ enum GatewayAgentChannel: String, Codable, CaseIterable, Sendable {
self = GatewayAgentChannel(rawValue: normalized) ?? .last
}
- var isDeliverable: Bool { self != .webchat }
+ var isDeliverable: Bool {
+ self != .webchat
+ }
- func shouldDeliver(_ deliver: Bool) -> Bool { deliver && self.isDeliverable }
+ func shouldDeliver(_ deliver: Bool) -> Bool {
+ deliver && self.isDeliverable
+ }
}
struct GatewayAgentInvocation: Sendable {
diff --git a/apps/macos/Sources/OpenClaw/GatewayDiscoveryHelpers.swift b/apps/macos/Sources/OpenClaw/GatewayDiscoveryHelpers.swift
index a533b92ebb9dc..281dcb9e8bd4c 100644
--- a/apps/macos/Sources/OpenClaw/GatewayDiscoveryHelpers.swift
+++ b/apps/macos/Sources/OpenClaw/GatewayDiscoveryHelpers.swift
@@ -1,5 +1,5 @@
-import OpenClawDiscovery
import Foundation
+import OpenClawDiscovery
enum GatewayDiscoveryHelpers {
static func sshTarget(for gateway: GatewayDiscoveryModel.DiscoveredGateway) -> String? {
diff --git a/apps/macos/Sources/OpenClaw/GatewayEnvironment.swift b/apps/macos/Sources/OpenClaw/GatewayEnvironment.swift
index 1e10394c2d277..059eb4da6e0cc 100644
--- a/apps/macos/Sources/OpenClaw/GatewayEnvironment.swift
+++ b/apps/macos/Sources/OpenClaw/GatewayEnvironment.swift
@@ -1,14 +1,16 @@
-import OpenClawIPC
import Foundation
+import OpenClawIPC
import OSLog
-// Lightweight SemVer helper (major.minor.patch only) for gateway compatibility checks.
+/// Lightweight SemVer helper (major.minor.patch only) for gateway compatibility checks.
struct Semver: Comparable, CustomStringConvertible, Sendable {
let major: Int
let minor: Int
let patch: Int
- var description: String { "\(self.major).\(self.minor).\(self.patch)" }
+ var description: String {
+ "\(self.major).\(self.minor).\(self.patch)"
+ }
static func < (lhs: Semver, rhs: Semver) -> Bool {
if lhs.major != rhs.major { return lhs.major < rhs.major }
@@ -93,7 +95,7 @@ enum GatewayEnvironment {
return (trimmed?.isEmpty == false) ? trimmed : nil
}
- // Exposed for tests so we can inject fake version checks without rewriting bundle metadata.
+ /// Exposed for tests so we can inject fake version checks without rewriting bundle metadata.
static func expectedGatewayVersion(from versionString: String?) -> Semver? {
Semver.parse(versionString)
}
diff --git a/apps/macos/Sources/OpenClaw/GeneralSettings.swift b/apps/macos/Sources/OpenClaw/GeneralSettings.swift
index 40a105d1cbbc2..d55f7c1b01583 100644
--- a/apps/macos/Sources/OpenClaw/GeneralSettings.swift
+++ b/apps/macos/Sources/OpenClaw/GeneralSettings.swift
@@ -1,8 +1,8 @@
import AppKit
+import Observation
import OpenClawDiscovery
import OpenClawIPC
import OpenClawKit
-import Observation
import SwiftUI
struct GeneralSettings: View {
@@ -16,8 +16,13 @@ struct GeneralSettings: View {
@State private var remoteStatus: RemoteStatus = .idle
@State private var showRemoteAdvanced = false
private let isPreview = ProcessInfo.processInfo.isPreview
- private var isNixMode: Bool { ProcessInfo.processInfo.isNixMode }
- private var remoteLabelWidth: CGFloat { 88 }
+ private var isNixMode: Bool {
+ ProcessInfo.processInfo.isNixMode
+ }
+
+ private var remoteLabelWidth: CGFloat {
+ 88
+ }
var body: some View {
ScrollView(.vertical) {
diff --git a/apps/macos/Sources/OpenClaw/HealthStore.swift b/apps/macos/Sources/OpenClaw/HealthStore.swift
index 4fb08f0c3da79..22c1409fca77d 100644
--- a/apps/macos/Sources/OpenClaw/HealthStore.swift
+++ b/apps/macos/Sources/OpenClaw/HealthStore.swift
@@ -89,8 +89,8 @@ final class HealthStore {
}
}
- // Test-only escape hatch: the HealthStore is a process-wide singleton but
- // state derivation is pure from `snapshot` + `lastError`.
+ /// Test-only escape hatch: the HealthStore is a process-wide singleton but
+ /// state derivation is pure from `snapshot` + `lastError`.
func __setSnapshotForTest(_ snapshot: HealthSnapshot?, lastError: String? = nil) {
self.snapshot = snapshot
self.lastError = lastError
diff --git a/apps/macos/Sources/OpenClaw/IconState.swift b/apps/macos/Sources/OpenClaw/IconState.swift
index ec27385835428..c2eab0e501046 100644
--- a/apps/macos/Sources/OpenClaw/IconState.swift
+++ b/apps/macos/Sources/OpenClaw/IconState.swift
@@ -72,7 +72,9 @@ enum IconOverrideSelection: String, CaseIterable, Identifiable {
case mainBash, mainRead, mainWrite, mainEdit, mainOther
case otherBash, otherRead, otherWrite, otherEdit, otherOther
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var label: String {
switch self {
diff --git a/apps/macos/Sources/OpenClaw/InstancesStore.swift b/apps/macos/Sources/OpenClaw/InstancesStore.swift
index 1f9dce6cb9a2e..566340337db69 100644
--- a/apps/macos/Sources/OpenClaw/InstancesStore.swift
+++ b/apps/macos/Sources/OpenClaw/InstancesStore.swift
@@ -1,8 +1,8 @@
-import OpenClawKit
-import OpenClawProtocol
import Cocoa
import Foundation
import Observation
+import OpenClawKit
+import OpenClawProtocol
import OSLog
struct InstanceInfo: Identifiable, Codable {
@@ -158,7 +158,7 @@ final class InstancesStore {
private func localFallbackInstance(reason: String) -> InstanceInfo {
let host = Host.current().localizedName ?? "this-mac"
- let ip = Self.primaryIPv4Address()
+ let ip = SystemPresenceInfo.primaryIPv4Address()
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
let osVersion = ProcessInfo.processInfo.operatingSystemVersion
let platform = "macos \(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)"
@@ -172,58 +172,13 @@ final class InstancesStore {
platform: platform,
deviceFamily: "Mac",
modelIdentifier: InstanceIdentity.modelIdentifier,
- lastInputSeconds: Self.lastInputSeconds(),
+ lastInputSeconds: SystemPresenceInfo.lastInputSeconds(),
mode: "local",
reason: reason,
text: text,
ts: ts)
}
- private static func lastInputSeconds() -> Int? {
- let anyEvent = CGEventType(rawValue: UInt32.max) ?? .null
- let seconds = CGEventSource.secondsSinceLastEventType(.combinedSessionState, eventType: anyEvent)
- if seconds.isNaN || seconds.isInfinite || seconds < 0 { return nil }
- return Int(seconds.rounded())
- }
-
- private static func primaryIPv4Address() -> String? {
- var addrList: UnsafeMutablePointer?
- guard getifaddrs(&addrList) == 0, let first = addrList else { return nil }
- defer { freeifaddrs(addrList) }
-
- var fallback: String?
- var en0: String?
-
- for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) {
- let flags = Int32(ptr.pointee.ifa_flags)
- let isUp = (flags & IFF_UP) != 0
- let isLoopback = (flags & IFF_LOOPBACK) != 0
- let name = String(cString: ptr.pointee.ifa_name)
- let family = ptr.pointee.ifa_addr.pointee.sa_family
- if !isUp || isLoopback || family != UInt8(AF_INET) { continue }
-
- var addr = ptr.pointee.ifa_addr.pointee
- var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
- let result = getnameinfo(
- &addr,
- socklen_t(ptr.pointee.ifa_addr.pointee.sa_len),
- &buffer,
- socklen_t(buffer.count),
- nil,
- 0,
- NI_NUMERICHOST)
- guard result == 0 else { continue }
- let len = buffer.prefix { $0 != 0 }
- let bytes = len.map { UInt8(bitPattern: $0) }
- guard let ip = String(bytes: bytes, encoding: .utf8) else { continue }
-
- if name == "en0" { en0 = ip; break }
- if fallback == nil { fallback = ip }
- }
-
- return en0 ?? fallback
- }
-
// MARK: - Helpers
/// Keep the last raw payload for logging.
diff --git a/apps/macos/Sources/OpenClaw/LogLocator.swift b/apps/macos/Sources/OpenClaw/LogLocator.swift
index 927b7892a2800..b504ab02acecb 100644
--- a/apps/macos/Sources/OpenClaw/LogLocator.swift
+++ b/apps/macos/Sources/OpenClaw/LogLocator.swift
@@ -7,8 +7,7 @@ enum LogLocator {
{
return URL(fileURLWithPath: override)
}
- let preferred = URL(fileURLWithPath: "/tmp/openclaw")
- return preferred
+ return URL(fileURLWithPath: "/tmp/openclaw")
}
private static var stdoutLog: URL {
diff --git a/apps/macos/Sources/OpenClaw/Logging/OpenClawLogging.swift b/apps/macos/Sources/OpenClaw/Logging/OpenClawLogging.swift
index bd46a8e6ff095..7692887e6c7ec 100644
--- a/apps/macos/Sources/OpenClaw/Logging/OpenClawLogging.swift
+++ b/apps/macos/Sources/OpenClaw/Logging/OpenClawLogging.swift
@@ -37,7 +37,9 @@ enum AppLogLevel: String, CaseIterable, Identifiable {
static let `default`: AppLogLevel = .info
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var title: String {
switch self {
diff --git a/apps/macos/Sources/OpenClaw/MenuBar.swift b/apps/macos/Sources/OpenClaw/MenuBar.swift
index 406d4e063dcbf..00e2a9be0a635 100644
--- a/apps/macos/Sources/OpenClaw/MenuBar.swift
+++ b/apps/macos/Sources/OpenClaw/MenuBar.swift
@@ -345,7 +345,7 @@ protocol UpdaterProviding: AnyObject {
func checkForUpdates(_ sender: Any?)
}
-// No-op updater used for debug/dev runs to suppress Sparkle dialogs.
+/// No-op updater used for debug/dev runs to suppress Sparkle dialogs.
final class DisabledUpdaterController: UpdaterProviding {
var automaticallyChecksForUpdates: Bool = false
var automaticallyDownloadsUpdates: Bool = false
@@ -394,7 +394,9 @@ final class SparkleUpdaterController: NSObject, UpdaterProviding {
set { self.controller.updater.automaticallyDownloadsUpdates = newValue }
}
- var isAvailable: Bool { true }
+ var isAvailable: Bool {
+ true
+ }
func checkForUpdates(_ sender: Any?) {
self.controller.checkForUpdates(sender)
diff --git a/apps/macos/Sources/OpenClaw/MenuContentView.swift b/apps/macos/Sources/OpenClaw/MenuContentView.swift
index fd1b437cf7cb7..3416d23f81211 100644
--- a/apps/macos/Sources/OpenClaw/MenuContentView.swift
+++ b/apps/macos/Sources/OpenClaw/MenuContentView.swift
@@ -400,7 +400,6 @@ struct MenuContent: View {
}
}
- @ViewBuilder
private func statusLine(label: String, color: Color) -> some View {
HStack(spacing: 6) {
Circle()
@@ -590,6 +589,8 @@ struct MenuContent: View {
private struct AudioInputDevice: Identifiable, Equatable {
let uid: String
let name: String
- var id: String { self.uid }
+ var id: String {
+ self.uid
+ }
}
}
diff --git a/apps/macos/Sources/OpenClaw/MenuHighlightedHostView.swift b/apps/macos/Sources/OpenClaw/MenuHighlightedHostView.swift
index f1e85cba1528f..7107946989ecb 100644
--- a/apps/macos/Sources/OpenClaw/MenuHighlightedHostView.swift
+++ b/apps/macos/Sources/OpenClaw/MenuHighlightedHostView.swift
@@ -22,7 +22,9 @@ final class HighlightedMenuItemHostView: NSView {
}
@available(*, unavailable)
- required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
override var intrinsicContentSize: NSSize {
let size = self.hosting.fittingSize
diff --git a/apps/macos/Sources/OpenClaw/MenuSessionsInjector.swift b/apps/macos/Sources/OpenClaw/MenuSessionsInjector.swift
index 9b6bb09934135..37fd6ca25052b 100644
--- a/apps/macos/Sources/OpenClaw/MenuSessionsInjector.swift
+++ b/apps/macos/Sources/OpenClaw/MenuSessionsInjector.swift
@@ -159,7 +159,9 @@ final class MenuSessionsInjector: NSObject, NSMenuDelegate {
extension MenuSessionsInjector {
// MARK: - Injection
- private var mainSessionKey: String { WorkActivityStore.shared.mainSessionKey }
+ private var mainSessionKey: String {
+ WorkActivityStore.shared.mainSessionKey
+ }
private func inject(into menu: NSMenu) {
self.cancelPreviewTasks()
@@ -1175,8 +1177,7 @@ extension MenuSessionsInjector {
private func makeHostedView(rootView: AnyView, width: CGFloat, highlighted: Bool) -> NSView {
if highlighted {
- let container = HighlightedMenuItemHostView(rootView: rootView, width: width)
- return container
+ return HighlightedMenuItemHostView(rootView: rootView, width: width)
}
let hosting = NSHostingView(rootView: rootView)
diff --git a/apps/macos/Sources/OpenClaw/MicLevelMonitor.swift b/apps/macos/Sources/OpenClaw/MicLevelMonitor.swift
index af72740a676f5..e35057d28cfab 100644
--- a/apps/macos/Sources/OpenClaw/MicLevelMonitor.swift
+++ b/apps/macos/Sources/OpenClaw/MicLevelMonitor.swift
@@ -64,8 +64,7 @@ actor MicLevelMonitor {
}
let rms = sqrt(sum / Float(frameCount) + 1e-12)
let db = 20 * log10(Double(rms))
- let normalized = max(0, min(1, (db + 50) / 50))
- return normalized
+ return max(0, min(1, (db + 50) / 50))
}
}
diff --git a/apps/macos/Sources/OpenClaw/ModelCatalogLoader.swift b/apps/macos/Sources/OpenClaw/ModelCatalogLoader.swift
index ff966e1eabcea..b320c84d2327e 100644
--- a/apps/macos/Sources/OpenClaw/ModelCatalogLoader.swift
+++ b/apps/macos/Sources/OpenClaw/ModelCatalogLoader.swift
@@ -2,7 +2,10 @@ import Foundation
import JavaScriptCore
enum ModelCatalogLoader {
- static var defaultPath: String { self.resolveDefaultPath() }
+ static var defaultPath: String {
+ self.resolveDefaultPath()
+ }
+
private static let logger = Logger(subsystem: "ai.openclaw", category: "models")
private nonisolated static let appSupportDir: URL = {
let base = FileManager().urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
diff --git a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeLocationService.swift b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeLocationService.swift
index db404aa6e171f..bd4df512ca499 100644
--- a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeLocationService.swift
+++ b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeLocationService.swift
@@ -1,6 +1,6 @@
-import OpenClawKit
import CoreLocation
import Foundation
+import OpenClawKit
@MainActor
final class MacNodeLocationService: NSObject, CLLocationManagerDelegate {
diff --git a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeModeCoordinator.swift b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeModeCoordinator.swift
index eed0755f9b75c..af46788c9ccd7 100644
--- a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeModeCoordinator.swift
+++ b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeModeCoordinator.swift
@@ -1,5 +1,5 @@
-import OpenClawKit
import Foundation
+import OpenClawKit
import OSLog
@MainActor
diff --git a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntime.swift b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntime.swift
index 0b88f159098ed..60bd95f2894be 100644
--- a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntime.swift
+++ b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntime.swift
@@ -1,7 +1,7 @@
import AppKit
+import Foundation
import OpenClawIPC
import OpenClawKit
-import Foundation
actor MacNodeRuntime {
private let cameraCapture = CameraCaptureService()
diff --git a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntimeMainActorServices.swift b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntimeMainActorServices.swift
index 982ec8bf90f9e..733410b186015 100644
--- a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntimeMainActorServices.swift
+++ b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntimeMainActorServices.swift
@@ -1,6 +1,6 @@
-import OpenClawKit
import CoreLocation
import Foundation
+import OpenClawKit
@MainActor
protocol MacNodeRuntimeMainActorServices: Sendable {
diff --git a/apps/macos/Sources/OpenClaw/NodePairingApprovalPrompter.swift b/apps/macos/Sources/OpenClaw/NodePairingApprovalPrompter.swift
index 9853294662432..ee994b38f6505 100644
--- a/apps/macos/Sources/OpenClaw/NodePairingApprovalPrompter.swift
+++ b/apps/macos/Sources/OpenClaw/NodePairingApprovalPrompter.swift
@@ -1,10 +1,10 @@
import AppKit
+import Foundation
+import Observation
import OpenClawDiscovery
import OpenClawIPC
import OpenClawKit
import OpenClawProtocol
-import Foundation
-import Observation
import OSLog
import UserNotifications
@@ -38,11 +38,6 @@ final class NodePairingApprovalPrompter {
private var remoteResolutionsByRequestId: [String: PairingResolution] = [:]
private var autoApproveAttempts: Set = []
- private final class AlertHostWindow: NSWindow {
- override var canBecomeKey: Bool { true }
- override var canBecomeMain: Bool { true }
- }
-
private struct PairingList: Codable {
let pending: [PendingRequest]
let paired: [PairedNode]?
@@ -68,7 +63,9 @@ final class NodePairingApprovalPrompter {
let silent: Bool?
let ts: Double
- var id: String { self.requestId }
+ var id: String {
+ self.requestId
+ }
}
private struct PairingResolvedEvent: Codable {
@@ -235,35 +232,11 @@ final class NodePairingApprovalPrompter {
}
private func endActiveAlert() {
- guard let alert = self.activeAlert else { return }
- if let parent = alert.window.sheetParent {
- parent.endSheet(alert.window, returnCode: .abort)
- }
- self.activeAlert = nil
- self.activeRequestId = nil
+ PairingAlertSupport.endActiveAlert(activeAlert: &self.activeAlert, activeRequestId: &self.activeRequestId)
}
private func requireAlertHostWindow() -> NSWindow {
- if let alertHostWindow {
- return alertHostWindow
- }
-
- let window = AlertHostWindow(
- contentRect: NSRect(x: 0, y: 0, width: 520, height: 1),
- styleMask: [.borderless],
- backing: .buffered,
- defer: false)
- window.title = ""
- window.isReleasedWhenClosed = false
- window.level = .floating
- window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
- window.isOpaque = false
- window.hasShadow = false
- window.backgroundColor = .clear
- window.ignoresMouseEvents = true
-
- self.alertHostWindow = window
- return window
+ PairingAlertSupport.requireAlertHostWindow(alertHostWindow: &self.alertHostWindow)
}
private func handle(push: GatewayPush) {
diff --git a/apps/macos/Sources/OpenClaw/NodesStore.swift b/apps/macos/Sources/OpenClaw/NodesStore.swift
index 6ea5fbe90876d..5cc94858645bc 100644
--- a/apps/macos/Sources/OpenClaw/NodesStore.swift
+++ b/apps/macos/Sources/OpenClaw/NodesStore.swift
@@ -18,9 +18,17 @@ struct NodeInfo: Identifiable, Codable {
let paired: Bool?
let connected: Bool?
- var id: String { self.nodeId }
- var isConnected: Bool { self.connected ?? false }
- var isPaired: Bool { self.paired ?? false }
+ var id: String {
+ self.nodeId
+ }
+
+ var isConnected: Bool {
+ self.connected ?? false
+ }
+
+ var isPaired: Bool {
+ self.paired ?? false
+ }
}
private struct NodeListResponse: Codable {
diff --git a/apps/macos/Sources/OpenClaw/NotificationManager.swift b/apps/macos/Sources/OpenClaw/NotificationManager.swift
index f522e6317643a..b8e6fcddc8cec 100644
--- a/apps/macos/Sources/OpenClaw/NotificationManager.swift
+++ b/apps/macos/Sources/OpenClaw/NotificationManager.swift
@@ -1,5 +1,5 @@
-import OpenClawIPC
import Foundation
+import OpenClawIPC
import Security
import UserNotifications
diff --git a/apps/macos/Sources/OpenClaw/NotifyOverlay.swift b/apps/macos/Sources/OpenClaw/NotifyOverlay.swift
index 1191c7e22227a..31157b0d831b5 100644
--- a/apps/macos/Sources/OpenClaw/NotifyOverlay.swift
+++ b/apps/macos/Sources/OpenClaw/NotifyOverlay.swift
@@ -10,7 +10,9 @@ final class NotifyOverlayController {
static let shared = NotifyOverlayController()
private(set) var model = Model()
- var isVisible: Bool { self.model.isVisible }
+ var isVisible: Bool {
+ self.model.isVisible
+ }
struct Model {
var title: String = ""
diff --git a/apps/macos/Sources/OpenClaw/Onboarding.swift b/apps/macos/Sources/OpenClaw/Onboarding.swift
index def8af4b2197d..b8a6377b419e6 100644
--- a/apps/macos/Sources/OpenClaw/Onboarding.swift
+++ b/apps/macos/Sources/OpenClaw/Onboarding.swift
@@ -1,9 +1,9 @@
import AppKit
+import Combine
+import Observation
import OpenClawChatUI
import OpenClawDiscovery
import OpenClawIPC
-import Combine
-import Observation
import SwiftUI
enum UIStrings {
@@ -142,18 +142,30 @@ struct OnboardingView: View {
Self.pageOrder(for: self.state.connectionMode, showOnboardingChat: self.showOnboardingChat)
}
- var pageCount: Int { self.pageOrder.count }
+ var pageCount: Int {
+ self.pageOrder.count
+ }
+
var activePageIndex: Int {
self.activePageIndex(for: self.currentPage)
}
- var buttonTitle: String { self.currentPage == self.pageCount - 1 ? "Finish" : "Next" }
- var wizardPageOrderIndex: Int? { self.pageOrder.firstIndex(of: self.wizardPageIndex) }
+ var buttonTitle: String {
+ self.currentPage == self.pageCount - 1 ? "Finish" : "Next"
+ }
+
+ var wizardPageOrderIndex: Int? {
+ self.pageOrder.firstIndex(of: self.wizardPageIndex)
+ }
+
var isWizardBlocking: Bool {
self.activePageIndex == self.wizardPageIndex && !self.onboardingWizard.isComplete
}
- var canAdvance: Bool { !self.isWizardBlocking }
+ var canAdvance: Bool {
+ !self.isWizardBlocking
+ }
+
var devLinkCommand: String {
let version = GatewayEnvironment.expectedGatewayVersionString() ?? "latest"
return "npm install -g openclaw@\(version)"
diff --git a/apps/macos/Sources/OpenClaw/OnboardingView+Actions.swift b/apps/macos/Sources/OpenClaw/OnboardingView+Actions.swift
index 47cce949db63f..ba43424aa9a76 100644
--- a/apps/macos/Sources/OpenClaw/OnboardingView+Actions.swift
+++ b/apps/macos/Sources/OpenClaw/OnboardingView+Actions.swift
@@ -1,7 +1,7 @@
import AppKit
+import Foundation
import OpenClawDiscovery
import OpenClawIPC
-import Foundation
import SwiftUI
extension OnboardingView {
diff --git a/apps/macos/Sources/OpenClaw/OnboardingView+Monitoring.swift b/apps/macos/Sources/OpenClaw/OnboardingView+Monitoring.swift
index 64ddc332e4ac0..dfbdf91d44d8f 100644
--- a/apps/macos/Sources/OpenClaw/OnboardingView+Monitoring.swift
+++ b/apps/macos/Sources/OpenClaw/OnboardingView+Monitoring.swift
@@ -1,5 +1,5 @@
-import OpenClawIPC
import Foundation
+import OpenClawIPC
extension OnboardingView {
@MainActor
diff --git a/apps/macos/Sources/OpenClaw/OnboardingView+Pages.swift b/apps/macos/Sources/OpenClaw/OnboardingView+Pages.swift
index 309c4aa026e69..5760bfff8c20d 100644
--- a/apps/macos/Sources/OpenClaw/OnboardingView+Pages.swift
+++ b/apps/macos/Sources/OpenClaw/OnboardingView+Pages.swift
@@ -206,7 +206,9 @@ extension OnboardingView {
.textFieldStyle(.roundedBorder)
.frame(width: fieldWidth)
}
- if let message = CommandResolver.sshTargetValidationMessage(self.state.remoteTarget) {
+ if let message = CommandResolver
+ .sshTargetValidationMessage(self.state.remoteTarget)
+ {
GridRow {
Text("")
.frame(width: labelWidth, alignment: .leading)
diff --git a/apps/macos/Sources/OpenClaw/OnboardingView+Wizard.swift b/apps/macos/Sources/OpenClaw/OnboardingView+Wizard.swift
index 51424fdb78c85..0c77f1e327dd7 100644
--- a/apps/macos/Sources/OpenClaw/OnboardingView+Wizard.swift
+++ b/apps/macos/Sources/OpenClaw/OnboardingView+Wizard.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Observation
+import OpenClawProtocol
import SwiftUI
extension OnboardingView {
diff --git a/apps/macos/Sources/OpenClaw/OnboardingView+Workspace.swift b/apps/macos/Sources/OpenClaw/OnboardingView+Workspace.swift
index 0b413433666b7..1895b2af94f7a 100644
--- a/apps/macos/Sources/OpenClaw/OnboardingView+Workspace.swift
+++ b/apps/macos/Sources/OpenClaw/OnboardingView+Workspace.swift
@@ -23,7 +23,7 @@ extension OnboardingView {
} catch {
self.workspaceStatus = "Failed to create workspace: \(error.localizedDescription)"
}
- case let .unsafe(reason):
+ case let .unsafe (reason):
self.workspaceStatus = "Workspace not touched: \(reason)"
}
self.refreshBootstrapStatus()
@@ -54,7 +54,7 @@ extension OnboardingView {
do {
let url = AgentWorkspace.resolveWorkspaceURL(from: self.workspacePath)
- if case let .unsafe(reason) = AgentWorkspace.bootstrapSafety(for: url) {
+ if case let .unsafe (reason) = AgentWorkspace.bootstrapSafety(for: url) {
self.workspaceStatus = "Workspace not created: \(reason)"
return
}
diff --git a/apps/macos/Sources/OpenClaw/OnboardingWizard.swift b/apps/macos/Sources/OpenClaw/OnboardingWizard.swift
index 412826650a66f..75b9522a4d100 100644
--- a/apps/macos/Sources/OpenClaw/OnboardingWizard.swift
+++ b/apps/macos/Sources/OpenClaw/OnboardingWizard.swift
@@ -1,7 +1,7 @@
-import OpenClawKit
-import OpenClawProtocol
import Foundation
import Observation
+import OpenClawKit
+import OpenClawProtocol
import OSLog
import SwiftUI
@@ -41,8 +41,13 @@ final class OnboardingWizardModel {
private var restartAttempts = 0
private let maxRestartAttempts = 1
- var isComplete: Bool { self.status == "done" }
- var isRunning: Bool { self.status == "running" }
+ var isComplete: Bool {
+ self.status == "done"
+ }
+
+ var isRunning: Bool {
+ self.status == "running"
+ }
func reset() {
self.sessionId = nil
@@ -408,5 +413,7 @@ private struct WizardOptionItem: Identifiable {
let index: Int
let option: WizardOption
- var id: Int { self.index }
+ var id: Int {
+ self.index
+ }
}
diff --git a/apps/macos/Sources/OpenClaw/OpenClawConfigFile.swift b/apps/macos/Sources/OpenClaw/OpenClawConfigFile.swift
index fc66030e3f52d..f49f2b7e0d4fd 100644
--- a/apps/macos/Sources/OpenClaw/OpenClawConfigFile.swift
+++ b/apps/macos/Sources/OpenClaw/OpenClawConfigFile.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Foundation
+import OpenClawProtocol
enum OpenClawConfigFile {
private static let logger = Logger(subsystem: "ai.openclaw", category: "config")
diff --git a/apps/macos/Sources/OpenClaw/OpenClawPaths.swift b/apps/macos/Sources/OpenClaw/OpenClawPaths.swift
index 632c07c802bdf..206031f9aa19b 100644
--- a/apps/macos/Sources/OpenClaw/OpenClawPaths.swift
+++ b/apps/macos/Sources/OpenClaw/OpenClawPaths.swift
@@ -24,8 +24,7 @@ enum OpenClawPaths {
}
}
let home = FileManager().homeDirectoryForCurrentUser
- let preferred = home.appendingPathComponent(".openclaw", isDirectory: true)
- return preferred
+ return home.appendingPathComponent(".openclaw", isDirectory: true)
}
private static func resolveConfigCandidate(in dir: URL) -> URL? {
diff --git a/apps/macos/Sources/OpenClaw/PairingAlertSupport.swift b/apps/macos/Sources/OpenClaw/PairingAlertSupport.swift
new file mode 100644
index 0000000000000..e8e4428bf3fd6
--- /dev/null
+++ b/apps/macos/Sources/OpenClaw/PairingAlertSupport.swift
@@ -0,0 +1,46 @@
+import AppKit
+
+final class PairingAlertHostWindow: NSWindow {
+ override var canBecomeKey: Bool {
+ true
+ }
+
+ override var canBecomeMain: Bool {
+ true
+ }
+}
+
+@MainActor
+enum PairingAlertSupport {
+ static func endActiveAlert(activeAlert: inout NSAlert?, activeRequestId: inout String?) {
+ guard let alert = activeAlert else { return }
+ if let parent = alert.window.sheetParent {
+ parent.endSheet(alert.window, returnCode: .abort)
+ }
+ activeAlert = nil
+ activeRequestId = nil
+ }
+
+ static func requireAlertHostWindow(alertHostWindow: inout NSWindow?) -> NSWindow {
+ if let alertHostWindow {
+ return alertHostWindow
+ }
+
+ let window = PairingAlertHostWindow(
+ contentRect: NSRect(x: 0, y: 0, width: 520, height: 1),
+ styleMask: [.borderless],
+ backing: .buffered,
+ defer: false)
+ window.title = ""
+ window.isReleasedWhenClosed = false
+ window.level = .floating
+ window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
+ window.isOpaque = false
+ window.hasShadow = false
+ window.backgroundColor = .clear
+ window.ignoresMouseEvents = true
+
+ alertHostWindow = window
+ return window
+ }
+}
diff --git a/apps/macos/Sources/OpenClaw/PermissionManager.swift b/apps/macos/Sources/OpenClaw/PermissionManager.swift
index 3cf1cba3f6ec8..b5bcd167a4641 100644
--- a/apps/macos/Sources/OpenClaw/PermissionManager.swift
+++ b/apps/macos/Sources/OpenClaw/PermissionManager.swift
@@ -1,11 +1,11 @@
import AppKit
import ApplicationServices
import AVFoundation
-import OpenClawIPC
import CoreGraphics
import CoreLocation
import Foundation
import Observation
+import OpenClawIPC
import Speech
import UserNotifications
@@ -336,7 +336,7 @@ final class LocationPermissionRequester: NSObject, CLLocationManagerDelegate {
cont.resume(returning: status)
}
- // nonisolated for Swift 6 strict concurrency compatibility
+ /// nonisolated for Swift 6 strict concurrency compatibility
nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
let status = manager.authorizationStatus
Task { @MainActor in
@@ -344,7 +344,7 @@ final class LocationPermissionRequester: NSObject, CLLocationManagerDelegate {
}
}
- // Legacy callback (still used on some macOS versions / configurations).
+ /// Legacy callback (still used on some macOS versions / configurations).
nonisolated func locationManager(
_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus)
diff --git a/apps/macos/Sources/OpenClaw/PermissionsSettings.swift b/apps/macos/Sources/OpenClaw/PermissionsSettings.swift
index a8f6accf8af7b..de15e5ebb63d1 100644
--- a/apps/macos/Sources/OpenClaw/PermissionsSettings.swift
+++ b/apps/macos/Sources/OpenClaw/PermissionsSettings.swift
@@ -1,6 +1,6 @@
+import CoreLocation
import OpenClawIPC
import OpenClawKit
-import CoreLocation
import SwiftUI
struct PermissionsSettings: View {
@@ -164,7 +164,9 @@ struct PermissionRow: View {
.padding(.vertical, self.compact ? 4 : 6)
}
- private var iconSize: CGFloat { self.compact ? 28 : 32 }
+ private var iconSize: CGFloat {
+ self.compact ? 28 : 32
+ }
private var title: String {
switch self.capability {
diff --git a/apps/macos/Sources/OpenClaw/PortGuardian.swift b/apps/macos/Sources/OpenClaw/PortGuardian.swift
index 98225f30e1e56..7ab7e8def3f77 100644
--- a/apps/macos/Sources/OpenClaw/PortGuardian.swift
+++ b/apps/macos/Sources/OpenClaw/PortGuardian.swift
@@ -103,7 +103,9 @@ actor PortGuardian {
let status: Status
let listeners: [ReportListener]
- var id: Int { self.port }
+ var id: Int {
+ self.port
+ }
var offenders: [ReportListener] {
if case let .interference(_, offenders) = self.status { return offenders }
@@ -141,7 +143,9 @@ actor PortGuardian {
let user: String?
let expected: Bool
- var id: Int32 { self.pid }
+ var id: Int32 {
+ self.pid
+ }
}
func diagnose(mode: AppState.ConnectionMode) async -> [PortReport] {
diff --git a/apps/macos/Sources/OpenClaw/PresenceReporter.swift b/apps/macos/Sources/OpenClaw/PresenceReporter.swift
index 16d70b8a92c0c..2e7a1d4c472c4 100644
--- a/apps/macos/Sources/OpenClaw/PresenceReporter.swift
+++ b/apps/macos/Sources/OpenClaw/PresenceReporter.swift
@@ -1,5 +1,4 @@
import Cocoa
-import Darwin
import Foundation
import OSLog
@@ -33,10 +32,10 @@ final class PresenceReporter {
private func push(reason: String) async {
let mode = await MainActor.run { AppStateStore.shared.connectionMode.rawValue }
let host = InstanceIdentity.displayName
- let ip = Self.primaryIPv4Address() ?? "ip-unknown"
+ let ip = SystemPresenceInfo.primaryIPv4Address() ?? "ip-unknown"
let version = Self.appVersionString()
let platform = Self.platformString()
- let lastInput = Self.lastInputSeconds()
+ let lastInput = SystemPresenceInfo.lastInputSeconds()
let text = Self.composePresenceSummary(mode: mode, reason: reason)
var params: [String: AnyHashable] = [
"instanceId": AnyHashable(self.instanceId),
@@ -64,9 +63,9 @@ final class PresenceReporter {
private static func composePresenceSummary(mode: String, reason: String) -> String {
let host = InstanceIdentity.displayName
- let ip = Self.primaryIPv4Address() ?? "ip-unknown"
+ let ip = SystemPresenceInfo.primaryIPv4Address() ?? "ip-unknown"
let version = Self.appVersionString()
- let lastInput = Self.lastInputSeconds()
+ let lastInput = SystemPresenceInfo.lastInputSeconds()
let lastLabel = lastInput.map { "last input \($0)s ago" } ?? "last input unknown"
return "Node: \(host) (\(ip)) · app \(version) · \(lastLabel) · mode \(mode) · reason \(reason)"
}
@@ -87,50 +86,7 @@ final class PresenceReporter {
return "macos \(v.majorVersion).\(v.minorVersion).\(v.patchVersion)"
}
- private static func lastInputSeconds() -> Int? {
- let anyEvent = CGEventType(rawValue: UInt32.max) ?? .null
- let seconds = CGEventSource.secondsSinceLastEventType(.combinedSessionState, eventType: anyEvent)
- if seconds.isNaN || seconds.isInfinite || seconds < 0 { return nil }
- return Int(seconds.rounded())
- }
-
- private static func primaryIPv4Address() -> String? {
- var addrList: UnsafeMutablePointer?
- guard getifaddrs(&addrList) == 0, let first = addrList else { return nil }
- defer { freeifaddrs(addrList) }
-
- var fallback: String?
- var en0: String?
-
- for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) {
- let flags = Int32(ptr.pointee.ifa_flags)
- let isUp = (flags & IFF_UP) != 0
- let isLoopback = (flags & IFF_LOOPBACK) != 0
- let name = String(cString: ptr.pointee.ifa_name)
- let family = ptr.pointee.ifa_addr.pointee.sa_family
- if !isUp || isLoopback || family != UInt8(AF_INET) { continue }
-
- var addr = ptr.pointee.ifa_addr.pointee
- var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
- let result = getnameinfo(
- &addr,
- socklen_t(ptr.pointee.ifa_addr.pointee.sa_len),
- &buffer,
- socklen_t(buffer.count),
- nil,
- 0,
- NI_NUMERICHOST)
- guard result == 0 else { continue }
- let len = buffer.prefix { $0 != 0 }
- let bytes = len.map { UInt8(bitPattern: $0) }
- guard let ip = String(bytes: bytes, encoding: .utf8) else { continue }
-
- if name == "en0" { en0 = ip; break }
- if fallback == nil { fallback = ip }
- }
-
- return en0 ?? fallback
- }
+ // (SystemPresenceInfo) last input + primary IPv4.
}
#if DEBUG
@@ -148,11 +104,11 @@ extension PresenceReporter {
}
static func _testLastInputSeconds() -> Int? {
- self.lastInputSeconds()
+ SystemPresenceInfo.lastInputSeconds()
}
static func _testPrimaryIPv4Address() -> String? {
- self.primaryIPv4Address()
+ SystemPresenceInfo.primaryIPv4Address()
}
}
#endif
diff --git a/apps/macos/Sources/OpenClaw/ProcessInfo+OpenClaw.swift b/apps/macos/Sources/OpenClaw/ProcessInfo+OpenClaw.swift
index d05e593388ea0..a219f49533664 100644
--- a/apps/macos/Sources/OpenClaw/ProcessInfo+OpenClaw.swift
+++ b/apps/macos/Sources/OpenClaw/ProcessInfo+OpenClaw.swift
@@ -12,8 +12,8 @@ extension ProcessInfo {
environment: [String: String],
standard: UserDefaults,
stableSuite: UserDefaults?,
- isAppBundle: Bool
- ) -> Bool {
+ isAppBundle: Bool) -> Bool
+ {
if environment["OPENCLAW_NIX_MODE"] == "1" { return true }
if standard.bool(forKey: "openclaw.nixMode") { return true }
diff --git a/apps/macos/Sources/OpenClaw/Resources/Info.plist b/apps/macos/Sources/OpenClaw/Resources/Info.plist
index 51081d43df58d..580a1ef00635c 100644
--- a/apps/macos/Sources/OpenClaw/Resources/Info.plist
+++ b/apps/macos/Sources/OpenClaw/Resources/Info.plist
@@ -15,9 +15,9 @@
CFBundlePackageTypeAPPLCFBundleShortVersionString
- 2026.2.13
+ 2026.2.19CFBundleVersion
- 202602130
+ 202602190CFBundleIconFileOpenClawCFBundleURLTypes
diff --git a/apps/macos/Sources/OpenClaw/RuntimeLocator.swift b/apps/macos/Sources/OpenClaw/RuntimeLocator.swift
index 8ec23a067be98..3112f57879b1c 100644
--- a/apps/macos/Sources/OpenClaw/RuntimeLocator.swift
+++ b/apps/macos/Sources/OpenClaw/RuntimeLocator.swift
@@ -10,7 +10,9 @@ struct RuntimeVersion: Comparable, CustomStringConvertible {
let minor: Int
let patch: Int
- var description: String { "\(self.major).\(self.minor).\(self.patch)" }
+ var description: String {
+ "\(self.major).\(self.minor).\(self.patch)"
+ }
static func < (lhs: RuntimeVersion, rhs: RuntimeVersion) -> Bool {
if lhs.major != rhs.major { return lhs.major < rhs.major }
@@ -163,5 +165,7 @@ enum RuntimeLocator {
}
extension RuntimeKind {
- fileprivate var binaryName: String { "node" }
+ fileprivate var binaryName: String {
+ "node"
+ }
}
diff --git a/apps/macos/Sources/OpenClaw/SessionData.swift b/apps/macos/Sources/OpenClaw/SessionData.swift
index defd4fe8aa113..8234cbdef854a 100644
--- a/apps/macos/Sources/OpenClaw/SessionData.swift
+++ b/apps/macos/Sources/OpenClaw/SessionData.swift
@@ -84,8 +84,13 @@ struct SessionRow: Identifiable {
let tokens: SessionTokenStats
let model: String?
- var ageText: String { relativeAge(from: self.updatedAt) }
- var label: String { self.displayName ?? self.key }
+ var ageText: String {
+ relativeAge(from: self.updatedAt)
+ }
+
+ var label: String {
+ self.displayName ?? self.key
+ }
var flagLabels: [String] {
var flags: [String] = []
diff --git a/apps/macos/Sources/OpenClaw/SessionMenuLabelView.swift b/apps/macos/Sources/OpenClaw/SessionMenuLabelView.swift
index 1cbeedd392d6d..51646e0a36a33 100644
--- a/apps/macos/Sources/OpenClaw/SessionMenuLabelView.swift
+++ b/apps/macos/Sources/OpenClaw/SessionMenuLabelView.swift
@@ -1,14 +1,7 @@
import SwiftUI
-private struct MenuItemHighlightedKey: EnvironmentKey {
- static let defaultValue = false
-}
-
extension EnvironmentValues {
- var menuItemHighlighted: Bool {
- get { self[MenuItemHighlightedKey.self] }
- set { self[MenuItemHighlightedKey.self] = newValue }
- }
+ @Entry var menuItemHighlighted: Bool = false
}
struct SessionMenuLabelView: View {
diff --git a/apps/macos/Sources/OpenClaw/SessionMenuPreviewView.swift b/apps/macos/Sources/OpenClaw/SessionMenuPreviewView.swift
index dc129df9f41e8..8840bce5569ac 100644
--- a/apps/macos/Sources/OpenClaw/SessionMenuPreviewView.swift
+++ b/apps/macos/Sources/OpenClaw/SessionMenuPreviewView.swift
@@ -183,7 +183,6 @@ struct SessionMenuPreviewView: View {
.frame(width: max(1, self.width), alignment: .leading)
}
- @ViewBuilder
private func previewRow(_ item: SessionPreviewItem) -> some View {
HStack(alignment: .top, spacing: 4) {
Text(item.role.label)
@@ -212,7 +211,6 @@ struct SessionMenuPreviewView: View {
}
}
- @ViewBuilder
private func placeholder(_ text: String) -> some View {
Text(text)
.font(.caption)
@@ -227,7 +225,9 @@ enum SessionMenuPreviewLoader {
private static let previewMaxChars = 240
private struct PreviewTimeoutError: LocalizedError {
- var errorDescription: String? { "preview timeout" }
+ var errorDescription: String? {
+ "preview timeout"
+ }
}
static func prewarm(sessionKeys: [String], maxItems: Int) async {
diff --git a/apps/macos/Sources/OpenClaw/SessionsSettings.swift b/apps/macos/Sources/OpenClaw/SessionsSettings.swift
index 4a2a0e81e0297..826f1128f54d0 100644
--- a/apps/macos/Sources/OpenClaw/SessionsSettings.swift
+++ b/apps/macos/Sources/OpenClaw/SessionsSettings.swift
@@ -85,7 +85,6 @@ struct SessionsSettings: View {
}
}
- @ViewBuilder
private func sessionRow(_ row: SessionRow) -> some View {
VStack(alignment: .leading, spacing: 6) {
HStack(alignment: .firstTextBaseline, spacing: 8) {
diff --git a/apps/macos/Sources/OpenClaw/ShellExecutor.swift b/apps/macos/Sources/OpenClaw/ShellExecutor.swift
index 9633f0f8da0a6..ec757441a15e1 100644
--- a/apps/macos/Sources/OpenClaw/ShellExecutor.swift
+++ b/apps/macos/Sources/OpenClaw/ShellExecutor.swift
@@ -1,5 +1,5 @@
-import OpenClawIPC
import Foundation
+import OpenClawIPC
enum ShellExecutor {
struct ShellResult {
@@ -69,7 +69,7 @@ enum ShellExecutor {
if let timeout, timeout > 0 {
let nanos = UInt64(timeout * 1_000_000_000)
- let result = await withTaskGroup(of: ShellResult.self) { group in
+ return await withTaskGroup(of: ShellResult.self) { group in
group.addTask { await waitTask.value }
group.addTask {
try? await Task.sleep(nanoseconds: nanos)
@@ -87,7 +87,6 @@ enum ShellExecutor {
group.cancelAll()
return first
}
- return result
}
return await waitTask.value
diff --git a/apps/macos/Sources/OpenClaw/SkillsModels.swift b/apps/macos/Sources/OpenClaw/SkillsModels.swift
index 1fb40d99f1597..d143484c40f67 100644
--- a/apps/macos/Sources/OpenClaw/SkillsModels.swift
+++ b/apps/macos/Sources/OpenClaw/SkillsModels.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Foundation
+import OpenClawProtocol
struct SkillsStatusReport: Codable {
let workspaceDir: String
@@ -25,7 +25,9 @@ struct SkillStatus: Codable, Identifiable {
let configChecks: [SkillStatusConfigCheck]
let install: [SkillInstallOption]
- var id: String { self.name }
+ var id: String {
+ self.name
+ }
}
struct SkillRequirements: Codable {
@@ -45,7 +47,9 @@ struct SkillStatusConfigCheck: Codable, Identifiable {
let value: AnyCodable?
let satisfied: Bool
- var id: String { self.path }
+ var id: String {
+ self.path
+ }
}
struct SkillInstallOption: Codable, Identifiable {
diff --git a/apps/macos/Sources/OpenClaw/SkillsSettings.swift b/apps/macos/Sources/OpenClaw/SkillsSettings.swift
index 83aaa66c55db4..02db8495112d4 100644
--- a/apps/macos/Sources/OpenClaw/SkillsSettings.swift
+++ b/apps/macos/Sources/OpenClaw/SkillsSettings.swift
@@ -1,5 +1,5 @@
-import OpenClawProtocol
import Observation
+import OpenClawProtocol
import SwiftUI
struct SkillsSettings: View {
@@ -142,7 +142,9 @@ private enum SkillsFilter: String, CaseIterable, Identifiable {
case needsSetup
case disabled
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var title: String {
switch self {
@@ -171,24 +173,16 @@ private struct SkillRow: View {
let onInstall: (SkillInstallOption, InstallTarget) -> Void
let onSetEnv: (String, Bool) -> Void
- private var missingBins: [String] { self.skill.missing.bins }
- private var missingEnv: [String] { self.skill.missing.env }
- private var missingConfig: [String] { self.skill.missing.config }
-
- init(
- skill: SkillStatus,
- isBusy: Bool,
- connectionMode: AppState.ConnectionMode,
- onToggleEnabled: @escaping (Bool) -> Void,
- onInstall: @escaping (SkillInstallOption, InstallTarget) -> Void,
- onSetEnv: @escaping (String, Bool) -> Void)
- {
- self.skill = skill
- self.isBusy = isBusy
- self.connectionMode = connectionMode
- self.onToggleEnabled = onToggleEnabled
- self.onInstall = onInstall
- self.onSetEnv = onSetEnv
+ private var missingBins: [String] {
+ self.skill.missing.bins
+ }
+
+ private var missingEnv: [String] {
+ self.skill.missing.env
+ }
+
+ private var missingConfig: [String] {
+ self.skill.missing.config
}
var body: some View {
@@ -274,7 +268,6 @@ private struct SkillRow: View {
set: { self.onToggleEnabled($0) })
}
- @ViewBuilder
private var missingSummary: some View {
VStack(alignment: .leading, spacing: 4) {
if self.shouldShowMissingBins {
@@ -295,7 +288,6 @@ private struct SkillRow: View {
}
}
- @ViewBuilder
private var configChecksView: some View {
VStack(alignment: .leading, spacing: 4) {
ForEach(self.skill.configChecks) { check in
@@ -326,7 +318,6 @@ private struct SkillRow: View {
}
}
- @ViewBuilder
private var trailingActions: some View {
VStack(alignment: .trailing, spacing: 8) {
if !self.installOptions.isEmpty {
@@ -438,7 +429,9 @@ private struct EnvEditorState: Identifiable {
let envKey: String
let isPrimary: Bool
- var id: String { "\(self.skillKey)::\(self.envKey)" }
+ var id: String {
+ "\(self.skillKey)::\(self.envKey)"
+ }
}
private struct EnvEditorView: View {
diff --git a/apps/macos/Sources/OpenClaw/SoundEffects.swift b/apps/macos/Sources/OpenClaw/SoundEffects.swift
index b321238295df9..37df8455f8f09 100644
--- a/apps/macos/Sources/OpenClaw/SoundEffects.swift
+++ b/apps/macos/Sources/OpenClaw/SoundEffects.swift
@@ -10,7 +10,9 @@ enum SoundEffectCatalog {
return ["Glass"] + sorted
}
- static func displayName(for raw: String) -> String { raw }
+ static func displayName(for raw: String) -> String {
+ raw
+ }
static func url(for name: String) -> URL? {
self.discoveredSoundMap[name]
diff --git a/apps/macos/Sources/OpenClaw/SystemPresenceInfo.swift b/apps/macos/Sources/OpenClaw/SystemPresenceInfo.swift
new file mode 100644
index 0000000000000..843ed371fb55d
--- /dev/null
+++ b/apps/macos/Sources/OpenClaw/SystemPresenceInfo.swift
@@ -0,0 +1,16 @@
+import CoreGraphics
+import Foundation
+import OpenClawKit
+
+enum SystemPresenceInfo {
+ static func lastInputSeconds() -> Int? {
+ let anyEvent = CGEventType(rawValue: UInt32.max) ?? .null
+ let seconds = CGEventSource.secondsSinceLastEventType(.combinedSessionState, eventType: anyEvent)
+ if seconds.isNaN || seconds.isInfinite || seconds < 0 { return nil }
+ return Int(seconds.rounded())
+ }
+
+ static func primaryIPv4Address() -> String? {
+ NetworkInterfaces.primaryIPv4Address()
+ }
+}
diff --git a/apps/macos/Sources/OpenClaw/SystemRunSettingsView.swift b/apps/macos/Sources/OpenClaw/SystemRunSettingsView.swift
index eef826c3f0c71..b9bd6bd0c8cc5 100644
--- a/apps/macos/Sources/OpenClaw/SystemRunSettingsView.swift
+++ b/apps/macos/Sources/OpenClaw/SystemRunSettingsView.swift
@@ -150,7 +150,9 @@ private enum ExecApprovalsSettingsTab: String, CaseIterable, Identifiable {
case policy
case allowlist
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var title: String {
switch self {
diff --git a/apps/macos/Sources/OpenClaw/TailscaleIntegrationSection.swift b/apps/macos/Sources/OpenClaw/TailscaleIntegrationSection.swift
index c1a3a3489a69d..c9354d38bc225 100644
--- a/apps/macos/Sources/OpenClaw/TailscaleIntegrationSection.swift
+++ b/apps/macos/Sources/OpenClaw/TailscaleIntegrationSection.swift
@@ -5,7 +5,9 @@ private enum GatewayTailscaleMode: String, CaseIterable, Identifiable {
case serve
case funnel
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var label: String {
switch self {
diff --git a/apps/macos/Sources/OpenClaw/TailscaleService.swift b/apps/macos/Sources/OpenClaw/TailscaleService.swift
index b7f716a427047..2cefa69d59d40 100644
--- a/apps/macos/Sources/OpenClaw/TailscaleService.swift
+++ b/apps/macos/Sources/OpenClaw/TailscaleService.swift
@@ -1,10 +1,8 @@
import AppKit
import Foundation
import Observation
+import OpenClawDiscovery
import os
-#if canImport(Darwin)
-import Darwin
-#endif
/// Manages Tailscale integration and status checking.
@Observable
@@ -140,7 +138,7 @@ final class TailscaleService {
self.logger.info("Tailscale API not responding; app likely not running")
}
- if self.tailscaleIP == nil, let fallback = Self.detectTailnetIPv4() {
+ if self.tailscaleIP == nil, let fallback = TailscaleNetwork.detectTailnetIPv4() {
self.tailscaleIP = fallback
if !self.isRunning {
self.isRunning = true
@@ -178,49 +176,7 @@ final class TailscaleService {
}
}
- private nonisolated static func isTailnetIPv4(_ address: String) -> Bool {
- let parts = address.split(separator: ".")
- guard parts.count == 4 else { return false }
- let octets = parts.compactMap { Int($0) }
- guard octets.count == 4 else { return false }
- let a = octets[0]
- let b = octets[1]
- return a == 100 && b >= 64 && b <= 127
- }
-
- private nonisolated static func detectTailnetIPv4() -> String? {
- var addrList: UnsafeMutablePointer?
- guard getifaddrs(&addrList) == 0, let first = addrList else { return nil }
- defer { freeifaddrs(addrList) }
-
- for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) {
- let flags = Int32(ptr.pointee.ifa_flags)
- let isUp = (flags & IFF_UP) != 0
- let isLoopback = (flags & IFF_LOOPBACK) != 0
- let family = ptr.pointee.ifa_addr.pointee.sa_family
- if !isUp || isLoopback || family != UInt8(AF_INET) { continue }
-
- var addr = ptr.pointee.ifa_addr.pointee
- var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
- let result = getnameinfo(
- &addr,
- socklen_t(ptr.pointee.ifa_addr.pointee.sa_len),
- &buffer,
- socklen_t(buffer.count),
- nil,
- 0,
- NI_NUMERICHOST)
- guard result == 0 else { continue }
- let len = buffer.prefix { $0 != 0 }
- let bytes = len.map { UInt8(bitPattern: $0) }
- guard let ip = String(bytes: bytes, encoding: .utf8) else { continue }
- if Self.isTailnetIPv4(ip) { return ip }
- }
-
- return nil
- }
-
nonisolated static func fallbackTailnetIPv4() -> String? {
- self.detectTailnetIPv4()
+ TailscaleNetwork.detectTailnetIPv4()
}
}
diff --git a/apps/macos/Sources/OpenClaw/TalkModeRuntime.swift b/apps/macos/Sources/OpenClaw/TalkModeRuntime.swift
index 9ef7b010fa80f..47b041a5873e6 100644
--- a/apps/macos/Sources/OpenClaw/TalkModeRuntime.swift
+++ b/apps/macos/Sources/OpenClaw/TalkModeRuntime.swift
@@ -1,7 +1,7 @@
import AVFoundation
+import Foundation
import OpenClawChatUI
import OpenClawKit
-import Foundation
import OSLog
import Speech
diff --git a/apps/macos/Sources/OpenClaw/TalkOverlayView.swift b/apps/macos/Sources/OpenClaw/TalkOverlayView.swift
index a24ba17437481..80599d55ec338 100644
--- a/apps/macos/Sources/OpenClaw/TalkOverlayView.swift
+++ b/apps/macos/Sources/OpenClaw/TalkOverlayView.swift
@@ -99,8 +99,13 @@ private final class OrbInteractionNSView: NSView {
private var didDrag = false
private var suppressSingleClick = false
- override var acceptsFirstResponder: Bool { true }
- override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+ override var acceptsFirstResponder: Bool {
+ true
+ }
+
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
+ true
+ }
override func mouseDown(with event: NSEvent) {
self.mouseDownEvent = event
diff --git a/apps/macos/Sources/OpenClaw/UsageData.swift b/apps/macos/Sources/OpenClaw/UsageData.swift
index 7800054c66c73..3886c966edb1c 100644
--- a/apps/macos/Sources/OpenClaw/UsageData.swift
+++ b/apps/macos/Sources/OpenClaw/UsageData.swift
@@ -41,8 +41,7 @@ struct UsageRow: Identifiable {
var remainingPercent: Int? {
guard let usedPercent, usedPercent.isFinite else { return nil }
- let remaining = max(0, min(100, Int(round(100 - usedPercent))))
- return remaining
+ return max(0, min(100, Int(round(100 - usedPercent))))
}
func detailText(now: Date = .init()) -> String {
diff --git a/apps/macos/Sources/OpenClaw/VoicePushToTalk.swift b/apps/macos/Sources/OpenClaw/VoicePushToTalk.swift
index 819bafd127149..e535ebd6616f9 100644
--- a/apps/macos/Sources/OpenClaw/VoicePushToTalk.swift
+++ b/apps/macos/Sources/OpenClaw/VoicePushToTalk.swift
@@ -122,7 +122,7 @@ actor VoicePushToTalk {
private var recognitionTask: SFSpeechRecognitionTask?
private var tapInstalled = false
- // Session token used to drop stale callbacks when a new capture starts.
+ /// Session token used to drop stale callbacks when a new capture starts.
private var sessionID = UUID()
private var committed: String = ""
diff --git a/apps/macos/Sources/OpenClaw/VoiceWakeChime.swift b/apps/macos/Sources/OpenClaw/VoiceWakeChime.swift
index c41ecf4fd4358..8a25838997669 100644
--- a/apps/macos/Sources/OpenClaw/VoiceWakeChime.swift
+++ b/apps/macos/Sources/OpenClaw/VoiceWakeChime.swift
@@ -28,7 +28,9 @@ enum VoiceWakeChime: Codable, Equatable, Sendable {
enum VoiceWakeChimeCatalog {
/// Options shown in the picker.
- static var systemOptions: [String] { SoundEffectCatalog.systemOptions }
+ static var systemOptions: [String] {
+ SoundEffectCatalog.systemOptions
+ }
static func displayName(for raw: String) -> String {
SoundEffectCatalog.displayName(for: raw)
diff --git a/apps/macos/Sources/OpenClaw/VoiceWakeGlobalSettingsSync.swift b/apps/macos/Sources/OpenClaw/VoiceWakeGlobalSettingsSync.swift
index fd888c8aa4fdc..af4fae356ee12 100644
--- a/apps/macos/Sources/OpenClaw/VoiceWakeGlobalSettingsSync.swift
+++ b/apps/macos/Sources/OpenClaw/VoiceWakeGlobalSettingsSync.swift
@@ -1,5 +1,5 @@
-import OpenClawKit
import Foundation
+import OpenClawKit
import OSLog
@MainActor
diff --git a/apps/macos/Sources/OpenClaw/VoiceWakeOverlay.swift b/apps/macos/Sources/OpenClaw/VoiceWakeOverlay.swift
index 7e5ffe76c1068..04bbfd69db021 100644
--- a/apps/macos/Sources/OpenClaw/VoiceWakeOverlay.swift
+++ b/apps/macos/Sources/OpenClaw/VoiceWakeOverlay.swift
@@ -18,7 +18,9 @@ final class VoiceWakeOverlayController {
enum Source: String { case wakeWord, pushToTalk }
var model = Model()
- var isVisible: Bool { self.model.isVisible }
+ var isVisible: Bool {
+ self.model.isVisible
+ }
struct Model {
var text: String = ""
diff --git a/apps/macos/Sources/OpenClaw/VoiceWakeOverlayTextViews.swift b/apps/macos/Sources/OpenClaw/VoiceWakeOverlayTextViews.swift
index 151db8c9324d5..8e88c86d45d17 100644
--- a/apps/macos/Sources/OpenClaw/VoiceWakeOverlayTextViews.swift
+++ b/apps/macos/Sources/OpenClaw/VoiceWakeOverlayTextViews.swift
@@ -11,7 +11,9 @@ struct TranscriptTextView: NSViewRepresentable {
var onEndEditing: () -> Void
var onSend: () -> Void
- func makeCoordinator() -> Coordinator { Coordinator(self) }
+ func makeCoordinator() -> Coordinator {
+ Coordinator(self)
+ }
func makeNSView(context: Context) -> NSScrollView {
let textView = TranscriptNSTextView()
@@ -77,7 +79,9 @@ struct TranscriptTextView: NSViewRepresentable {
var parent: TranscriptTextView
var isProgrammaticUpdate = false
- init(_ parent: TranscriptTextView) { self.parent = parent }
+ init(_ parent: TranscriptTextView) {
+ self.parent = parent
+ }
func textDidBeginEditing(_ notification: Notification) {
self.parent.onBeginEditing()
@@ -147,7 +151,9 @@ private final class ClickCatcher: NSView {
}
@available(*, unavailable)
- required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
diff --git a/apps/macos/Sources/OpenClaw/VoiceWakeOverlayView.swift b/apps/macos/Sources/OpenClaw/VoiceWakeOverlayView.swift
index 48055c10a6c37..516da776ace16 100644
--- a/apps/macos/Sources/OpenClaw/VoiceWakeOverlayView.swift
+++ b/apps/macos/Sources/OpenClaw/VoiceWakeOverlayView.swift
@@ -131,7 +131,9 @@ private struct OverlayBackground: View {
}
extension OverlayBackground: @MainActor Equatable {
- static func == (lhs: Self, rhs: Self) -> Bool { true }
+ static func == (lhs: Self, rhs: Self) -> Bool {
+ true
+ }
}
struct CloseHoverButton: View {
diff --git a/apps/macos/Sources/OpenClaw/VoiceWakeRuntime.swift b/apps/macos/Sources/OpenClaw/VoiceWakeRuntime.swift
index 7ef86c28507e1..61f913b9da889 100644
--- a/apps/macos/Sources/OpenClaw/VoiceWakeRuntime.swift
+++ b/apps/macos/Sources/OpenClaw/VoiceWakeRuntime.swift
@@ -48,10 +48,10 @@ actor VoiceWakeRuntime {
private var isStarting: Bool = false
private var triggerOnlyTask: Task?
- // Tunables
- // Silence threshold once we've captured user speech (post-trigger).
+ /// Tunables
+ /// Silence threshold once we've captured user speech (post-trigger).
private let silenceWindow: TimeInterval = 2.0
- // Silence threshold when we only heard the trigger but no post-trigger speech yet.
+ /// Silence threshold when we only heard the trigger but no post-trigger speech yet.
private let triggerOnlySilenceWindow: TimeInterval = 5.0
// Maximum capture duration from trigger until we force-send, to avoid runaway sessions.
private let captureHardStop: TimeInterval = 120.0
diff --git a/apps/macos/Sources/OpenClaw/VoiceWakeSettings.swift b/apps/macos/Sources/OpenClaw/VoiceWakeSettings.swift
index ca4f4a203553e..d4413618e11cb 100644
--- a/apps/macos/Sources/OpenClaw/VoiceWakeSettings.swift
+++ b/apps/macos/Sources/OpenClaw/VoiceWakeSettings.swift
@@ -29,7 +29,9 @@ struct VoiceWakeSettings: View {
private struct AudioInputDevice: Identifiable, Equatable {
let uid: String
let name: String
- var id: String { self.uid }
+ var id: String {
+ self.uid
+ }
}
private struct TriggerEntry: Identifiable {
diff --git a/apps/macos/Sources/OpenClaw/WebChatManager.swift b/apps/macos/Sources/OpenClaw/WebChatManager.swift
index 2f77692de820d..61d1b4d39b7b6 100644
--- a/apps/macos/Sources/OpenClaw/WebChatManager.swift
+++ b/apps/macos/Sources/OpenClaw/WebChatManager.swift
@@ -3,8 +3,13 @@ import Foundation
/// A borderless panel that can still accept key focus (needed for typing).
final class WebChatPanel: NSPanel {
- override var canBecomeKey: Bool { true }
- override var canBecomeMain: Bool { true }
+ override var canBecomeKey: Bool {
+ true
+ }
+
+ override var canBecomeMain: Bool {
+ true
+ }
}
enum WebChatPresentation {
diff --git a/apps/macos/Sources/OpenClaw/WebChatSwiftUI.swift b/apps/macos/Sources/OpenClaw/WebChatSwiftUI.swift
index d6b4417f06af3..5b866304b090f 100644
--- a/apps/macos/Sources/OpenClaw/WebChatSwiftUI.swift
+++ b/apps/macos/Sources/OpenClaw/WebChatSwiftUI.swift
@@ -1,8 +1,8 @@
import AppKit
+import Foundation
import OpenClawChatUI
import OpenClawKit
import OpenClawProtocol
-import Foundation
import OSLog
import QuartzCore
import SwiftUI
diff --git a/apps/macos/Sources/OpenClaw/WorkActivityStore.swift b/apps/macos/Sources/OpenClaw/WorkActivityStore.swift
index b6fd97477fc24..77d6296303002 100644
--- a/apps/macos/Sources/OpenClaw/WorkActivityStore.swift
+++ b/apps/macos/Sources/OpenClaw/WorkActivityStore.swift
@@ -1,7 +1,7 @@
-import OpenClawKit
-import OpenClawProtocol
import Foundation
import Observation
+import OpenClawKit
+import OpenClawProtocol
import SwiftUI
@MainActor
@@ -31,7 +31,9 @@ final class WorkActivityStore {
private var mainSessionKeyStorage = "main"
private let toolResultGrace: TimeInterval = 2.0
- var mainSessionKey: String { self.mainSessionKeyStorage }
+ var mainSessionKey: String {
+ self.mainSessionKeyStorage
+ }
func handleJob(sessionKey: String, state: String) {
let isStart = state.lowercased() == "started" || state.lowercased() == "streaming"
diff --git a/apps/macos/Sources/OpenClawDiscovery/GatewayDiscoveryModel.swift b/apps/macos/Sources/OpenClawDiscovery/GatewayDiscoveryModel.swift
index 27548d90657f0..abd18efaa9a41 100644
--- a/apps/macos/Sources/OpenClawDiscovery/GatewayDiscoveryModel.swift
+++ b/apps/macos/Sources/OpenClawDiscovery/GatewayDiscoveryModel.swift
@@ -1,7 +1,7 @@
-import OpenClawKit
import Foundation
import Network
import Observation
+import OpenClawKit
import OSLog
@MainActor
@@ -18,7 +18,10 @@ public final class GatewayDiscoveryModel {
}
public struct DiscoveredGateway: Identifiable, Equatable, Sendable {
- public var id: String { self.stableID }
+ public var id: String {
+ self.stableID
+ }
+
public var displayName: String
// Resolved service endpoint (SRV + A/AAAA). Used for routing; do not trust TXT for routing.
public var serviceHost: String?
@@ -326,43 +329,9 @@ public final class GatewayDiscoveryModel {
}
private func updateStatusText() {
- let states = Array(self.statesByDomain.values)
- if states.isEmpty {
- self.statusText = self.browsers.isEmpty ? "Idle" : "Setup"
- return
- }
-
- if let failed = states.first(where: { state in
- if case .failed = state { return true }
- return false
- }) {
- if case let .failed(err) = failed {
- self.statusText = "Failed: \(err)"
- return
- }
- }
-
- if let waiting = states.first(where: { state in
- if case .waiting = state { return true }
- return false
- }) {
- if case let .waiting(err) = waiting {
- self.statusText = "Waiting: \(err)"
- return
- }
- }
-
- if states.contains(where: { if case .ready = $0 { true } else { false } }) {
- self.statusText = "Searching…"
- return
- }
-
- if states.contains(where: { if case .setup = $0 { true } else { false } }) {
- self.statusText = "Setup"
- return
- }
-
- self.statusText = "Searching…"
+ self.statusText = GatewayDiscoveryStatusText.make(
+ states: Array(self.statesByDomain.values),
+ hasBrowsers: !self.browsers.isEmpty)
}
private static func txtDictionary(from result: NWBrowser.Result) -> [String: String] {
diff --git a/apps/macos/Sources/OpenClawDiscovery/TailscaleNetwork.swift b/apps/macos/Sources/OpenClawDiscovery/TailscaleNetwork.swift
new file mode 100644
index 0000000000000..ef78e6f400ff1
--- /dev/null
+++ b/apps/macos/Sources/OpenClawDiscovery/TailscaleNetwork.swift
@@ -0,0 +1,46 @@
+import Darwin
+import Foundation
+
+public enum TailscaleNetwork {
+ public static func isTailnetIPv4(_ address: String) -> Bool {
+ let parts = address.split(separator: ".")
+ guard parts.count == 4 else { return false }
+ let octets = parts.compactMap { Int($0) }
+ guard octets.count == 4 else { return false }
+ let a = octets[0]
+ let b = octets[1]
+ return a == 100 && b >= 64 && b <= 127
+ }
+
+ public static func detectTailnetIPv4() -> String? {
+ var addrList: UnsafeMutablePointer?
+ guard getifaddrs(&addrList) == 0, let first = addrList else { return nil }
+ defer { freeifaddrs(addrList) }
+
+ for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) {
+ let flags = Int32(ptr.pointee.ifa_flags)
+ let isUp = (flags & IFF_UP) != 0
+ let isLoopback = (flags & IFF_LOOPBACK) != 0
+ let family = ptr.pointee.ifa_addr.pointee.sa_family
+ if !isUp || isLoopback || family != UInt8(AF_INET) { continue }
+
+ var addr = ptr.pointee.ifa_addr.pointee
+ var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
+ let result = getnameinfo(
+ &addr,
+ socklen_t(ptr.pointee.ifa_addr.pointee.sa_len),
+ &buffer,
+ socklen_t(buffer.count),
+ nil,
+ 0,
+ NI_NUMERICHOST)
+ guard result == 0 else { continue }
+ let len = buffer.prefix { $0 != 0 }
+ let bytes = len.map { UInt8(bitPattern: $0) }
+ guard let ip = String(bytes: bytes, encoding: .utf8) else { continue }
+ if self.isTailnetIPv4(ip) { return ip }
+ }
+
+ return nil
+ }
+}
diff --git a/apps/macos/Sources/OpenClawDiscovery/WideAreaGatewayDiscovery.swift b/apps/macos/Sources/OpenClawDiscovery/WideAreaGatewayDiscovery.swift
index bacff45d604cb..fea0aca91c15f 100644
--- a/apps/macos/Sources/OpenClawDiscovery/WideAreaGatewayDiscovery.swift
+++ b/apps/macos/Sources/OpenClawDiscovery/WideAreaGatewayDiscovery.swift
@@ -1,5 +1,5 @@
-import OpenClawKit
import Foundation
+import OpenClawKit
struct WideAreaGatewayBeacon: Sendable, Equatable {
var instanceName: String
@@ -117,13 +117,12 @@ enum WideAreaGatewayDiscovery {
}
var seen = Set()
- let ordered = ips.filter { value in
+ return ips.filter { value in
guard self.isTailnetIPv4(value) else { return false }
if seen.contains(value) { return false }
seen.insert(value)
return true
}
- return ordered
}
private static func readTailscaleStatus() -> String? {
@@ -370,5 +369,7 @@ private struct TailscaleStatus: Decodable {
}
extension Collection {
- fileprivate var nonEmpty: Self? { isEmpty ? nil : self }
+ fileprivate var nonEmpty: Self? {
+ isEmpty ? nil : self
+ }
}
diff --git a/apps/macos/Sources/OpenClawIPC/IPC.swift b/apps/macos/Sources/OpenClawIPC/IPC.swift
index 9560699d47fcd..13fbe8756ab15 100644
--- a/apps/macos/Sources/OpenClawIPC/IPC.swift
+++ b/apps/macos/Sources/OpenClawIPC/IPC.swift
@@ -407,11 +407,10 @@ extension Request: Codable {
}
}
-// Shared transport settings
+/// Shared transport settings
public let controlSocketPath: String = {
let home = FileManager().homeDirectoryForCurrentUser
- let preferred = home
+ return home
.appendingPathComponent("Library/Application Support/OpenClaw/control.sock")
.path
- return preferred
}()
diff --git a/apps/macos/Sources/OpenClawMacCLI/ConnectCommand.swift b/apps/macos/Sources/OpenClawMacCLI/ConnectCommand.swift
index 1c31ce3b05161..0989164a01e60 100644
--- a/apps/macos/Sources/OpenClawMacCLI/ConnectCommand.swift
+++ b/apps/macos/Sources/OpenClawMacCLI/ConnectCommand.swift
@@ -1,9 +1,7 @@
+import Foundation
+import OpenClawDiscovery
import OpenClawKit
import OpenClawProtocol
-import Foundation
-#if canImport(Darwin)
-import Darwin
-#endif
struct ConnectOptions {
var url: String?
@@ -301,7 +299,7 @@ private func resolvedPassword(opts: ConnectOptions, mode: String, config: Gatewa
private func resolveLocalHost(bind: String?) -> String {
let normalized = (bind ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
- let tailnetIP = detectTailnetIPv4()
+ let tailnetIP = TailscaleNetwork.detectTailnetIPv4()
switch normalized {
case "tailnet":
return tailnetIP ?? "127.0.0.1"
@@ -309,45 +307,3 @@ private func resolveLocalHost(bind: String?) -> String {
return "127.0.0.1"
}
}
-
-private func detectTailnetIPv4() -> String? {
- var addrList: UnsafeMutablePointer?
- guard getifaddrs(&addrList) == 0, let first = addrList else { return nil }
- defer { freeifaddrs(addrList) }
-
- for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) {
- let flags = Int32(ptr.pointee.ifa_flags)
- let isUp = (flags & IFF_UP) != 0
- let isLoopback = (flags & IFF_LOOPBACK) != 0
- let family = ptr.pointee.ifa_addr.pointee.sa_family
- if !isUp || isLoopback || family != UInt8(AF_INET) { continue }
-
- var addr = ptr.pointee.ifa_addr.pointee
- var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
- let result = getnameinfo(
- &addr,
- socklen_t(ptr.pointee.ifa_addr.pointee.sa_len),
- &buffer,
- socklen_t(buffer.count),
- nil,
- 0,
- NI_NUMERICHOST)
- guard result == 0 else { continue }
- let len = buffer.prefix { $0 != 0 }
- let bytes = len.map { UInt8(bitPattern: $0) }
- guard let ip = String(bytes: bytes, encoding: .utf8) else { continue }
- if isTailnetIPv4(ip) { return ip }
- }
-
- return nil
-}
-
-private func isTailnetIPv4(_ address: String) -> Bool {
- let parts = address.split(separator: ".")
- guard parts.count == 4 else { return false }
- let octets = parts.compactMap { Int($0) }
- guard octets.count == 4 else { return false }
- let a = octets[0]
- let b = octets[1]
- return a == 100 && b >= 64 && b <= 127
-}
diff --git a/apps/macos/Sources/OpenClawMacCLI/DiscoverCommand.swift b/apps/macos/Sources/OpenClawMacCLI/DiscoverCommand.swift
index 09ef2bbc051b2..b039ecdf41159 100644
--- a/apps/macos/Sources/OpenClawMacCLI/DiscoverCommand.swift
+++ b/apps/macos/Sources/OpenClawMacCLI/DiscoverCommand.swift
@@ -1,5 +1,5 @@
-import OpenClawDiscovery
import Foundation
+import OpenClawDiscovery
struct DiscoveryOptions {
var timeoutMs: Int = 2000
diff --git a/apps/macos/Sources/OpenClawMacCLI/WizardCommand.swift b/apps/macos/Sources/OpenClawMacCLI/WizardCommand.swift
index 898a8a31cfa3d..0a73fc2108c2b 100644
--- a/apps/macos/Sources/OpenClawMacCLI/WizardCommand.swift
+++ b/apps/macos/Sources/OpenClawMacCLI/WizardCommand.swift
@@ -1,7 +1,7 @@
-import OpenClawKit
-import OpenClawProtocol
import Darwin
import Foundation
+import OpenClawKit
+import OpenClawProtocol
struct WizardCliOptions {
var url: String?
diff --git a/apps/macos/Sources/OpenClawProtocol/GatewayModels.swift b/apps/macos/Sources/OpenClawProtocol/GatewayModels.swift
index a134b4fd5b4d2..661d5dc11fd0c 100644
--- a/apps/macos/Sources/OpenClawProtocol/GatewayModels.swift
+++ b/apps/macos/Sources/OpenClawProtocol/GatewayModels.swift
@@ -296,6 +296,7 @@ public struct Snapshot: Codable, Sendable {
public let statedir: String?
public let sessiondefaults: [String: AnyCodable]?
public let authmode: AnyCodable?
+ public let updateavailable: [String: AnyCodable]?
public init(
presence: [PresenceEntry],
@@ -305,7 +306,8 @@ public struct Snapshot: Codable, Sendable {
configpath: String?,
statedir: String?,
sessiondefaults: [String: AnyCodable]?,
- authmode: AnyCodable?
+ authmode: AnyCodable?,
+ updateavailable: [String: AnyCodable]?
) {
self.presence = presence
self.health = health
@@ -315,6 +317,7 @@ public struct Snapshot: Codable, Sendable {
self.statedir = statedir
self.sessiondefaults = sessiondefaults
self.authmode = authmode
+ self.updateavailable = updateavailable
}
private enum CodingKeys: String, CodingKey {
case presence
@@ -325,6 +328,7 @@ public struct Snapshot: Codable, Sendable {
case statedir = "stateDir"
case sessiondefaults = "sessionDefaults"
case authmode = "authMode"
+ case updateavailable = "updateAvailable"
}
}
@@ -394,6 +398,7 @@ public struct SendParams: Codable, Sendable {
public let gifplayback: Bool?
public let channel: String?
public let accountid: String?
+ public let threadid: String?
public let sessionkey: String?
public let idempotencykey: String
@@ -405,6 +410,7 @@ public struct SendParams: Codable, Sendable {
gifplayback: Bool?,
channel: String?,
accountid: String?,
+ threadid: String?,
sessionkey: String?,
idempotencykey: String
) {
@@ -415,6 +421,7 @@ public struct SendParams: Codable, Sendable {
self.gifplayback = gifplayback
self.channel = channel
self.accountid = accountid
+ self.threadid = threadid
self.sessionkey = sessionkey
self.idempotencykey = idempotencykey
}
@@ -426,6 +433,7 @@ public struct SendParams: Codable, Sendable {
case gifplayback = "gifPlayback"
case channel
case accountid = "accountId"
+ case threadid = "threadId"
case sessionkey = "sessionKey"
case idempotencykey = "idempotencyKey"
}
@@ -436,7 +444,11 @@ public struct PollParams: Codable, Sendable {
public let question: String
public let options: [String]
public let maxselections: Int?
+ public let durationseconds: Int?
public let durationhours: Int?
+ public let silent: Bool?
+ public let isanonymous: Bool?
+ public let threadid: String?
public let channel: String?
public let accountid: String?
public let idempotencykey: String
@@ -446,7 +458,11 @@ public struct PollParams: Codable, Sendable {
question: String,
options: [String],
maxselections: Int?,
+ durationseconds: Int?,
durationhours: Int?,
+ silent: Bool?,
+ isanonymous: Bool?,
+ threadid: String?,
channel: String?,
accountid: String?,
idempotencykey: String
@@ -455,7 +471,11 @@ public struct PollParams: Codable, Sendable {
self.question = question
self.options = options
self.maxselections = maxselections
+ self.durationseconds = durationseconds
self.durationhours = durationhours
+ self.silent = silent
+ self.isanonymous = isanonymous
+ self.threadid = threadid
self.channel = channel
self.accountid = accountid
self.idempotencykey = idempotencykey
@@ -465,7 +485,11 @@ public struct PollParams: Codable, Sendable {
case question
case options
case maxselections = "maxSelections"
+ case durationseconds = "durationSeconds"
case durationhours = "durationHours"
+ case silent
+ case isanonymous = "isAnonymous"
+ case threadid = "threadId"
case channel
case accountid = "accountId"
case idempotencykey = "idempotencyKey"
@@ -905,6 +929,68 @@ public struct NodeInvokeRequestEvent: Codable, Sendable {
}
}
+public struct PushTestParams: Codable, Sendable {
+ public let nodeid: String
+ public let title: String?
+ public let body: String?
+ public let environment: String?
+
+ public init(
+ nodeid: String,
+ title: String?,
+ body: String?,
+ environment: String?
+ ) {
+ self.nodeid = nodeid
+ self.title = title
+ self.body = body
+ self.environment = environment
+ }
+ private enum CodingKeys: String, CodingKey {
+ case nodeid = "nodeId"
+ case title
+ case body
+ case environment
+ }
+}
+
+public struct PushTestResult: Codable, Sendable {
+ public let ok: Bool
+ public let status: Int
+ public let apnsid: String?
+ public let reason: String?
+ public let tokensuffix: String
+ public let topic: String
+ public let environment: String
+
+ public init(
+ ok: Bool,
+ status: Int,
+ apnsid: String?,
+ reason: String?,
+ tokensuffix: String,
+ topic: String,
+ environment: String
+ ) {
+ self.ok = ok
+ self.status = status
+ self.apnsid = apnsid
+ self.reason = reason
+ self.tokensuffix = tokensuffix
+ self.topic = topic
+ self.environment = environment
+ }
+ private enum CodingKeys: String, CodingKey {
+ case ok
+ case status
+ case apnsid = "apnsId"
+ case reason
+ case tokensuffix = "tokenSuffix"
+ case topic
+ case environment
+ }
+}
+
public struct SessionsListParams: Codable, Sendable {
public let limit: Int?
public let activeminutes: Int?
@@ -1026,6 +1112,7 @@ public struct SessionsPatchParams: Codable, Sendable {
public let execnode: AnyCodable?
public let model: AnyCodable?
public let spawnedby: AnyCodable?
+ public let spawndepth: AnyCodable?
public let sendpolicy: AnyCodable?
public let groupactivation: AnyCodable?
@@ -1043,6 +1130,7 @@ public struct SessionsPatchParams: Codable, Sendable {
execnode: AnyCodable?,
model: AnyCodable?,
spawnedby: AnyCodable?,
+ spawndepth: AnyCodable?,
sendpolicy: AnyCodable?,
groupactivation: AnyCodable?
) {
@@ -1059,6 +1147,7 @@ public struct SessionsPatchParams: Codable, Sendable {
self.execnode = execnode
self.model = model
self.spawnedby = spawnedby
+ self.spawndepth = spawndepth
self.sendpolicy = sendpolicy
self.groupactivation = groupactivation
}
@@ -1076,6 +1165,7 @@ public struct SessionsPatchParams: Codable, Sendable {
case execnode = "execNode"
case model
case spawnedby = "spawnedBy"
+ case spawndepth = "spawnDepth"
case sendpolicy = "sendPolicy"
case groupactivation = "groupActivation"
}
@@ -1083,14 +1173,18 @@ public struct SessionsPatchParams: Codable, Sendable {
public struct SessionsResetParams: Codable, Sendable {
public let key: String
+ public let reason: AnyCodable?
public init(
- key: String
+ key: String,
+ reason: AnyCodable?
) {
self.key = key
+ self.reason = reason
}
private enum CodingKeys: String, CodingKey {
case key
+ case reason
}
}
@@ -2060,6 +2154,7 @@ public struct SkillsUpdateParams: Codable, Sendable {
public struct CronJob: Codable, Sendable {
public let id: String
public let agentid: String?
+ public let sessionkey: String?
public let name: String
public let description: String?
public let enabled: Bool
@@ -2070,12 +2165,13 @@ public struct CronJob: Codable, Sendable {
public let sessiontarget: AnyCodable
public let wakemode: AnyCodable
public let payload: AnyCodable
- public let delivery: [String: AnyCodable]?
+ public let delivery: AnyCodable?
public let state: [String: AnyCodable]
public init(
id: String,
agentid: String?,
+ sessionkey: String?,
name: String,
description: String?,
enabled: Bool,
@@ -2086,11 +2182,12 @@ public struct CronJob: Codable, Sendable {
sessiontarget: AnyCodable,
wakemode: AnyCodable,
payload: AnyCodable,
- delivery: [String: AnyCodable]?,
+ delivery: AnyCodable?,
state: [String: AnyCodable]
) {
self.id = id
self.agentid = agentid
+ self.sessionkey = sessionkey
self.name = name
self.description = description
self.enabled = enabled
@@ -2107,6 +2204,7 @@ public struct CronJob: Codable, Sendable {
private enum CodingKeys: String, CodingKey {
case id
case agentid = "agentId"
+ case sessionkey = "sessionKey"
case name
case description
case enabled
@@ -2141,6 +2239,7 @@ public struct CronStatusParams: Codable, Sendable {
public struct CronAddParams: Codable, Sendable {
public let name: String
public let agentid: AnyCodable?
+ public let sessionkey: AnyCodable?
public let description: String?
public let enabled: Bool?
public let deleteafterrun: Bool?
@@ -2148,11 +2247,12 @@ public struct CronAddParams: Codable, Sendable {
public let sessiontarget: AnyCodable
public let wakemode: AnyCodable
public let payload: AnyCodable
- public let delivery: [String: AnyCodable]?
+ public let delivery: AnyCodable?
public init(
name: String,
agentid: AnyCodable?,
+ sessionkey: AnyCodable?,
description: String?,
enabled: Bool?,
deleteafterrun: Bool?,
@@ -2160,10 +2260,11 @@ public struct CronAddParams: Codable, Sendable {
sessiontarget: AnyCodable,
wakemode: AnyCodable,
payload: AnyCodable,
- delivery: [String: AnyCodable]?
+ delivery: AnyCodable?
) {
self.name = name
self.agentid = agentid
+ self.sessionkey = sessionkey
self.description = description
self.enabled = enabled
self.deleteafterrun = deleteafterrun
@@ -2176,6 +2277,7 @@ public struct CronAddParams: Codable, Sendable {
private enum CodingKeys: String, CodingKey {
case name
case agentid = "agentId"
+ case sessionkey = "sessionKey"
case description
case enabled
case deleteafterrun = "deleteAfterRun"
@@ -2472,6 +2574,19 @@ public struct DevicePairRejectParams: Codable, Sendable {
}
}
+public struct DevicePairRemoveParams: Codable, Sendable {
+ public let deviceid: String
+
+ public init(
+ deviceid: String
+ ) {
+ self.deviceid = deviceid
+ }
+ private enum CodingKeys: String, CodingKey {
+ case deviceid = "deviceId"
+ }
+}
+
public struct DeviceTokenRotateParams: Codable, Sendable {
public let deviceid: String
public let role: String
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatViewModel.swift b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatViewModel.swift
index 272fd81c11dfe..fc7b399353db2 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatViewModel.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatViewModel.swift
@@ -103,18 +103,22 @@ public final class OpenClawChatViewModel {
let now = Date().timeIntervalSince1970 * 1000
let cutoff = now - (24 * 60 * 60 * 1000)
let sorted = self.sessions.sorted { ($0.updatedAt ?? 0) > ($1.updatedAt ?? 0) }
- var seen = Set()
- var recent: [OpenClawChatSessionEntry] = []
- for entry in sorted {
- guard !seen.contains(entry.key) else { continue }
- seen.insert(entry.key)
- guard (entry.updatedAt ?? 0) >= cutoff else { continue }
- recent.append(entry)
- }
var result: [OpenClawChatSessionEntry] = []
var included = Set()
- for entry in recent where !included.contains(entry.key) {
+
+ // Always show the main session first, even if it hasn't been updated recently.
+ if let main = sorted.first(where: { $0.key == "main" }) {
+ result.append(main)
+ included.insert(main.key)
+ } else {
+ result.append(self.placeholderSession(key: "main"))
+ included.insert("main")
+ }
+
+ for entry in sorted {
+ guard !included.contains(entry.key) else { continue }
+ guard (entry.updatedAt ?? 0) >= cutoff else { continue }
result.append(entry)
included.insert(entry.key)
}
@@ -166,7 +170,9 @@ public final class OpenClawChatViewModel {
}
let payload = try await self.transport.requestHistory(sessionKey: self.sessionKey)
- self.messages = Self.decodeMessages(payload.messages ?? [])
+ self.messages = Self.reconcileMessageIDs(
+ previous: self.messages,
+ incoming: Self.decodeMessages(payload.messages ?? []))
self.sessionId = payload.sessionId
if let level = payload.thinkingLevel, !level.isEmpty {
self.thinkingLevel = level
@@ -187,6 +193,70 @@ public final class OpenClawChatViewModel {
return Self.dedupeMessages(decoded)
}
+ private static func messageIdentityKey(for message: OpenClawChatMessage) -> String? {
+ let role = message.role.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ guard !role.isEmpty else { return nil }
+
+ let timestamp: String = {
+ guard let value = message.timestamp, value.isFinite else { return "" }
+ return String(format: "%.3f", value)
+ }()
+
+ let contentFingerprint = message.content.map { item in
+ let type = (item.type ?? "text").trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ let text = (item.text ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let id = (item.id ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let name = (item.name ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let fileName = (item.fileName ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ return [type, text, id, name, fileName].joined(separator: "\\u{001F}")
+ }.joined(separator: "\\u{001E}")
+
+ let toolCallId = (message.toolCallId ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let toolName = (message.toolName ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ if timestamp.isEmpty, contentFingerprint.isEmpty, toolCallId.isEmpty, toolName.isEmpty {
+ return nil
+ }
+ return [role, timestamp, toolCallId, toolName, contentFingerprint].joined(separator: "|")
+ }
+
+ private static func reconcileMessageIDs(
+ previous: [OpenClawChatMessage],
+ incoming: [OpenClawChatMessage]) -> [OpenClawChatMessage]
+ {
+ guard !previous.isEmpty, !incoming.isEmpty else { return incoming }
+
+ var idsByKey: [String: [UUID]] = [:]
+ for message in previous {
+ guard let key = Self.messageIdentityKey(for: message) else { continue }
+ idsByKey[key, default: []].append(message.id)
+ }
+
+ return incoming.map { message in
+ guard let key = Self.messageIdentityKey(for: message),
+ var ids = idsByKey[key],
+ let reusedId = ids.first
+ else {
+ return message
+ }
+ ids.removeFirst()
+ if ids.isEmpty {
+ idsByKey.removeValue(forKey: key)
+ } else {
+ idsByKey[key] = ids
+ }
+ guard reusedId != message.id else { return message }
+ return OpenClawChatMessage(
+ id: reusedId,
+ role: message.role,
+ content: message.content,
+ timestamp: message.timestamp,
+ toolCallId: message.toolCallId,
+ toolName: message.toolName,
+ usage: message.usage,
+ stopReason: message.stopReason)
+ }
+ }
+
private static func dedupeMessages(_ messages: [OpenClawChatMessage]) -> [OpenClawChatMessage] {
var result: [OpenClawChatMessage] = []
result.reserveCapacity(messages.count)
@@ -371,11 +441,18 @@ public final class OpenClawChatViewModel {
}
private func handleChatEvent(_ chat: OpenClawChatEventPayload) {
- if let sessionKey = chat.sessionKey, sessionKey != self.sessionKey {
+ let isOurRun = chat.runId.flatMap { self.pendingRuns.contains($0) } ?? false
+
+ // Gateway may publish canonical session keys (for example "agent:main:main")
+ // even when this view currently uses an alias key (for example "main").
+ // Never drop events for our own pending run on key mismatch, or the UI can stay
+ // stuck at "thinking" until the user reopens and forces a history reload.
+ if let sessionKey = chat.sessionKey,
+ !Self.matchesCurrentSessionKey(incoming: sessionKey, current: self.sessionKey),
+ !isOurRun
+ {
return
}
-
- let isOurRun = chat.runId.flatMap { self.pendingRuns.contains($0) } ?? false
if !isOurRun {
// Keep multiple clients in sync: if another client finishes a run for our session, refresh history.
switch chat.state {
@@ -407,6 +484,21 @@ public final class OpenClawChatViewModel {
}
}
+ private static func matchesCurrentSessionKey(incoming: String, current: String) -> Bool {
+ let incomingNormalized = incoming.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ let currentNormalized = current.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ if incomingNormalized == currentNormalized {
+ return true
+ }
+ // Common alias pair in operator clients: UI uses "main" while gateway emits canonical.
+ if (incomingNormalized == "agent:main:main" && currentNormalized == "main") ||
+ (incomingNormalized == "main" && currentNormalized == "agent:main:main")
+ {
+ return true
+ }
+ return false
+ }
+
private func handleAgentEvent(_ evt: OpenClawAgentEventPayload) {
if let sessionId, evt.runId != sessionId {
return
@@ -440,7 +532,9 @@ public final class OpenClawChatViewModel {
private func refreshHistoryAfterRun() async {
do {
let payload = try await self.transport.requestHistory(sessionKey: self.sessionKey)
- self.messages = Self.decodeMessages(payload.messages ?? [])
+ self.messages = Self.reconcileMessageIDs(
+ previous: self.messages,
+ incoming: Self.decodeMessages(payload.messages ?? []))
self.sessionId = payload.sessionId
if let level = payload.thinkingLevel, !level.isEmpty {
self.thinkingLevel = level
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/AnyCodable.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/AnyCodable.swift
index ef522447f43c8..02b53e3c392f1 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawKit/AnyCodable.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/AnyCodable.swift
@@ -1,93 +1,4 @@
-import Foundation
+import OpenClawProtocol
-/// Lightweight `Codable` wrapper that round-trips heterogeneous JSON payloads.
-///
-/// Marked `@unchecked Sendable` because it can hold reference types.
-public struct AnyCodable: Codable, @unchecked Sendable, Hashable {
- public let value: Any
+public typealias AnyCodable = OpenClawProtocol.AnyCodable
- public init(_ value: Any) { self.value = value }
-
- public init(from decoder: Decoder) throws {
- let container = try decoder.singleValueContainer()
- if let intVal = try? container.decode(Int.self) { self.value = intVal; return }
- if let doubleVal = try? container.decode(Double.self) { self.value = doubleVal; return }
- if let boolVal = try? container.decode(Bool.self) { self.value = boolVal; return }
- if let stringVal = try? container.decode(String.self) { self.value = stringVal; return }
- if container.decodeNil() { self.value = NSNull(); return }
- if let dict = try? container.decode([String: AnyCodable].self) { self.value = dict; return }
- if let array = try? container.decode([AnyCodable].self) { self.value = array; return }
- throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported type")
- }
-
- public func encode(to encoder: Encoder) throws {
- var container = encoder.singleValueContainer()
- switch self.value {
- case let intVal as Int: try container.encode(intVal)
- case let doubleVal as Double: try container.encode(doubleVal)
- case let boolVal as Bool: try container.encode(boolVal)
- case let stringVal as String: try container.encode(stringVal)
- case is NSNull: try container.encodeNil()
- case let dict as [String: AnyCodable]: try container.encode(dict)
- case let array as [AnyCodable]: try container.encode(array)
- case let dict as [String: Any]:
- try container.encode(dict.mapValues { AnyCodable($0) })
- case let array as [Any]:
- try container.encode(array.map { AnyCodable($0) })
- case let dict as NSDictionary:
- var converted: [String: AnyCodable] = [:]
- for (k, v) in dict {
- guard let key = k as? String else { continue }
- converted[key] = AnyCodable(v)
- }
- try container.encode(converted)
- case let array as NSArray:
- try container.encode(array.map { AnyCodable($0) })
- default:
- let context = EncodingError.Context(codingPath: encoder.codingPath, debugDescription: "Unsupported type")
- throw EncodingError.invalidValue(self.value, context)
- }
- }
-
- public static func == (lhs: AnyCodable, rhs: AnyCodable) -> Bool {
- switch (lhs.value, rhs.value) {
- case let (l as Int, r as Int): l == r
- case let (l as Double, r as Double): l == r
- case let (l as Bool, r as Bool): l == r
- case let (l as String, r as String): l == r
- case (_ as NSNull, _ as NSNull): true
- case let (l as [String: AnyCodable], r as [String: AnyCodable]): l == r
- case let (l as [AnyCodable], r as [AnyCodable]): l == r
- default:
- false
- }
- }
-
- public func hash(into hasher: inout Hasher) {
- switch self.value {
- case let v as Int:
- hasher.combine(0); hasher.combine(v)
- case let v as Double:
- hasher.combine(1); hasher.combine(v)
- case let v as Bool:
- hasher.combine(2); hasher.combine(v)
- case let v as String:
- hasher.combine(3); hasher.combine(v)
- case _ as NSNull:
- hasher.combine(4)
- case let v as [String: AnyCodable]:
- hasher.combine(5)
- for (k, val) in v.sorted(by: { $0.key < $1.key }) {
- hasher.combine(k)
- hasher.combine(val)
- }
- case let v as [AnyCodable]:
- hasher.combine(6)
- for item in v {
- hasher.combine(item)
- }
- default:
- hasher.combine(999)
- }
- }
-}
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/Capabilities.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/Capabilities.swift
index d5c5e3c439cdf..49f9efe996bf8 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawKit/Capabilities.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/Capabilities.swift
@@ -7,6 +7,7 @@ public enum OpenClawCapability: String, Codable, Sendable {
case voiceWake
case location
case device
+ case watch
case photos
case contacts
case calendar
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/DeepLinks.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/DeepLinks.swift
index 10dd7ea05368e..30606ca26712c 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawKit/DeepLinks.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/DeepLinks.swift
@@ -2,6 +2,56 @@ import Foundation
public enum DeepLinkRoute: Sendable, Equatable {
case agent(AgentDeepLink)
+ case gateway(GatewayConnectDeepLink)
+}
+
+public struct GatewayConnectDeepLink: Codable, Sendable, Equatable {
+ public let host: String
+ public let port: Int
+ public let tls: Bool
+ public let token: String?
+ public let password: String?
+
+ public init(host: String, port: Int, tls: Bool, token: String?, password: String?) {
+ self.host = host
+ self.port = port
+ self.tls = tls
+ self.token = token
+ self.password = password
+ }
+
+ public var websocketURL: URL? {
+ let scheme = self.tls ? "wss" : "ws"
+ return URL(string: "\(scheme)://\(self.host):\(self.port)")
+ }
+
+ /// Parse a device-pair setup code (base64url-encoded JSON: `{url, token?, password?}`).
+ public static func fromSetupCode(_ code: String) -> GatewayConnectDeepLink? {
+ guard let data = Self.decodeBase64Url(code) else { return nil }
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
+ guard let urlString = json["url"] as? String,
+ let parsed = URLComponents(string: urlString),
+ let hostname = parsed.host, !hostname.isEmpty
+ else { return nil }
+
+ let scheme = (parsed.scheme ?? "ws").lowercased()
+ let tls = scheme == "wss"
+ let port = parsed.port ?? (tls ? 443 : 18789)
+ let token = json["token"] as? String
+ let password = json["password"] as? String
+ return GatewayConnectDeepLink(host: hostname, port: port, tls: tls, token: token, password: password)
+ }
+
+ private static func decodeBase64Url(_ input: String) -> Data? {
+ var base64 = input
+ .replacingOccurrences(of: "-", with: "+")
+ .replacingOccurrences(of: "_", with: "/")
+ let remainder = base64.count % 4
+ if remainder > 0 {
+ base64.append(contentsOf: String(repeating: "=", count: 4 - remainder))
+ }
+ return Data(base64Encoded: base64)
+ }
}
public struct AgentDeepLink: Codable, Sendable, Equatable {
@@ -69,6 +119,23 @@ public enum DeepLinkParser {
channel: query["channel"],
timeoutSeconds: timeoutSeconds,
key: query["key"]))
+
+ case "gateway":
+ guard let hostParam = query["host"],
+ !hostParam.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else {
+ return nil
+ }
+ let port = query["port"].flatMap { Int($0) } ?? 18789
+ let tls = (query["tls"] as NSString?)?.boolValue ?? false
+ return .gateway(
+ .init(
+ host: hostParam,
+ port: port,
+ tls: tls,
+ token: query["token"],
+ password: query["password"]))
+
default:
return nil
}
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayChannel.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayChannel.swift
index a255fc7a81daa..9682a31aa4650 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayChannel.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayChannel.swift
@@ -133,10 +133,16 @@ public actor GatewayChannelActor {
private var lastAuthSource: GatewayAuthSource = .none
private let decoder = JSONDecoder()
private let encoder = JSONEncoder()
- private let connectTimeoutSeconds: Double = 6
- private let connectChallengeTimeoutSeconds: Double = 3.0
+ // Remote gateways (tailscale/wan) can take a bit longer to deliver the connect.challenge event,
+ // and we must include the nonce once the gateway requires v2 signing.
+ private let connectTimeoutSeconds: Double = 12
+ private let connectChallengeTimeoutSeconds: Double = 6.0
+ // Some networks will silently drop idle TCP/TLS flows around ~30s. The gateway tick is server->client,
+ // but NATs/proxies often require outbound traffic to keep the connection alive.
+ private let keepaliveIntervalSeconds: Double = 15.0
private var watchdogTask: Task?
private var tickTask: Task?
+ private var keepaliveTask: Task?
private let defaultRequestTimeoutMs: Double = 15000
private let pushHandler: (@Sendable (GatewayPush) async -> Void)?
private let connectOptions: GatewayConnectOptions?
@@ -175,6 +181,9 @@ public actor GatewayChannelActor {
self.tickTask?.cancel()
self.tickTask = nil
+ self.keepaliveTask?.cancel()
+ self.keepaliveTask = nil
+
self.task?.cancel(with: .goingAway, reason: nil)
self.task = nil
@@ -257,6 +266,7 @@ public actor GatewayChannelActor {
self.connected = true
self.backoffMs = 500
self.lastSeq = nil
+ self.startKeepalive()
let waiters = self.connectWaiters
self.connectWaiters.removeAll()
@@ -265,6 +275,29 @@ public actor GatewayChannelActor {
}
}
+ private func startKeepalive() {
+ self.keepaliveTask?.cancel()
+ self.keepaliveTask = Task { [weak self] in
+ guard let self else { return }
+ await self.keepaliveLoop()
+ }
+ }
+
+ private func keepaliveLoop() async {
+ while self.shouldReconnect {
+ try? await Task.sleep(nanoseconds: UInt64(self.keepaliveIntervalSeconds * 1_000_000_000))
+ guard self.shouldReconnect else { return }
+ guard self.connected else { continue }
+ // Best-effort outbound message to keep intermediate NAT/proxy state alive.
+ // We intentionally ignore the response.
+ do {
+ try await self.send(method: "health", params: nil)
+ } catch {
+ // Avoid spamming logs; the reconnect paths will surface meaningful errors.
+ }
+ }
+ }
+
private func sendConnect() async throws {
let platform = InstanceIdentity.platformString
let primaryLocale = Locale.preferredLanguages.first ?? Locale.current.identifier
@@ -458,6 +491,8 @@ public actor GatewayChannelActor {
let wrapped = self.wrap(err, context: "gateway receive")
self.logger.error("gateway ws receive failed \(wrapped.localizedDescription, privacy: .public)")
self.connected = false
+ self.keepaliveTask?.cancel()
+ self.keepaliveTask = nil
await self.disconnectHandler?("receive failed: \(wrapped.localizedDescription)")
await self.failPending(wrapped)
await self.scheduleReconnect()
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayDiscoveryStatusText.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayDiscoveryStatusText.swift
new file mode 100644
index 0000000000000..e15baf17fdb1a
--- /dev/null
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayDiscoveryStatusText.swift
@@ -0,0 +1,39 @@
+import Foundation
+import Network
+
+public enum GatewayDiscoveryStatusText {
+ public static func make(states: [NWBrowser.State], hasBrowsers: Bool) -> String {
+ if states.isEmpty {
+ return hasBrowsers ? "Setup" : "Idle"
+ }
+
+ if let failed = states.first(where: { state in
+ if case .failed = state { return true }
+ return false
+ }) {
+ if case let .failed(err) = failed {
+ return "Failed: \(err)"
+ }
+ }
+
+ if let waiting = states.first(where: { state in
+ if case .waiting = state { return true }
+ return false
+ }) {
+ if case let .waiting(err) = waiting {
+ return "Waiting: \(err)"
+ }
+ }
+
+ if states.contains(where: { if case .ready = $0 { true } else { false } }) {
+ return "Searching…"
+ }
+
+ if states.contains(where: { if case .setup = $0 { true } else { false } }) {
+ return "Setup"
+ }
+
+ return "Searching…"
+ }
+}
+
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayNodeSession.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayNodeSession.swift
index 6311b4632cba7..d0303f7e9977b 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayNodeSession.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayNodeSession.swift
@@ -85,7 +85,13 @@ public actor GatewayNodeSession {
latch.resume(result)
}
timeoutTask = Task.detached {
- try? await Task.sleep(nanoseconds: UInt64(timeout) * 1_000_000)
+ do {
+ try await Task.sleep(nanoseconds: UInt64(timeout) * 1_000_000)
+ } catch {
+ // Expected when invoke finishes first and cancels the timeout task.
+ return
+ }
+ guard !Task.isCancelled else { return }
timeoutLogger.info("node invoke timeout fired id=\(request.id, privacy: .public)")
latch.resume(BridgeInvokeResponse(
id: request.id,
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayPayloadDecoding.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayPayloadDecoding.swift
index 8672ab09f681f..139aa7d2942a8 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayPayloadDecoding.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayPayloadDecoding.swift
@@ -2,14 +2,6 @@ import OpenClawProtocol
import Foundation
public enum GatewayPayloadDecoding {
- public static func decode(
- _ payload: OpenClawProtocol.AnyCodable,
- as _: T.Type = T.self) throws -> T
- {
- let data = try JSONEncoder().encode(payload)
- return try JSONDecoder().decode(T.self, from: data)
- }
-
public static func decode(
_ payload: AnyCodable,
as _: T.Type = T.self) throws -> T
@@ -18,14 +10,6 @@ public enum GatewayPayloadDecoding {
return try JSONDecoder().decode(T.self, from: data)
}
- public static func decodeIfPresent(
- _ payload: OpenClawProtocol.AnyCodable?,
- as _: T.Type = T.self) throws -> T?
- {
- guard let payload else { return nil }
- return try self.decode(payload, as: T.self)
- }
-
public static func decodeIfPresent(
_ payload: AnyCodable?,
as _: T.Type = T.self) throws -> T?
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/NetworkInterfaces.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/NetworkInterfaces.swift
new file mode 100644
index 0000000000000..3679ef5423444
--- /dev/null
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/NetworkInterfaces.swift
@@ -0,0 +1,43 @@
+import Darwin
+import Foundation
+
+public enum NetworkInterfaces {
+ public static func primaryIPv4Address() -> String? {
+ var addrList: UnsafeMutablePointer?
+ guard getifaddrs(&addrList) == 0, let first = addrList else { return nil }
+ defer { freeifaddrs(addrList) }
+
+ var fallback: String?
+ var en0: String?
+
+ for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) {
+ let flags = Int32(ptr.pointee.ifa_flags)
+ let isUp = (flags & IFF_UP) != 0
+ let isLoopback = (flags & IFF_LOOPBACK) != 0
+ let name = String(cString: ptr.pointee.ifa_name)
+ let family = ptr.pointee.ifa_addr.pointee.sa_family
+ if !isUp || isLoopback || family != UInt8(AF_INET) { continue }
+
+ var addr = ptr.pointee.ifa_addr.pointee
+ var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
+ let result = getnameinfo(
+ &addr,
+ socklen_t(ptr.pointee.ifa_addr.pointee.sa_len),
+ &buffer,
+ socklen_t(buffer.count),
+ nil,
+ 0,
+ NI_NUMERICHOST)
+ guard result == 0 else { continue }
+ let len = buffer.prefix { $0 != 0 }
+ let bytes = len.map { UInt8(bitPattern: $0) }
+ guard let ip = String(bytes: bytes, encoding: .utf8) else { continue }
+
+ if name == "en0" { en0 = ip; break }
+ if fallback == nil { fallback = ip }
+ }
+
+ return en0 ?? fallback
+ }
+}
+
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/OpenClawKitResources.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/OpenClawKitResources.swift
index b19792ad7b813..5af33d1d35c28 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawKit/OpenClawKitResources.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/OpenClawKitResources.swift
@@ -52,18 +52,26 @@ public enum OpenClawKitResources {
for candidate in candidates {
guard let baseURL = candidate else { continue }
- // Direct path
- let directURL = baseURL.appendingPathComponent("\(bundleName).bundle")
- if let bundle = Bundle(url: directURL) {
- return bundle
+ // SwiftPM often places the resource bundle next to (or near) the test runner bundle,
+ // not inside it. Walk up a few levels and check common container paths.
+ var roots: [URL] = []
+ roots.append(baseURL)
+ roots.append(baseURL.appendingPathComponent("Resources"))
+ roots.append(baseURL.appendingPathComponent("Contents/Resources"))
+
+ var current = baseURL
+ for _ in 0 ..< 5 {
+ current = current.deletingLastPathComponent()
+ roots.append(current)
+ roots.append(current.appendingPathComponent("Resources"))
+ roots.append(current.appendingPathComponent("Contents/Resources"))
}
- // Inside Resources/
- let resourcesURL = baseURL
- .appendingPathComponent("Resources")
- .appendingPathComponent("\(bundleName).bundle")
- if let bundle = Bundle(url: resourcesURL) {
- return bundle
+ for root in roots {
+ let bundleURL = root.appendingPathComponent("\(bundleName).bundle")
+ if let bundle = Bundle(url: bundleURL) {
+ return bundle
+ }
}
}
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/PhotoCapture.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/PhotoCapture.swift
new file mode 100644
index 0000000000000..b5f00d34751e1
--- /dev/null
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/PhotoCapture.swift
@@ -0,0 +1,19 @@
+import Foundation
+
+public enum PhotoCapture {
+ public static func transcodeJPEGForGateway(
+ rawData: Data,
+ maxWidthPx: Int,
+ quality: Double,
+ maxPayloadBytes: Int = 5 * 1024 * 1024
+ ) throws -> (data: Data, widthPx: Int, heightPx: Int) {
+ // Base64 inflates payloads by ~4/3; cap encoded bytes so the payload stays under maxPayloadBytes (API limit).
+ let maxEncodedBytes = (maxPayloadBytes / 4) * 3
+ return try JPEGTranscoder.transcodeToJPEG(
+ imageData: rawData,
+ maxWidthPx: maxWidthPx,
+ quality: quality,
+ maxBytes: maxEncodedBytes)
+ }
+}
+
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/ShareGatewayRelaySettings.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/ShareGatewayRelaySettings.swift
new file mode 100644
index 0000000000000..7b4c3864b37e8
--- /dev/null
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/ShareGatewayRelaySettings.swift
@@ -0,0 +1,62 @@
+import Foundation
+
+public struct ShareGatewayRelayConfig: Codable, Sendable, Equatable {
+ public let gatewayURLString: String
+ public let token: String?
+ public let password: String?
+ public let sessionKey: String
+ public let deliveryChannel: String?
+ public let deliveryTo: String?
+
+ public init(
+ gatewayURLString: String,
+ token: String?,
+ password: String?,
+ sessionKey: String,
+ deliveryChannel: String? = nil,
+ deliveryTo: String? = nil)
+ {
+ self.gatewayURLString = gatewayURLString
+ self.token = token
+ self.password = password
+ self.sessionKey = sessionKey
+ self.deliveryChannel = deliveryChannel
+ self.deliveryTo = deliveryTo
+ }
+}
+
+public enum ShareGatewayRelaySettings {
+ private static let suiteName = "group.ai.openclaw.shared"
+ private static let relayConfigKey = "share.gatewayRelay.config.v1"
+ private static let lastEventKey = "share.gatewayRelay.event.v1"
+
+ private static var defaults: UserDefaults {
+ UserDefaults(suiteName: self.suiteName) ?? .standard
+ }
+
+ public static func loadConfig() -> ShareGatewayRelayConfig? {
+ guard let data = self.defaults.data(forKey: self.relayConfigKey) else { return nil }
+ return try? JSONDecoder().decode(ShareGatewayRelayConfig.self, from: data)
+ }
+
+ public static func saveConfig(_ config: ShareGatewayRelayConfig) {
+ guard let data = try? JSONEncoder().encode(config) else { return }
+ self.defaults.set(data, forKey: self.relayConfigKey)
+ }
+
+ public static func clearConfig() {
+ self.defaults.removeObject(forKey: self.relayConfigKey)
+ }
+
+ public static func saveLastEvent(_ message: String) {
+ let timestamp = ISO8601DateFormatter().string(from: Date())
+ let payload = "[\(timestamp)] \(message)"
+ self.defaults.set(payload, forKey: self.lastEventKey)
+ }
+
+ public static func loadLastEvent() -> String? {
+ let value = self.defaults.string(forKey: self.lastEventKey)?
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ return value.isEmpty ? nil : value
+ }
+}
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/ShareToAgentDeepLink.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/ShareToAgentDeepLink.swift
new file mode 100644
index 0000000000000..08f0623433460
--- /dev/null
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/ShareToAgentDeepLink.swift
@@ -0,0 +1,62 @@
+import Foundation
+
+public struct SharedContentPayload: Sendable, Equatable {
+ public let title: String?
+ public let url: URL?
+ public let text: String?
+
+ public init(title: String?, url: URL?, text: String?) {
+ self.title = title
+ self.url = url
+ self.text = text
+ }
+}
+
+public enum ShareToAgentDeepLink {
+ public static func buildURL(from payload: SharedContentPayload, instruction: String? = nil) -> URL? {
+ let message = self.buildMessage(from: payload, instruction: instruction)
+ guard !message.isEmpty else { return nil }
+
+ var components = URLComponents()
+ components.scheme = "openclaw"
+ components.host = "agent"
+ components.queryItems = [
+ URLQueryItem(name: "message", value: message),
+ URLQueryItem(name: "thinking", value: "low"),
+ ]
+ return components.url
+ }
+
+ public static func buildMessage(from payload: SharedContentPayload, instruction: String? = nil) -> String {
+ let title = self.clean(payload.title)
+ let text = self.clean(payload.text)
+ let urlText = payload.url?.absoluteString.trimmingCharacters(in: .whitespacesAndNewlines)
+ let resolvedInstruction = self.clean(instruction) ?? ShareToAgentSettings.loadDefaultInstruction()
+
+ var lines: [String] = ["Shared from iOS."]
+ if let title, !title.isEmpty {
+ lines.append("Title: \(title)")
+ }
+ if let urlText, !urlText.isEmpty {
+ lines.append("URL: \(urlText)")
+ }
+ if let text, !text.isEmpty {
+ lines.append("Text:\n\(text)")
+ }
+ lines.append(resolvedInstruction)
+
+ let message = lines.joined(separator: "\n\n")
+ return self.limit(message, maxCharacters: 2400)
+ }
+
+ private static func clean(_ value: String?) -> String? {
+ guard let value else { return nil }
+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty ? nil : trimmed
+ }
+
+ private static func limit(_ value: String, maxCharacters: Int) -> String {
+ guard value.count > maxCharacters else { return value }
+ return String(value.prefix(maxCharacters))
+ }
+}
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/ShareToAgentSettings.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/ShareToAgentSettings.swift
new file mode 100644
index 0000000000000..9034dcfe1b667
--- /dev/null
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/ShareToAgentSettings.swift
@@ -0,0 +1,29 @@
+import Foundation
+
+public enum ShareToAgentSettings {
+ private static let suiteName = "group.ai.openclaw.shared"
+ private static let defaultInstructionKey = "share.defaultInstruction"
+ private static let fallbackInstruction = "Please help me with this."
+
+ private static var defaults: UserDefaults {
+ UserDefaults(suiteName: suiteName) ?? .standard
+ }
+
+ public static func loadDefaultInstruction() -> String {
+ let raw = self.defaults.string(forKey: self.defaultInstructionKey)?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ if let raw, !raw.isEmpty {
+ return raw
+ }
+ return self.fallbackInstruction
+ }
+
+ public static func saveDefaultInstruction(_ value: String?) {
+ let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ if trimmed.isEmpty {
+ self.defaults.removeObject(forKey: self.defaultInstructionKey)
+ return
+ }
+ self.defaults.set(trimmed, forKey: self.defaultInstructionKey)
+ }
+}
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/TalkPromptBuilder.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/TalkPromptBuilder.swift
index c63f40e9d3a7d..2a2e39d68cf69 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawKit/TalkPromptBuilder.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/TalkPromptBuilder.swift
@@ -1,10 +1,19 @@
public enum TalkPromptBuilder: Sendable {
- public static func build(transcript: String, interruptedAtSeconds: Double?) -> String {
+ public static func build(
+ transcript: String,
+ interruptedAtSeconds: Double?,
+ includeVoiceDirectiveHint: Bool = true
+ ) -> String {
var lines: [String] = [
"Talk Mode active. Reply in a concise, spoken tone.",
- "You may optionally prefix the response with JSON (first line) to set ElevenLabs voice (id or alias), e.g. {\"voice\":\"\",\"once\":true}.",
]
+ if includeVoiceDirectiveHint {
+ lines.append(
+ "You may optionally prefix the response with JSON (first line) to set ElevenLabs voice (id or alias), e.g. {\"voice\":\"\",\"once\":true}."
+ )
+ }
+
if let interruptedAtSeconds {
let formatted = String(format: "%.1f", interruptedAtSeconds)
lines.append("Assistant speech interrupted at \(formatted)s.")
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/WatchCommands.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/WatchCommands.swift
new file mode 100644
index 0000000000000..814efe68a886a
--- /dev/null
+++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/WatchCommands.swift
@@ -0,0 +1,52 @@
+import Foundation
+
+public enum OpenClawWatchCommand: String, Codable, Sendable {
+ case status = "watch.status"
+ case notify = "watch.notify"
+}
+
+public struct OpenClawWatchStatusPayload: Codable, Sendable, Equatable {
+ public var supported: Bool
+ public var paired: Bool
+ public var appInstalled: Bool
+ public var reachable: Bool
+ public var activationState: String
+
+ public init(
+ supported: Bool,
+ paired: Bool,
+ appInstalled: Bool,
+ reachable: Bool,
+ activationState: String)
+ {
+ self.supported = supported
+ self.paired = paired
+ self.appInstalled = appInstalled
+ self.reachable = reachable
+ self.activationState = activationState
+ }
+}
+
+public struct OpenClawWatchNotifyParams: Codable, Sendable, Equatable {
+ public var title: String
+ public var body: String
+ public var priority: OpenClawNotificationPriority?
+
+ public init(title: String, body: String, priority: OpenClawNotificationPriority? = nil) {
+ self.title = title
+ self.body = body
+ self.priority = priority
+ }
+}
+
+public struct OpenClawWatchNotifyPayload: Codable, Sendable, Equatable {
+ public var deliveredImmediately: Bool
+ public var queuedForDelivery: Bool
+ public var transport: String
+
+ public init(deliveredImmediately: Bool, queuedForDelivery: Bool, transport: String) {
+ self.deliveredImmediately = deliveredImmediately
+ self.queuedForDelivery = queuedForDelivery
+ self.transport = transport
+ }
+}
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawProtocol/AnyCodable.swift b/apps/shared/OpenClawKit/Sources/OpenClawProtocol/AnyCodable.swift
index ad0c338729677..4315bb073efca 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawProtocol/AnyCodable.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawProtocol/AnyCodable.swift
@@ -1,33 +1,34 @@
import Foundation
/// Lightweight `Codable` wrapper that round-trips heterogeneous JSON payloads.
+///
/// Marked `@unchecked Sendable` because it can hold reference types.
-public struct AnyCodable: Codable, @unchecked Sendable {
+public struct AnyCodable: Codable, @unchecked Sendable, Hashable {
public let value: Any
- public init(_ value: Any) { self.value = value }
+ public init(_ value: Any) { self.value = Self.normalize(value) }
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
+ if let boolVal = try? container.decode(Bool.self) { self.value = boolVal; return }
if let intVal = try? container.decode(Int.self) { self.value = intVal; return }
if let doubleVal = try? container.decode(Double.self) { self.value = doubleVal; return }
- if let boolVal = try? container.decode(Bool.self) { self.value = boolVal; return }
if let stringVal = try? container.decode(String.self) { self.value = stringVal; return }
if container.decodeNil() { self.value = NSNull(); return }
if let dict = try? container.decode([String: AnyCodable].self) { self.value = dict; return }
if let array = try? container.decode([AnyCodable].self) { self.value = array; return }
- throw DecodingError.dataCorruptedError(
- in: container,
- debugDescription: "Unsupported type")
+ throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported type")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self.value {
+ case let boolVal as Bool: try container.encode(boolVal)
case let intVal as Int: try container.encode(intVal)
case let doubleVal as Double: try container.encode(doubleVal)
- case let boolVal as Bool: try container.encode(boolVal)
case let stringVal as String: try container.encode(stringVal)
+ case let number as NSNumber where CFGetTypeID(number) == CFBooleanGetTypeID():
+ try container.encode(number.boolValue)
case is NSNull: try container.encodeNil()
case let dict as [String: AnyCodable]: try container.encode(dict)
case let array as [AnyCodable]: try container.encode(array)
@@ -51,4 +52,53 @@ public struct AnyCodable: Codable, @unchecked Sendable {
throw EncodingError.invalidValue(self.value, context)
}
}
+
+ private static func normalize(_ value: Any) -> Any {
+ if let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() {
+ return number.boolValue
+ }
+ return value
+ }
+
+ public static func == (lhs: AnyCodable, rhs: AnyCodable) -> Bool {
+ switch (lhs.value, rhs.value) {
+ case let (l as Bool, r as Bool): l == r
+ case let (l as Int, r as Int): l == r
+ case let (l as Double, r as Double): l == r
+ case let (l as String, r as String): l == r
+ case (_ as NSNull, _ as NSNull): true
+ case let (l as [String: AnyCodable], r as [String: AnyCodable]): l == r
+ case let (l as [AnyCodable], r as [AnyCodable]): l == r
+ default:
+ false
+ }
+ }
+
+ public func hash(into hasher: inout Hasher) {
+ switch self.value {
+ case let v as Bool:
+ hasher.combine(2); hasher.combine(v)
+ case let v as Int:
+ hasher.combine(0); hasher.combine(v)
+ case let v as Double:
+ hasher.combine(1); hasher.combine(v)
+ case let v as String:
+ hasher.combine(3); hasher.combine(v)
+ case _ as NSNull:
+ hasher.combine(4)
+ case let v as [String: AnyCodable]:
+ hasher.combine(5)
+ for (k, val) in v.sorted(by: { $0.key < $1.key }) {
+ hasher.combine(k)
+ hasher.combine(val)
+ }
+ case let v as [AnyCodable]:
+ hasher.combine(6)
+ for item in v {
+ hasher.combine(item)
+ }
+ default:
+ hasher.combine(999)
+ }
+ }
}
diff --git a/apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift b/apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift
index a134b4fd5b4d2..661d5dc11fd0c 100644
--- a/apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift
+++ b/apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift
@@ -296,6 +296,7 @@ public struct Snapshot: Codable, Sendable {
public let statedir: String?
public let sessiondefaults: [String: AnyCodable]?
public let authmode: AnyCodable?
+ public let updateavailable: [String: AnyCodable]?
public init(
presence: [PresenceEntry],
@@ -305,7 +306,8 @@ public struct Snapshot: Codable, Sendable {
configpath: String?,
statedir: String?,
sessiondefaults: [String: AnyCodable]?,
- authmode: AnyCodable?
+ authmode: AnyCodable?,
+ updateavailable: [String: AnyCodable]?
) {
self.presence = presence
self.health = health
@@ -315,6 +317,7 @@ public struct Snapshot: Codable, Sendable {
self.statedir = statedir
self.sessiondefaults = sessiondefaults
self.authmode = authmode
+ self.updateavailable = updateavailable
}
private enum CodingKeys: String, CodingKey {
case presence
@@ -325,6 +328,7 @@ public struct Snapshot: Codable, Sendable {
case statedir = "stateDir"
case sessiondefaults = "sessionDefaults"
case authmode = "authMode"
+ case updateavailable = "updateAvailable"
}
}
@@ -394,6 +398,7 @@ public struct SendParams: Codable, Sendable {
public let gifplayback: Bool?
public let channel: String?
public let accountid: String?
+ public let threadid: String?
public let sessionkey: String?
public let idempotencykey: String
@@ -405,6 +410,7 @@ public struct SendParams: Codable, Sendable {
gifplayback: Bool?,
channel: String?,
accountid: String?,
+ threadid: String?,
sessionkey: String?,
idempotencykey: String
) {
@@ -415,6 +421,7 @@ public struct SendParams: Codable, Sendable {
self.gifplayback = gifplayback
self.channel = channel
self.accountid = accountid
+ self.threadid = threadid
self.sessionkey = sessionkey
self.idempotencykey = idempotencykey
}
@@ -426,6 +433,7 @@ public struct SendParams: Codable, Sendable {
case gifplayback = "gifPlayback"
case channel
case accountid = "accountId"
+ case threadid = "threadId"
case sessionkey = "sessionKey"
case idempotencykey = "idempotencyKey"
}
@@ -436,7 +444,11 @@ public struct PollParams: Codable, Sendable {
public let question: String
public let options: [String]
public let maxselections: Int?
+ public let durationseconds: Int?
public let durationhours: Int?
+ public let silent: Bool?
+ public let isanonymous: Bool?
+ public let threadid: String?
public let channel: String?
public let accountid: String?
public let idempotencykey: String
@@ -446,7 +458,11 @@ public struct PollParams: Codable, Sendable {
question: String,
options: [String],
maxselections: Int?,
+ durationseconds: Int?,
durationhours: Int?,
+ silent: Bool?,
+ isanonymous: Bool?,
+ threadid: String?,
channel: String?,
accountid: String?,
idempotencykey: String
@@ -455,7 +471,11 @@ public struct PollParams: Codable, Sendable {
self.question = question
self.options = options
self.maxselections = maxselections
+ self.durationseconds = durationseconds
self.durationhours = durationhours
+ self.silent = silent
+ self.isanonymous = isanonymous
+ self.threadid = threadid
self.channel = channel
self.accountid = accountid
self.idempotencykey = idempotencykey
@@ -465,7 +485,11 @@ public struct PollParams: Codable, Sendable {
case question
case options
case maxselections = "maxSelections"
+ case durationseconds = "durationSeconds"
case durationhours = "durationHours"
+ case silent
+ case isanonymous = "isAnonymous"
+ case threadid = "threadId"
case channel
case accountid = "accountId"
case idempotencykey = "idempotencyKey"
@@ -905,6 +929,68 @@ public struct NodeInvokeRequestEvent: Codable, Sendable {
}
}
+public struct PushTestParams: Codable, Sendable {
+ public let nodeid: String
+ public let title: String?
+ public let body: String?
+ public let environment: String?
+
+ public init(
+ nodeid: String,
+ title: String?,
+ body: String?,
+ environment: String?
+ ) {
+ self.nodeid = nodeid
+ self.title = title
+ self.body = body
+ self.environment = environment
+ }
+ private enum CodingKeys: String, CodingKey {
+ case nodeid = "nodeId"
+ case title
+ case body
+ case environment
+ }
+}
+
+public struct PushTestResult: Codable, Sendable {
+ public let ok: Bool
+ public let status: Int
+ public let apnsid: String?
+ public let reason: String?
+ public let tokensuffix: String
+ public let topic: String
+ public let environment: String
+
+ public init(
+ ok: Bool,
+ status: Int,
+ apnsid: String?,
+ reason: String?,
+ tokensuffix: String,
+ topic: String,
+ environment: String
+ ) {
+ self.ok = ok
+ self.status = status
+ self.apnsid = apnsid
+ self.reason = reason
+ self.tokensuffix = tokensuffix
+ self.topic = topic
+ self.environment = environment
+ }
+ private enum CodingKeys: String, CodingKey {
+ case ok
+ case status
+ case apnsid = "apnsId"
+ case reason
+ case tokensuffix = "tokenSuffix"
+ case topic
+ case environment
+ }
+}
+
public struct SessionsListParams: Codable, Sendable {
public let limit: Int?
public let activeminutes: Int?
@@ -1026,6 +1112,7 @@ public struct SessionsPatchParams: Codable, Sendable {
public let execnode: AnyCodable?
public let model: AnyCodable?
public let spawnedby: AnyCodable?
+ public let spawndepth: AnyCodable?
public let sendpolicy: AnyCodable?
public let groupactivation: AnyCodable?
@@ -1043,6 +1130,7 @@ public struct SessionsPatchParams: Codable, Sendable {
execnode: AnyCodable?,
model: AnyCodable?,
spawnedby: AnyCodable?,
+ spawndepth: AnyCodable?,
sendpolicy: AnyCodable?,
groupactivation: AnyCodable?
) {
@@ -1059,6 +1147,7 @@ public struct SessionsPatchParams: Codable, Sendable {
self.execnode = execnode
self.model = model
self.spawnedby = spawnedby
+ self.spawndepth = spawndepth
self.sendpolicy = sendpolicy
self.groupactivation = groupactivation
}
@@ -1076,6 +1165,7 @@ public struct SessionsPatchParams: Codable, Sendable {
case execnode = "execNode"
case model
case spawnedby = "spawnedBy"
+ case spawndepth = "spawnDepth"
case sendpolicy = "sendPolicy"
case groupactivation = "groupActivation"
}
@@ -1083,14 +1173,18 @@ public struct SessionsPatchParams: Codable, Sendable {
public struct SessionsResetParams: Codable, Sendable {
public let key: String
+ public let reason: AnyCodable?
public init(
- key: String
+ key: String,
+ reason: AnyCodable?
) {
self.key = key
+ self.reason = reason
}
private enum CodingKeys: String, CodingKey {
case key
+ case reason
}
}
@@ -2060,6 +2154,7 @@ public struct SkillsUpdateParams: Codable, Sendable {
public struct CronJob: Codable, Sendable {
public let id: String
public let agentid: String?
+ public let sessionkey: String?
public let name: String
public let description: String?
public let enabled: Bool
@@ -2070,12 +2165,13 @@ public struct CronJob: Codable, Sendable {
public let sessiontarget: AnyCodable
public let wakemode: AnyCodable
public let payload: AnyCodable
- public let delivery: [String: AnyCodable]?
+ public let delivery: AnyCodable?
public let state: [String: AnyCodable]
public init(
id: String,
agentid: String?,
+ sessionkey: String?,
name: String,
description: String?,
enabled: Bool,
@@ -2086,11 +2182,12 @@ public struct CronJob: Codable, Sendable {
sessiontarget: AnyCodable,
wakemode: AnyCodable,
payload: AnyCodable,
- delivery: [String: AnyCodable]?,
+ delivery: AnyCodable?,
state: [String: AnyCodable]
) {
self.id = id
self.agentid = agentid
+ self.sessionkey = sessionkey
self.name = name
self.description = description
self.enabled = enabled
@@ -2107,6 +2204,7 @@ public struct CronJob: Codable, Sendable {
private enum CodingKeys: String, CodingKey {
case id
case agentid = "agentId"
+ case sessionkey = "sessionKey"
case name
case description
case enabled
@@ -2141,6 +2239,7 @@ public struct CronStatusParams: Codable, Sendable {
public struct CronAddParams: Codable, Sendable {
public let name: String
public let agentid: AnyCodable?
+ public let sessionkey: AnyCodable?
public let description: String?
public let enabled: Bool?
public let deleteafterrun: Bool?
@@ -2148,11 +2247,12 @@ public struct CronAddParams: Codable, Sendable {
public let sessiontarget: AnyCodable
public let wakemode: AnyCodable
public let payload: AnyCodable
- public let delivery: [String: AnyCodable]?
+ public let delivery: AnyCodable?
public init(
name: String,
agentid: AnyCodable?,
+ sessionkey: AnyCodable?,
description: String?,
enabled: Bool?,
deleteafterrun: Bool?,
@@ -2160,10 +2260,11 @@ public struct CronAddParams: Codable, Sendable {
sessiontarget: AnyCodable,
wakemode: AnyCodable,
payload: AnyCodable,
- delivery: [String: AnyCodable]?
+ delivery: AnyCodable?
) {
self.name = name
self.agentid = agentid
+ self.sessionkey = sessionkey
self.description = description
self.enabled = enabled
self.deleteafterrun = deleteafterrun
@@ -2176,6 +2277,7 @@ public struct CronAddParams: Codable, Sendable {
private enum CodingKeys: String, CodingKey {
case name
case agentid = "agentId"
+ case sessionkey = "sessionKey"
case description
case enabled
case deleteafterrun = "deleteAfterRun"
@@ -2472,6 +2574,19 @@ public struct DevicePairRejectParams: Codable, Sendable {
}
}
+public struct DevicePairRemoveParams: Codable, Sendable {
+ public let deviceid: String
+
+ public init(
+ deviceid: String
+ ) {
+ self.deviceid = deviceid
+ }
+ private enum CodingKeys: String, CodingKey {
+ case deviceid = "deviceId"
+ }
+}
+
public struct DeviceTokenRotateParams: Codable, Sendable {
public let deviceid: String
public let role: String
diff --git a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/AnyCodableTests.swift b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/AnyCodableTests.swift
new file mode 100644
index 0000000000000..3835f1186c077
--- /dev/null
+++ b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/AnyCodableTests.swift
@@ -0,0 +1,40 @@
+import Foundation
+import Testing
+import OpenClawProtocol
+
+struct AnyCodableTests {
+ @Test
+ func encodesNSNumberBooleansAsJSONBooleans() throws {
+ let trueData = try JSONEncoder().encode(AnyCodable(NSNumber(value: true)))
+ let falseData = try JSONEncoder().encode(AnyCodable(NSNumber(value: false)))
+
+ #expect(String(data: trueData, encoding: .utf8) == "true")
+ #expect(String(data: falseData, encoding: .utf8) == "false")
+ }
+
+ @Test
+ func preservesBooleanLiteralsFromJSONSerializationBridge() throws {
+ let raw = try #require(
+ JSONSerialization.jsonObject(with: Data(#"{"enabled":true,"nested":{"active":false}}"#.utf8))
+ as? [String: Any]
+ )
+ let enabled = try #require(raw["enabled"])
+ let nested = try #require(raw["nested"])
+
+ struct RequestEnvelope: Codable {
+ let params: [String: AnyCodable]
+ }
+
+ let envelope = RequestEnvelope(
+ params: [
+ "enabled": AnyCodable(enabled),
+ "nested": AnyCodable(nested),
+ ]
+ )
+ let data = try JSONEncoder().encode(envelope)
+ let json = try #require(String(data: data, encoding: .utf8))
+
+ #expect(json.contains(#""enabled":true"#))
+ #expect(json.contains(#""active":false"#))
+ }
+}
diff --git a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatViewModelTests.swift b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatViewModelTests.swift
index 3babe8b9a30c7..ff7caabf381c0 100644
--- a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatViewModelTests.swift
+++ b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatViewModelTests.swift
@@ -215,6 +215,153 @@ extension TestChatTransportState {
#expect(await MainActor.run { vm.pendingToolCalls.isEmpty })
}
+ @Test func acceptsCanonicalSessionKeyEventsForOwnPendingRun() async throws {
+ let history1 = OpenClawChatHistoryPayload(
+ sessionKey: "main",
+ sessionId: "sess-main",
+ messages: [],
+ thinkingLevel: "off")
+ let history2 = OpenClawChatHistoryPayload(
+ sessionKey: "main",
+ sessionId: "sess-main",
+ messages: [
+ AnyCodable([
+ "role": "assistant",
+ "content": [["type": "text", "text": "from history"]],
+ "timestamp": Date().timeIntervalSince1970 * 1000,
+ ]),
+ ],
+ thinkingLevel: "off")
+
+ let transport = TestChatTransport(historyResponses: [history1, history2])
+ let vm = await MainActor.run { OpenClawChatViewModel(sessionKey: "main", transport: transport) }
+
+ await MainActor.run { vm.load() }
+ try await waitUntil("bootstrap") { await MainActor.run { vm.healthOK } }
+
+ await MainActor.run {
+ vm.input = "hi"
+ vm.send()
+ }
+ try await waitUntil("pending run starts") { await MainActor.run { vm.pendingRunCount == 1 } }
+
+ let runId = try #require(await transport.lastSentRunId())
+ transport.emit(
+ .chat(
+ OpenClawChatEventPayload(
+ runId: runId,
+ sessionKey: "agent:main:main",
+ state: "final",
+ message: nil,
+ errorMessage: nil)))
+
+ try await waitUntil("pending run clears") { await MainActor.run { vm.pendingRunCount == 0 } }
+ try await waitUntil("history refresh") {
+ await MainActor.run { vm.messages.contains(where: { $0.role == "assistant" }) }
+ }
+ }
+
+ @Test func acceptsCanonicalSessionKeyEventsForExternalRuns() async throws {
+ let now = Date().timeIntervalSince1970 * 1000
+ let history1 = OpenClawChatHistoryPayload(
+ sessionKey: "main",
+ sessionId: "sess-main",
+ messages: [
+ AnyCodable([
+ "role": "user",
+ "content": [["type": "text", "text": "first"]],
+ "timestamp": now,
+ ]),
+ ],
+ thinkingLevel: "off")
+ let history2 = OpenClawChatHistoryPayload(
+ sessionKey: "main",
+ sessionId: "sess-main",
+ messages: [
+ AnyCodable([
+ "role": "user",
+ "content": [["type": "text", "text": "first"]],
+ "timestamp": now,
+ ]),
+ AnyCodable([
+ "role": "assistant",
+ "content": [["type": "text", "text": "from external run"]],
+ "timestamp": now + 1,
+ ]),
+ ],
+ thinkingLevel: "off")
+
+ let transport = TestChatTransport(historyResponses: [history1, history2])
+ let vm = await MainActor.run { OpenClawChatViewModel(sessionKey: "main", transport: transport) }
+
+ await MainActor.run { vm.load() }
+ try await waitUntil("bootstrap") { await MainActor.run { vm.messages.count == 1 } }
+
+ transport.emit(
+ .chat(
+ OpenClawChatEventPayload(
+ runId: "external-run",
+ sessionKey: "agent:main:main",
+ state: "final",
+ message: nil,
+ errorMessage: nil)))
+
+ try await waitUntil("history refresh after canonical external event") {
+ await MainActor.run { vm.messages.count == 2 }
+ }
+ }
+
+ @Test func preservesMessageIDsAcrossHistoryRefreshes() async throws {
+ let now = Date().timeIntervalSince1970 * 1000
+ let history1 = OpenClawChatHistoryPayload(
+ sessionKey: "main",
+ sessionId: "sess-main",
+ messages: [
+ AnyCodable([
+ "role": "user",
+ "content": [["type": "text", "text": "hello"]],
+ "timestamp": now,
+ ]),
+ ],
+ thinkingLevel: "off")
+ let history2 = OpenClawChatHistoryPayload(
+ sessionKey: "main",
+ sessionId: "sess-main",
+ messages: [
+ AnyCodable([
+ "role": "user",
+ "content": [["type": "text", "text": "hello"]],
+ "timestamp": now,
+ ]),
+ AnyCodable([
+ "role": "assistant",
+ "content": [["type": "text", "text": "world"]],
+ "timestamp": now + 1,
+ ]),
+ ],
+ thinkingLevel: "off")
+
+ let transport = TestChatTransport(historyResponses: [history1, history2])
+ let vm = await MainActor.run { OpenClawChatViewModel(sessionKey: "main", transport: transport) }
+
+ await MainActor.run { vm.load() }
+ try await waitUntil("bootstrap") { await MainActor.run { vm.messages.count == 1 } }
+ let firstIdBefore = try #require(await MainActor.run { vm.messages.first?.id })
+
+ transport.emit(
+ .chat(
+ OpenClawChatEventPayload(
+ runId: "other-run",
+ sessionKey: "main",
+ state: "final",
+ message: nil,
+ errorMessage: nil)))
+
+ try await waitUntil("history refresh") { await MainActor.run { vm.messages.count == 2 } }
+ let firstIdAfter = try #require(await MainActor.run { vm.messages.first?.id })
+ #expect(firstIdAfter == firstIdBefore)
+ }
+
@Test func clearsStreamingOnExternalFinalEvent() async throws {
let sessionId = "sess-main"
let history = OpenClawChatHistoryPayload(
diff --git a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/TalkPromptBuilderTests.swift b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/TalkPromptBuilderTests.swift
index 1ca18fdf32d9d..513b60d047aaf 100644
--- a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/TalkPromptBuilderTests.swift
+++ b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/TalkPromptBuilderTests.swift
@@ -12,4 +12,18 @@ final class TalkPromptBuilderTests: XCTestCase {
let prompt = TalkPromptBuilder.build(transcript: "Hi", interruptedAtSeconds: 1.234)
XCTAssertTrue(prompt.contains("Assistant speech interrupted at 1.2s."))
}
+
+ func testBuildIncludesVoiceDirectiveHintByDefault() {
+ let prompt = TalkPromptBuilder.build(transcript: "Hello", interruptedAtSeconds: nil)
+ XCTAssertTrue(prompt.contains("ElevenLabs voice"))
+ }
+
+ func testBuildExcludesVoiceDirectiveHintWhenDisabled() {
+ let prompt = TalkPromptBuilder.build(
+ transcript: "Hello",
+ interruptedAtSeconds: nil,
+ includeVoiceDirectiveHint: false)
+ XCTAssertFalse(prompt.contains("ElevenLabs voice"))
+ XCTAssertTrue(prompt.contains("Talk Mode active."))
+ }
}
diff --git a/apps/shared/OpenClawKit/Tools/CanvasA2UI/bootstrap.js b/apps/shared/OpenClawKit/Tools/CanvasA2UI/bootstrap.js
index 563adcc3b1d4a..a9cb659876a5c 100644
--- a/apps/shared/OpenClawKit/Tools/CanvasA2UI/bootstrap.js
+++ b/apps/shared/OpenClawKit/Tools/CanvasA2UI/bootstrap.js
@@ -451,7 +451,6 @@ class OpenClawA2UIHost extends LitElement {
if (this.surfaces.length === 0) {
return html`
Canvas (A2UI)
-
Waiting for A2UI messages…
`;
}
diff --git a/assets/chrome-extension/README.md b/assets/chrome-extension/README.md
index 2a2a11a3be5c7..4ee072c1f2bb5 100644
--- a/assets/chrome-extension/README.md
+++ b/assets/chrome-extension/README.md
@@ -20,3 +20,4 @@ Purpose: attach OpenClaw to an existing Chrome tab so the Gateway can automate i
## Options
- `Relay port`: defaults to `18792`.
+- `Gateway token`: required. Set this to `gateway.auth.token` (or `OPENCLAW_GATEWAY_TOKEN`).
diff --git a/assets/chrome-extension/background.js b/assets/chrome-extension/background.js
index 31ba401bddca6..7a1754e06c96b 100644
--- a/assets/chrome-extension/background.js
+++ b/assets/chrome-extension/background.js
@@ -42,6 +42,12 @@ async function getRelayPort() {
return n
}
+async function getGatewayToken() {
+ const stored = await chrome.storage.local.get(['gatewayToken'])
+ const token = String(stored.gatewayToken || '').trim()
+ return token || ''
+}
+
function setBadge(tabId, kind) {
const cfg = BADGE[kind]
void chrome.action.setBadgeText({ tabId, text: cfg.text })
@@ -55,8 +61,11 @@ async function ensureRelayConnection() {
relayConnectPromise = (async () => {
const port = await getRelayPort()
+ const gatewayToken = await getGatewayToken()
const httpBase = `http://127.0.0.1:${port}`
- const wsUrl = `ws://127.0.0.1:${port}/extension`
+ const wsUrl = gatewayToken
+ ? `ws://127.0.0.1:${port}/extension?token=${encodeURIComponent(gatewayToken)}`
+ : `ws://127.0.0.1:${port}/extension`
// Fast preflight: is the relay server up?
try {
@@ -65,6 +74,12 @@ async function ensureRelayConnection() {
throw new Error(`Relay server not reachable at ${httpBase} (${String(err)})`)
}
+ if (!gatewayToken) {
+ throw new Error(
+ 'Missing gatewayToken in extension settings (chrome.storage.local.gatewayToken)',
+ )
+ }
+
const ws = new WebSocket(wsUrl)
relayWs = ws
diff --git a/assets/chrome-extension/options.html b/assets/chrome-extension/options.html
index 14704d65cf0d7..17fc6a79eed33 100644
--- a/assets/chrome-extension/options.html
+++ b/assets/chrome-extension/options.html
@@ -176,15 +176,19 @@
Getting started
-
Relay port
+
Relay connection
+
+
+
+
- Default: 18792. Extension connects to: http://127.0.0.1:<port>/.
- Only change this if your OpenClaw profile uses a different cdpUrl port.
+ Default port: 18792. Extension connects to: http://127.0.0.1:<port>/.
+ Gateway token must match gateway.auth.token (or OPENCLAW_GATEWAY_TOKEN).
diff --git a/assets/chrome-extension/options.js b/assets/chrome-extension/options.js
index 5b558ddccf2d5..e4252ccae4c2b 100644
--- a/assets/chrome-extension/options.js
+++ b/assets/chrome-extension/options.js
@@ -13,6 +13,12 @@ function updateRelayUrl(port) {
el.textContent = `http://127.0.0.1:${port}/`
}
+function relayHeaders(token) {
+ const t = String(token || '').trim()
+ if (!t) return {}
+ return { 'x-openclaw-relay-token': t }
+}
+
function setStatus(kind, message) {
const status = document.getElementById('status')
if (!status) return
@@ -20,18 +26,31 @@ function setStatus(kind, message) {
status.textContent = message || ''
}
-async function checkRelayReachable(port) {
- const url = `http://127.0.0.1:${port}/`
+async function checkRelayReachable(port, token) {
+ const url = `http://127.0.0.1:${port}/json/version`
+ const trimmedToken = String(token || '').trim()
+ if (!trimmedToken) {
+ setStatus('error', 'Gateway token required. Save your gateway token to connect.')
+ return
+ }
const ctrl = new AbortController()
- const t = setTimeout(() => ctrl.abort(), 900)
+ const t = setTimeout(() => ctrl.abort(), 1200)
try {
- const res = await fetch(url, { method: 'HEAD', signal: ctrl.signal })
+ const res = await fetch(url, {
+ method: 'GET',
+ headers: relayHeaders(trimmedToken),
+ signal: ctrl.signal,
+ })
+ if (res.status === 401) {
+ setStatus('error', 'Gateway token rejected. Check token and save again.')
+ return
+ }
if (!res.ok) throw new Error(`HTTP ${res.status}`)
- setStatus('ok', `Relay reachable at ${url}`)
+ setStatus('ok', `Relay reachable and authenticated at http://127.0.0.1:${port}/`)
} catch {
setStatus(
'error',
- `Relay not reachable at ${url}. Start OpenClaw’s browser relay on this machine, then click the toolbar button again.`,
+ `Relay not reachable/authenticated at http://127.0.0.1:${port}/. Start OpenClaw browser relay and verify token.`,
)
} finally {
clearTimeout(t)
@@ -39,20 +58,25 @@ async function checkRelayReachable(port) {
}
async function load() {
- const stored = await chrome.storage.local.get(['relayPort'])
+ const stored = await chrome.storage.local.get(['relayPort', 'gatewayToken'])
const port = clampPort(stored.relayPort)
+ const token = String(stored.gatewayToken || '').trim()
document.getElementById('port').value = String(port)
+ document.getElementById('token').value = token
updateRelayUrl(port)
- await checkRelayReachable(port)
+ await checkRelayReachable(port, token)
}
async function save() {
- const input = document.getElementById('port')
- const port = clampPort(input.value)
- await chrome.storage.local.set({ relayPort: port })
- input.value = String(port)
+ const portInput = document.getElementById('port')
+ const tokenInput = document.getElementById('token')
+ const port = clampPort(portInput.value)
+ const token = String(tokenInput.value || '').trim()
+ await chrome.storage.local.set({ relayPort: port, gatewayToken: token })
+ portInput.value = String(port)
+ tokenInput.value = token
updateRelayUrl(port)
- await checkRelayReachable(port)
+ await checkRelayReachable(port, token)
}
document.getElementById('save').addEventListener('click', () => void save())
diff --git a/docker-setup.sh b/docker-setup.sh
index 1d2f5e53fd126..00c3cf1924fd4 100755
--- a/docker-setup.sh
+++ b/docker-setup.sh
@@ -8,6 +8,11 @@ IMAGE_NAME="${OPENCLAW_IMAGE:-openclaw:local}"
EXTRA_MOUNTS="${OPENCLAW_EXTRA_MOUNTS:-}"
HOME_VOLUME_NAME="${OPENCLAW_HOME_VOLUME:-}"
+fail() {
+ echo "ERROR: $*" >&2
+ exit 1
+}
+
require_cmd() {
if ! command -v "$1" >/dev/null 2>&1; then
echo "Missing dependency: $1" >&2
@@ -15,6 +20,44 @@ require_cmd() {
fi
}
+contains_disallowed_chars() {
+ local value="$1"
+ [[ "$value" == *$'\n'* || "$value" == *$'\r'* || "$value" == *$'\t'* ]]
+}
+
+validate_mount_path_value() {
+ local label="$1"
+ local value="$2"
+ if [[ -z "$value" ]]; then
+ fail "$label cannot be empty."
+ fi
+ if contains_disallowed_chars "$value"; then
+ fail "$label contains unsupported control characters."
+ fi
+ if [[ "$value" =~ [[:space:]] ]]; then
+ fail "$label cannot contain whitespace."
+ fi
+}
+
+validate_named_volume() {
+ local value="$1"
+ if [[ ! "$value" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]*$ ]]; then
+ fail "OPENCLAW_HOME_VOLUME must match [A-Za-z0-9][A-Za-z0-9_.-]* when using a named volume."
+ fi
+}
+
+validate_mount_spec() {
+ local mount="$1"
+ if contains_disallowed_chars "$mount"; then
+ fail "OPENCLAW_EXTRA_MOUNTS entries cannot contain control characters."
+ fi
+ # Keep mount specs strict to avoid YAML structure injection.
+ # Expected format: source:target[:options]
+ if [[ ! "$mount" =~ ^[^[:space:],:]+:[^[:space:],:]+(:[^[:space:],:]+)?$ ]]; then
+ fail "Invalid mount format '$mount'. Expected source:target[:options] without spaces."
+ fi
+}
+
require_cmd docker
if ! docker compose version >/dev/null 2>&1; then
echo "Docker Compose not available (try: docker compose version)" >&2
@@ -24,6 +67,19 @@ fi
OPENCLAW_CONFIG_DIR="${OPENCLAW_CONFIG_DIR:-$HOME/.openclaw}"
OPENCLAW_WORKSPACE_DIR="${OPENCLAW_WORKSPACE_DIR:-$HOME/.openclaw/workspace}"
+validate_mount_path_value "OPENCLAW_CONFIG_DIR" "$OPENCLAW_CONFIG_DIR"
+validate_mount_path_value "OPENCLAW_WORKSPACE_DIR" "$OPENCLAW_WORKSPACE_DIR"
+if [[ -n "$HOME_VOLUME_NAME" ]]; then
+ if [[ "$HOME_VOLUME_NAME" == *"/"* ]]; then
+ validate_mount_path_value "OPENCLAW_HOME_VOLUME" "$HOME_VOLUME_NAME"
+ else
+ validate_named_volume "$HOME_VOLUME_NAME"
+ fi
+fi
+if contains_disallowed_chars "$EXTRA_MOUNTS"; then
+ fail "OPENCLAW_EXTRA_MOUNTS cannot contain control characters."
+fi
+
mkdir -p "$OPENCLAW_CONFIG_DIR"
mkdir -p "$OPENCLAW_WORKSPACE_DIR"
@@ -57,6 +113,9 @@ write_extra_compose() {
local home_volume="$1"
shift
local mount
+ local gateway_home_mount
+ local gateway_config_mount
+ local gateway_workspace_mount
cat >"$EXTRA_COMPOSE_FILE" <<'YAML'
services:
@@ -65,12 +124,19 @@ services:
YAML
if [[ -n "$home_volume" ]]; then
- printf ' - %s:/home/node\n' "$home_volume" >>"$EXTRA_COMPOSE_FILE"
- printf ' - %s:/home/node/.openclaw\n' "$OPENCLAW_CONFIG_DIR" >>"$EXTRA_COMPOSE_FILE"
- printf ' - %s:/home/node/.openclaw/workspace\n' "$OPENCLAW_WORKSPACE_DIR" >>"$EXTRA_COMPOSE_FILE"
+ gateway_home_mount="${home_volume}:/home/node"
+ gateway_config_mount="${OPENCLAW_CONFIG_DIR}:/home/node/.openclaw"
+ gateway_workspace_mount="${OPENCLAW_WORKSPACE_DIR}:/home/node/.openclaw/workspace"
+ validate_mount_spec "$gateway_home_mount"
+ validate_mount_spec "$gateway_config_mount"
+ validate_mount_spec "$gateway_workspace_mount"
+ printf ' - %s\n' "$gateway_home_mount" >>"$EXTRA_COMPOSE_FILE"
+ printf ' - %s\n' "$gateway_config_mount" >>"$EXTRA_COMPOSE_FILE"
+ printf ' - %s\n' "$gateway_workspace_mount" >>"$EXTRA_COMPOSE_FILE"
fi
for mount in "$@"; do
+ validate_mount_spec "$mount"
printf ' - %s\n' "$mount" >>"$EXTRA_COMPOSE_FILE"
done
@@ -80,16 +146,18 @@ YAML
YAML
if [[ -n "$home_volume" ]]; then
- printf ' - %s:/home/node\n' "$home_volume" >>"$EXTRA_COMPOSE_FILE"
- printf ' - %s:/home/node/.openclaw\n' "$OPENCLAW_CONFIG_DIR" >>"$EXTRA_COMPOSE_FILE"
- printf ' - %s:/home/node/.openclaw/workspace\n' "$OPENCLAW_WORKSPACE_DIR" >>"$EXTRA_COMPOSE_FILE"
+ printf ' - %s\n' "$gateway_home_mount" >>"$EXTRA_COMPOSE_FILE"
+ printf ' - %s\n' "$gateway_config_mount" >>"$EXTRA_COMPOSE_FILE"
+ printf ' - %s\n' "$gateway_workspace_mount" >>"$EXTRA_COMPOSE_FILE"
fi
for mount in "$@"; do
+ validate_mount_spec "$mount"
printf ' - %s\n' "$mount" >>"$EXTRA_COMPOSE_FILE"
done
if [[ -n "$home_volume" && "$home_volume" != *"/"* ]]; then
+ validate_named_volume "$home_volume"
cat >>"$EXTRA_COMPOSE_FILE" <`, with delivery (announce by default or none).
- Wakeups are first-class: a job can request “wake now” vs “next heartbeat”.
+- Webhook posting is per job via `delivery.mode = "webhook"` + `delivery.to = ""`.
+- Legacy fallback remains for stored jobs with `notify: true` when `cron.webhook` is set, migrate those jobs to webhook delivery mode.
## Quick start (actionable)
@@ -99,7 +101,7 @@ A cron job is a stored record with:
- a **schedule** (when it should run),
- a **payload** (what it should do),
-- optional **delivery mode** (announce or none).
+- optional **delivery mode** (`announce`, `webhook`, or `none`).
- optional **agent binding** (`agentId`): run the job under a specific agent; if
missing or unknown, the gateway falls back to the default agent.
@@ -113,11 +115,22 @@ Cron supports three schedule kinds:
- `at`: one-shot timestamp via `schedule.at` (ISO 8601).
- `every`: fixed interval (ms).
-- `cron`: 5-field cron expression with optional IANA timezone.
+- `cron`: 5-field cron expression (or 6-field with seconds) with optional IANA timezone.
Cron expressions use `croner`. If a timezone is omitted, the Gateway host’s
local timezone is used.
+To reduce top-of-hour load spikes across many gateways, OpenClaw applies a
+deterministic per-job stagger window of up to 5 minutes for recurring
+top-of-hour expressions (for example `0 * * * *`, `0 */2 * * *`). Fixed-hour
+expressions such as `0 7 * * *` remain exact.
+
+For any cron schedule, you can set an explicit stagger window with `schedule.staggerMs`
+(`0` keeps exact timing). CLI shortcuts:
+
+- `--stagger 30s` (or `1m`, `5m`) to set an explicit stagger window.
+- `--exact` to force `staggerMs = 0`.
+
### Main vs isolated execution
#### Main session jobs (system events)
@@ -140,8 +153,9 @@ Key behaviors:
- Prompt is prefixed with `[cron:]` for traceability.
- Each run starts a **fresh session id** (no prior conversation carry-over).
- Default behavior: if `delivery` is omitted, isolated jobs announce a summary (`delivery.mode = "announce"`).
-- `delivery.mode` (isolated-only) chooses what happens:
+- `delivery.mode` chooses what happens:
- `announce`: deliver a summary to the target channel and post a brief summary to the main session.
+ - `webhook`: POST the finished event payload to `delivery.to` when the finished event includes a summary.
- `none`: internal only (no delivery, no main-session summary).
- `wakeMode` controls when the main-session summary posts:
- `now`: immediate heartbeat.
@@ -163,11 +177,11 @@ Common `agentTurn` fields:
- `model` / `thinking`: optional overrides (see below).
- `timeoutSeconds`: optional timeout override.
-Delivery config (isolated jobs only):
+Delivery config:
-- `delivery.mode`: `none` | `announce`.
+- `delivery.mode`: `none` | `announce` | `webhook`.
- `delivery.channel`: `last` or a specific channel.
-- `delivery.to`: channel-specific target (phone/chat/channel id).
+- `delivery.to`: channel-specific target (announce) or webhook URL (webhook mode).
- `delivery.bestEffort`: avoid failing the job if announce delivery fails.
Announce delivery suppresses messaging tool sends for the run; use `delivery.channel`/`delivery.to`
@@ -192,6 +206,18 @@ Behavior details:
- The main-session summary respects `wakeMode`: `now` triggers an immediate heartbeat and
`next-heartbeat` waits for the next scheduled heartbeat.
+#### Webhook delivery flow
+
+When `delivery.mode = "webhook"`, cron posts the finished event payload to `delivery.to` when the finished event includes a summary.
+
+Behavior details:
+
+- The endpoint must be a valid HTTP(S) URL.
+- No channel delivery is attempted in webhook mode.
+- No main-session summary is posted in webhook mode.
+- If `cron.webhookToken` is set, auth header is `Authorization: Bearer `.
+- Deprecated fallback: stored legacy jobs with `notify: true` still post to `cron.webhook` (if configured), with a warning so you can migrate to `delivery.mode = "webhook"`.
+
### Model and thinking overrides
Isolated jobs (`agentTurn`) can override the model and thinking level:
@@ -213,11 +239,12 @@ Resolution priority:
Isolated jobs can deliver output to a channel via the top-level `delivery` config:
-- `delivery.mode`: `announce` (deliver a summary) or `none`.
+- `delivery.mode`: `announce` (channel delivery), `webhook` (HTTP POST), or `none`.
- `delivery.channel`: `whatsapp` / `telegram` / `discord` / `slack` / `mattermost` (plugin) / `signal` / `imessage` / `last`.
- `delivery.to`: channel-specific recipient target.
-Delivery config is only valid for isolated jobs (`sessionTarget: "isolated"`).
+`announce` delivery is only valid for isolated jobs (`sessionTarget: "isolated"`).
+`webhook` delivery is valid for both main and isolated jobs.
If `delivery.channel` or `delivery.to` is omitted, cron can fall back to the main session’s
“last route” (the last place the agent replied).
@@ -333,10 +360,21 @@ Notes:
enabled: true, // default true
store: "~/.openclaw/cron/jobs.json",
maxConcurrentRuns: 1, // default 1
+ webhook: "https://example.invalid/legacy", // deprecated fallback for stored notify:true jobs
+ webhookToken: "replace-with-dedicated-webhook-token", // optional bearer token for webhook mode
},
}
```
+Webhook behavior:
+
+- Preferred: set `delivery.mode: "webhook"` with `delivery.to: "https://..."` per job.
+- Webhook URLs must be valid `http://` or `https://` URLs.
+- When posted, payload is the cron finished event JSON.
+- If `cron.webhookToken` is set, auth header is `Authorization: Bearer `.
+- If `cron.webhookToken` is not set, no `Authorization` header is sent.
+- Deprecated fallback: stored legacy jobs with `notify: true` still use `cron.webhook` when present.
+
Disable cron entirely:
- `cron.enabled: false` (config)
@@ -381,6 +419,19 @@ openclaw cron add \
--to "+15551234567"
```
+Recurring cron job with explicit 30-second stagger:
+
+```bash
+openclaw cron add \
+ --name "Minute watcher" \
+ --cron "0 * * * * *" \
+ --tz "UTC" \
+ --stagger 30s \
+ --session isolated \
+ --message "Run minute watcher checks." \
+ --announce
+```
+
Recurring isolated job (deliver to a Telegram topic):
```bash
@@ -438,6 +489,12 @@ openclaw cron edit \
--thinking low
```
+Force an existing cron job to run exactly on schedule (no stagger):
+
+```bash
+openclaw cron edit --exact
+```
+
Run history:
```bash
@@ -476,3 +533,10 @@ openclaw system event --mode now --text "Next heartbeat: check battery."
- For forum topics, use `-100…:topic:` so it’s explicit and unambiguous.
- If you see `telegram:...` prefixes in logs or stored “last route” targets, that’s normal;
cron delivery accepts them and still parses topic IDs correctly.
+
+### Subagent announce delivery retries
+
+- When a subagent run completes, the gateway announces the result to the requester session.
+- If the announce flow returns `false` (e.g. requester session is busy), the gateway retries up to 3 times with tracking via `announceRetryCount`.
+- Announces older than 5 minutes past `endedAt` are force-expired to prevent stale entries from looping indefinitely.
+- If you see repeated announce deliveries in logs, check the subagent registry for entries with high `announceRetryCount` values.
diff --git a/docs/automation/cron-vs-heartbeat.md b/docs/automation/cron-vs-heartbeat.md
index 423565d4f3268..c25cbcb80dbc9 100644
--- a/docs/automation/cron-vs-heartbeat.md
+++ b/docs/automation/cron-vs-heartbeat.md
@@ -74,7 +74,9 @@ See [Heartbeat](/gateway/heartbeat) for full configuration.
## Cron: Precise Scheduling
-Cron jobs run at **exact times** and can run in isolated sessions without affecting main context.
+Cron jobs run at precise times and can run in isolated sessions without affecting main context.
+Recurring top-of-hour schedules are automatically spread by a deterministic
+per-job offset in a 0-5 minute window.
### When to use cron
@@ -87,7 +89,9 @@ Cron jobs run at **exact times** and can run in isolated sessions without affect
### Cron advantages
-- **Exact timing**: 5-field cron expressions with timezone support.
+- **Precise timing**: 5-field or 6-field (seconds) cron expressions with timezone support.
+- **Built-in load spreading**: recurring top-of-hour schedules are staggered by up to 5 minutes by default.
+- **Per-job control**: override stagger with `--stagger ` or force exact timing with `--exact`.
- **Session isolation**: Runs in `cron:` without polluting main history.
- **Model overrides**: Use a cheaper or more powerful model per job.
- **Delivery control**: Isolated jobs default to `announce` (summary); choose `none` as needed.
@@ -207,7 +211,7 @@ For ad-hoc workflows, call Lobster directly.
- Lobster runs as a **local subprocess** (`lobster` CLI) in tool mode and returns a **JSON envelope**.
- If the tool returns `needs_approval`, you resume with a `resumeToken` and `approve` flag.
- The tool is an **optional plugin**; enable it additively via `tools.alsoAllow: ["lobster"]` (recommended).
-- If you pass `lobsterPath`, it must be an **absolute path**.
+- Lobster expects the `lobster` CLI to be available on `PATH`.
See [Lobster](/tools/lobster) for full usage and examples.
diff --git a/docs/automation/hooks.md b/docs/automation/hooks.md
index ffdf32ab79b00..66b96cd1e9e96 100644
--- a/docs/automation/hooks.md
+++ b/docs/automation/hooks.md
@@ -119,6 +119,8 @@ Example `package.json`:
Each entry points to a hook directory containing `HOOK.md` and `handler.ts` (or `index.ts`).
Hook packs can ship dependencies; they will be installed under `~/.openclaw/hooks/`.
+Each `openclaw.hooks` entry must stay inside the package directory after symlink
+resolution; entries that escape are rejected.
Security note: `openclaw hooks install` installs dependencies with `npm install --ignore-scripts`
(no lifecycle scripts). Keep hook pack dependency trees "pure JS/TS" and avoid packages that rely
@@ -207,12 +209,13 @@ Each event includes:
```typescript
{
- type: 'command' | 'session' | 'agent' | 'gateway',
- action: string, // e.g., 'new', 'reset', 'stop'
+ type: 'command' | 'session' | 'agent' | 'gateway' | 'message',
+ action: string, // e.g., 'new', 'reset', 'stop', 'received', 'sent'
sessionKey: string, // Session identifier
timestamp: Date, // When the event occurred
messages: string[], // Push messages here to send to user
context: {
+ // Command events:
sessionEntry?: SessionEntry,
sessionId?: string,
sessionFile?: string,
@@ -220,7 +223,13 @@ Each event includes:
senderId?: string,
workspaceDir?: string,
bootstrapFiles?: WorkspaceBootstrapFile[],
- cfg?: OpenClawConfig
+ cfg?: OpenClawConfig,
+ // Message events (see Message Events section for full details):
+ from?: string, // message:received
+ to?: string, // message:sent
+ content?: string,
+ channelId?: string,
+ success?: boolean, // message:sent
}
}
```
@@ -246,6 +255,70 @@ Triggered when the gateway starts:
- **`gateway:startup`**: After channels start and hooks are loaded
+### Message Events
+
+Triggered when messages are received or sent:
+
+- **`message`**: All message events (general listener)
+- **`message:received`**: When an inbound message is received from any channel
+- **`message:sent`**: When an outbound message is successfully sent
+
+#### Message Event Context
+
+Message events include rich context about the message:
+
+```typescript
+// message:received context
+{
+ from: string, // Sender identifier (phone number, user ID, etc.)
+ content: string, // Message content
+ timestamp?: number, // Unix timestamp when received
+ channelId: string, // Channel (e.g., "whatsapp", "telegram", "discord")
+ accountId?: string, // Provider account ID for multi-account setups
+ conversationId?: string, // Chat/conversation ID
+ messageId?: string, // Message ID from the provider
+ metadata?: { // Additional provider-specific data
+ to?: string,
+ provider?: string,
+ surface?: string,
+ threadId?: string,
+ senderId?: string,
+ senderName?: string,
+ senderUsername?: string,
+ senderE164?: string,
+ }
+}
+
+// message:sent context
+{
+ to: string, // Recipient identifier
+ content: string, // Message content that was sent
+ success: boolean, // Whether the send succeeded
+ error?: string, // Error message if sending failed
+ channelId: string, // Channel (e.g., "whatsapp", "telegram", "discord")
+ accountId?: string, // Provider account ID
+ conversationId?: string, // Chat/conversation ID
+ messageId?: string, // Message ID returned by the provider
+}
+```
+
+#### Example: Message Logger Hook
+
+```typescript
+import type { HookHandler } from "../../src/hooks/hooks.js";
+import { isMessageReceivedEvent, isMessageSentEvent } from "../../src/hooks/internal-hooks.js";
+
+const handler: HookHandler = async (event) => {
+ if (isMessageReceivedEvent(event)) {
+ console.log(`[message-logger] Received from ${event.context.from}: ${event.context.content}`);
+ } else if (isMessageSentEvent(event)) {
+ console.log(`[message-logger] Sent to ${event.context.to}: ${event.context.content}`);
+ }
+};
+
+export default handler;
+```
+
### Tool Result Hooks (Plugin API)
These hooks are not event-stream listeners; they let plugins synchronously adjust tool results before OpenClaw persists them.
@@ -259,8 +332,6 @@ Planned event types:
- **`session:start`**: When a new session begins
- **`session:end`**: When a session ends
- **`agent:error`**: When an agent encounters an error
-- **`message:sent`**: When a message is sent
-- **`message:received`**: When a message is received
## Creating Custom Hooks
diff --git a/docs/automation/troubleshooting.md b/docs/automation/troubleshooting.md
index 51f2aa209cf41..a189d805221f9 100644
--- a/docs/automation/troubleshooting.md
+++ b/docs/automation/troubleshooting.md
@@ -89,7 +89,8 @@ Common signatures:
- `heartbeat skipped` with `reason=quiet-hours` → outside `activeHours`.
- `requests-in-flight` → main lane busy; heartbeat deferred.
-- `empty-heartbeat-file` → `HEARTBEAT.md` exists but has no actionable content.
+- `empty-heartbeat-file` → interval heartbeat skipped because `HEARTBEAT.md` has no actionable content and no tagged cron event is queued.
+- `no-heartbeat-file` → interval heartbeat skipped because `HEARTBEAT.md` is missing and no tagged cron event is queued.
- `alerts-disabled` → visibility settings suppress outbound heartbeat messages.
## Timezone and activeHours gotchas
diff --git a/docs/channels/bluebubbles.md b/docs/channels/bluebubbles.md
index a63d2f1d35ec2..fd677a1d585df 100644
--- a/docs/channels/bluebubbles.md
+++ b/docs/channels/bluebubbles.md
@@ -44,6 +44,10 @@ Status: bundled plugin that talks to the BlueBubbles macOS server over HTTP. **R
4. Point BlueBubbles webhooks to your gateway (example: `https://your-gateway-host:3000/bluebubbles-webhook?password=`).
5. Start the gateway; it will register the webhook handler and start pairing.
+Security note:
+
+- Always set a webhook password. If you expose the gateway through a reverse proxy (Tailscale Serve/Funnel, nginx, Cloudflare Tunnel, ngrok), the proxy may connect to the gateway over loopback. The BlueBubbles webhook handler treats requests with forwarding headers as proxied and will not accept passwordless webhooks.
+
## Keeping Messages.app alive (VM / headless setups)
Some macOS VM / always-on setups can end up with Messages.app going “idle” (incoming events stop until the app is opened/foregrounded). A simple workaround is to **poke Messages every 5 minutes** using an AppleScript + LaunchAgent.
diff --git a/docs/channels/discord.md b/docs/channels/discord.md
index 29d99253fa45e..774a0eba1a8e0 100644
--- a/docs/channels/discord.md
+++ b/docs/channels/discord.md
@@ -23,16 +23,98 @@ Status: ready for DMs and guild channels via the official Discord gateway.
## Quick setup
+You will need to create a new application with a bot, add the bot to your server, and pair it to OpenClaw. We recommend adding your bot to your own private server. If you don't have one yet, [create one first](https://support.discord.com/hc/en-us/articles/204849977-How-do-I-create-a-server) (choose **Create My Own > For me and my friends**).
+
-
- Create an application in the Discord Developer Portal, add a bot, then enable:
+
+ Go to the [Discord Developer Portal](https://discord.com/developers/applications) and click **New Application**. Name it something like "OpenClaw".
+
+ Click **Bot** on the sidebar. Set the **Username** to whatever you call your OpenClaw agent.
+
+
+
+
+ Still on the **Bot** page, scroll down to **Privileged Gateway Intents** and enable:
+
+ - **Message Content Intent** (required)
+ - **Server Members Intent** (recommended; required for role allowlists and name-to-ID matching)
+ - **Presence Intent** (optional; only needed for presence updates)
+
+
+
+
+ Scroll back up on the **Bot** page and click **Reset Token**.
+
+
+ Despite the name, this generates your first token — nothing is being "reset."
+
- - **Message Content Intent**
- - **Server Members Intent** (required for role allowlists and role-based routing; recommended for name-to-ID allowlist matching)
+ Copy the token and save it somewhere. This is your **Bot Token** and you will need it shortly.
-
+
+ Click **OAuth2** on the sidebar. You'll generate an invite URL with the right permissions to add the bot to your server.
+
+ Scroll down to **OAuth2 URL Generator** and enable:
+
+ - `bot`
+ - `applications.commands`
+
+ A **Bot Permissions** section will appear below. Enable:
+
+ - View Channels
+ - Send Messages
+ - Read Message History
+ - Embed Links
+ - Attach Files
+ - Add Reactions (optional)
+
+ Copy the generated URL at the bottom, paste it into your browser, select your server, and click **Continue** to connect. You should now see your bot in the Discord server.
+
+
+
+
+ Back in the Discord app, you need to enable Developer Mode so you can copy internal IDs.
+
+ 1. Click **User Settings** (gear icon next to your avatar) → **Advanced** → toggle on **Developer Mode**
+ 2. Right-click your **server icon** in the sidebar → **Copy Server ID**
+ 3. Right-click your **own avatar** → **Copy User ID**
+
+ Save your **Server ID** and **User ID** alongside your Bot Token — you'll send all three to OpenClaw in the next step.
+
+
+
+
+ For pairing to work, Discord needs to allow your bot to DM you. Right-click your **server icon** → **Privacy Settings** → toggle on **Direct Messages**.
+
+ This lets server members (including bots) send you DMs. Keep this enabled if you want to use Discord DMs with OpenClaw. If you only plan to use guild channels, you can disable DMs after pairing.
+
+
+
+
+ Your Discord bot token is a secret (like a password). Set it on the machine running OpenClaw before messaging your agent.
+
+```bash
+openclaw config set channels.discord.token '"YOUR_BOT_TOKEN"' --json
+openclaw config set channels.discord.enabled true --json
+openclaw gateway
+```
+
+ If OpenClaw is already running as a background service, use `openclaw gateway restart` instead.
+
+
+
+
+
+
+
+ Chat with your OpenClaw agent on any existing channel (e.g. Telegram) and tell it. If Discord is your first channel, use the CLI / config tab instead.
+
+ > "I already set my Discord bot token in config. Please finish Discord setup with User ID `` and Server ID ``."
+
+
+ If you prefer file-based config, set:
```json5
{
@@ -45,32 +127,40 @@ Status: ready for DMs and guild channels via the official Discord gateway.
}
```
- Env fallback for the default account:
+ Env fallback for the default account:
```bash
DISCORD_BOT_TOKEN=...
```
-
-
-
- Invite the bot to your server with message permissions.
-
-```bash
-openclaw gateway
-```
+
+
+ Wait until the gateway is running, then DM your bot in Discord. It will respond with a pairing code.
+
+
+
+ Send the pairing code to your agent on your existing channel:
+
+ > "Approve this Discord pairing code: ``"
+
+
```bash
openclaw pairing list discord
openclaw pairing approve discord
```
+
+
+
Pairing codes expire after 1 hour.
+ You should now be able to chat with your agent in Discord via DM.
+
@@ -78,6 +168,87 @@ openclaw pairing approve discord
Token resolution is account-aware. Config token values win over env fallback. `DISCORD_BOT_TOKEN` is only used for the default account.
+## Recommended: Set up a guild workspace
+
+Once DMs are working, you can set up your Discord server as a full workspace where each channel gets its own agent session with its own context. This is recommended for private servers where it's just you and your bot.
+
+
+
+ This enables your agent to respond in any channel on your server, not just DMs.
+
+
+
+ > "Add my Discord Server ID `` to the guild allowlist"
+
+
+
+```json5
+{
+ channels: {
+ discord: {
+ groupPolicy: "allowlist",
+ guilds: {
+ YOUR_SERVER_ID: {
+ requireMention: true,
+ users: ["YOUR_USER_ID"],
+ },
+ },
+ },
+ },
+}
+```
+
+
+
+
+
+
+
+ By default, your agent only responds in guild channels when @mentioned. For a private server, you probably want it to respond to every message.
+
+
+
+ > "Allow my agent to respond on this server without having to be @mentioned"
+
+
+ Set `requireMention: false` in your guild config:
+
+```json5
+{
+ channels: {
+ discord: {
+ guilds: {
+ YOUR_SERVER_ID: {
+ requireMention: false,
+ },
+ },
+ },
+ },
+}
+```
+
+
+
+
+
+
+
+ By default, long-term memory (MEMORY.md) only loads in DM sessions. Guild channels do not auto-load MEMORY.md.
+
+
+
+ > "When I ask questions in Discord channels, use memory_search or memory_get if you need long-term context from MEMORY.md."
+
+
+ If you need shared context in every channel, put the stable instructions in `AGENTS.md` or `USER.md` (they are injected for every session). Keep long-term notes in `MEMORY.md` and access them on demand with memory tools.
+
+
+
+
+
+
+Now create some channels on your Discord server and start chatting. Your agent can see the channel name, and each channel gets its own isolated session — so you can set up `#coding`, `#home`, `#research`, or whatever fits your workflow.
+
## Runtime model
- Gateway owns the Discord connection.
@@ -87,15 +258,95 @@ Token resolution is account-aware. Config token values win over env fallback. `D
- Group DMs are ignored by default (`channels.discord.dm.groupEnabled=false`).
- Native slash commands run in isolated command sessions (`agent::discord:slash:`), while still carrying `CommandTargetSessionKey` to the routed conversation session.
+## Interactive components
+
+OpenClaw supports Discord components v2 containers for agent messages. Use the message tool with a `components` payload. Interaction results are routed back to the agent as normal inbound messages and follow the existing Discord `replyToMode` settings.
+
+Supported blocks:
+
+- `text`, `section`, `separator`, `actions`, `media-gallery`, `file`
+- Action rows allow up to 5 buttons or a single select menu
+- Select types: `string`, `user`, `role`, `mentionable`, `channel`
+
+By default, components are single use. Set `components.reusable=true` to allow buttons, selects, and forms to be used multiple times until they expire.
+
+To restrict who can click a button, set `allowedUsers` on that button (Discord user IDs, tags, or `*`). When configured, unmatched users receive an ephemeral denial.
+
+File attachments:
+
+- `file` blocks must point to an attachment reference (`attachment://`)
+- Provide the attachment via `media`/`path`/`filePath` (single file); use `media-gallery` for multiple files
+- Use `filename` to override the upload name when it should match the attachment reference
+
+Modal forms:
+
+- Add `components.modal` with up to 5 fields
+- Field types: `text`, `checkbox`, `radio`, `select`, `role-select`, `user-select`
+- OpenClaw adds a trigger button automatically
+
+Example:
+
+```json5
+{
+ channel: "discord",
+ action: "send",
+ to: "channel:123456789012345678",
+ message: "Optional fallback text",
+ components: {
+ reusable: true,
+ text: "Choose a path",
+ blocks: [
+ {
+ type: "actions",
+ buttons: [
+ {
+ label: "Approve",
+ style: "success",
+ allowedUsers: ["123456789012345678"],
+ },
+ { label: "Decline", style: "danger" },
+ ],
+ },
+ {
+ type: "actions",
+ select: {
+ type: "string",
+ placeholder: "Pick an option",
+ options: [
+ { label: "Option A", value: "a" },
+ { label: "Option B", value: "b" },
+ ],
+ },
+ },
+ ],
+ modal: {
+ title: "Details",
+ triggerLabel: "Open form",
+ fields: [
+ { type: "text", label: "Requester" },
+ {
+ type: "select",
+ label: "Priority",
+ options: [
+ { label: "Low", value: "low" },
+ { label: "High", value: "high" },
+ ],
+ },
+ ],
+ },
+ },
+}
+```
+
## Access control and routing
- `channels.discord.dm.policy` controls DM access:
+ `channels.discord.dmPolicy` controls DM access (legacy: `channels.discord.dm.policy`):
- `pairing` (default)
- `allowlist`
- - `open` (requires `channels.discord.dm.allowFrom` to include `"*"`)
+ - `open` (requires `channels.discord.allowFrom` to include `"*"`; legacy: `channels.discord.dm.allowFrom`)
- `disabled`
If DM policy is not open, unknown users are blocked (or prompted for pairing in `pairing` mode).
@@ -313,6 +564,23 @@ See [Slash commands](/tools/slash-commands) for command catalog and behavior.
+
+ `ackReaction` sends an acknowledgement emoji while OpenClaw is processing an inbound message.
+
+ Resolution order:
+
+ - `channels.discord.accounts..ackReaction`
+ - `channels.discord.ackReaction`
+ - `messages.ackReaction`
+ - agent identity emoji fallback (`agents.list[].identity.emoji`, else "👀")
+
+ Notes:
+
+ - Discord accepts unicode emoji or custom emoji names.
+ - Use `""` to disable the reaction for a channel or account.
+
+
+
Channel-initiated config writes are enabled by default.
@@ -333,7 +601,7 @@ See [Slash commands](/tools/slash-commands) for command catalog and behavior.
- Route Discord gateway WebSocket traffic through an HTTP(S) proxy with `channels.discord.proxy`.
+ Route Discord gateway WebSocket traffic and startup REST lookups (application ID + allowlist resolution) through an HTTP(S) proxy with `channels.discord.proxy`.
```json5
{
@@ -482,6 +750,30 @@ Default gate behavior:
| moderation | disabled |
| presence | disabled |
+## Components v2 UI
+
+OpenClaw uses Discord components v2 for exec approvals and cross-context markers. Discord message actions can also accept `components` for custom UI (advanced; requires Carbon component instances), while legacy `embeds` remain available but are not recommended.
+
+- `channels.discord.ui.components.accentColor` sets the accent color used by Discord component containers (hex).
+- Set per account with `channels.discord.accounts..ui.components.accentColor`.
+- `embeds` are ignored when components v2 are present.
+
+Example:
+
+```json5
+{
+ channels: {
+ discord: {
+ ui: {
+ components: {
+ accentColor: "#5865F2",
+ },
+ },
+ },
+ },
+}
+```
+
## Voice messages
Discord voice messages show a waveform preview and require OGG/Opus audio plus metadata. OpenClaw generates the waveform automatically, but it needs `ffmpeg` and `ffprobe` available on the gateway host to inspect and convert audio files.
@@ -545,7 +837,7 @@ openclaw logs --follow
- DM disabled: `channels.discord.dm.enabled=false`
- - DM policy disabled: `channels.discord.dm.policy="disabled"`
+ - DM policy disabled: `channels.discord.dmPolicy="disabled"` (legacy: `channels.discord.dm.policy`)
- awaiting pairing approval in `pairing` mode
@@ -574,6 +866,7 @@ High-signal Discord fields:
- media/retry: `mediaMaxMb`, `retry`
- actions: `actions.*`
- presence: `activity`, `status`, `activityType`, `activityUrl`
+- UI: `ui.components.accentColor`
- features: `pluralkit`, `execApprovals`, `intents`, `agentComponents`, `heartbeat`, `responsePrefix`
## Safety and operations
@@ -586,5 +879,6 @@ High-signal Discord fields:
- [Pairing](/channels/pairing)
- [Channel routing](/channels/channel-routing)
+- [Multi-agent routing](/concepts/multi-agent)
- [Troubleshooting](/channels/troubleshooting)
- [Slash commands](/tools/slash-commands)
diff --git a/docs/channels/feishu.md b/docs/channels/feishu.md
index 461facdbb2730..e92f84460d386 100644
--- a/docs/channels/feishu.md
+++ b/docs/channels/feishu.md
@@ -193,6 +193,8 @@ Edit `~/.openclaw/openclaw.json`:
}
```
+If you use `connectionMode: "webhook"`, set `verificationToken`. The Feishu webhook server binds to `127.0.0.1` by default; set `webhookHost` only if you intentionally need a different bind address.
+
### Configure via environment variables
```bash
@@ -527,23 +529,28 @@ Full configuration: [Gateway configuration](/gateway/configuration)
Key options:
-| Setting | Description | Default |
-| ------------------------------------------------- | ------------------------------- | --------- |
-| `channels.feishu.enabled` | Enable/disable channel | `true` |
-| `channels.feishu.domain` | API domain (`feishu` or `lark`) | `feishu` |
-| `channels.feishu.accounts..appId` | App ID | - |
-| `channels.feishu.accounts..appSecret` | App Secret | - |
-| `channels.feishu.accounts..domain` | Per-account API domain override | `feishu` |
-| `channels.feishu.dmPolicy` | DM policy | `pairing` |
-| `channels.feishu.allowFrom` | DM allowlist (open_id list) | - |
-| `channels.feishu.groupPolicy` | Group policy | `open` |
-| `channels.feishu.groupAllowFrom` | Group allowlist | - |
-| `channels.feishu.groups..requireMention` | Require @mention | `true` |
-| `channels.feishu.groups..enabled` | Enable group | `true` |
-| `channels.feishu.textChunkLimit` | Message chunk size | `2000` |
-| `channels.feishu.mediaMaxMb` | Media size limit | `30` |
-| `channels.feishu.streaming` | Enable streaming card output | `true` |
-| `channels.feishu.blockStreaming` | Enable block streaming | `true` |
+| Setting | Description | Default |
+| ------------------------------------------------- | ------------------------------- | ---------------- |
+| `channels.feishu.enabled` | Enable/disable channel | `true` |
+| `channels.feishu.domain` | API domain (`feishu` or `lark`) | `feishu` |
+| `channels.feishu.connectionMode` | Event transport mode | `websocket` |
+| `channels.feishu.verificationToken` | Required for webhook mode | - |
+| `channels.feishu.webhookPath` | Webhook route path | `/feishu/events` |
+| `channels.feishu.webhookHost` | Webhook bind host | `127.0.0.1` |
+| `channels.feishu.webhookPort` | Webhook bind port | `3000` |
+| `channels.feishu.accounts..appId` | App ID | - |
+| `channels.feishu.accounts..appSecret` | App Secret | - |
+| `channels.feishu.accounts..domain` | Per-account API domain override | `feishu` |
+| `channels.feishu.dmPolicy` | DM policy | `pairing` |
+| `channels.feishu.allowFrom` | DM allowlist (open_id list) | - |
+| `channels.feishu.groupPolicy` | Group policy | `open` |
+| `channels.feishu.groupAllowFrom` | Group allowlist | - |
+| `channels.feishu.groups..requireMention` | Require @mention | `true` |
+| `channels.feishu.groups..enabled` | Enable group | `true` |
+| `channels.feishu.textChunkLimit` | Message chunk size | `2000` |
+| `channels.feishu.mediaMaxMb` | Media size limit | `30` |
+| `channels.feishu.streaming` | Enable streaming card output | `true` |
+| `channels.feishu.blockStreaming` | Enable block streaming | `true` |
---
diff --git a/docs/channels/grammy.md b/docs/channels/grammy.md
index c2891d1a2eeb3..ae92c5292b02c 100644
--- a/docs/channels/grammy.md
+++ b/docs/channels/grammy.md
@@ -21,7 +21,7 @@ title: grammY
- **Webhook support:** `webhook-set.ts` wraps `setWebhook/deleteWebhook`; `webhook.ts` hosts the callback with health + graceful shutdown. Gateway enables webhook mode when `channels.telegram.webhookUrl` + `channels.telegram.webhookSecret` are set (otherwise it long-polls).
- **Sessions:** direct chats collapse into the agent main session (`agent::`); groups use `agent::telegram:group:`; replies route back to the same channel.
- **Config knobs:** `channels.telegram.botToken`, `channels.telegram.dmPolicy`, `channels.telegram.groups` (allowlist + mention defaults), `channels.telegram.allowFrom`, `channels.telegram.groupAllowFrom`, `channels.telegram.groupPolicy`, `channels.telegram.mediaMaxMb`, `channels.telegram.linkPreview`, `channels.telegram.proxy`, `channels.telegram.webhookSecret`, `channels.telegram.webhookUrl`, `channels.telegram.webhookHost`.
-- **Draft streaming:** optional `channels.telegram.streamMode` uses `sendMessageDraft` in private topic chats (Bot API 9.3+). This is separate from channel block streaming.
+- **Live stream preview:** optional `channels.telegram.streamMode` sends a temporary message and updates it with `editMessageText`. This is separate from channel block streaming.
- **Tests:** grammy mocks cover DM + group mention gating and outbound send; more media/webhook fixtures still welcome.
Open questions
diff --git a/docs/channels/groups.md b/docs/channels/groups.md
index 1b3fb0394a332..6bd278846c5bd 100644
--- a/docs/channels/groups.md
+++ b/docs/channels/groups.md
@@ -105,7 +105,7 @@ Want “groups can only see folder X” instead of “no host access”? Keep `w
docker: {
binds: [
// hostPath:containerPath:mode
- "~/FriendsShared:/data:ro",
+ "/home/user/FriendsShared:/data:ro",
],
},
},
diff --git a/docs/channels/imessage.md b/docs/channels/imessage.md
index 2876be3137280..d7a1b6335977a 100644
--- a/docs/channels/imessage.md
+++ b/docs/channels/imessage.md
@@ -97,12 +97,19 @@ exec ssh -T gateway-host imsg "$@"
cliPath: "~/.openclaw/scripts/imsg-ssh",
remoteHost: "user@gateway-host", // used for SCP attachment fetches
includeAttachments: true,
+ // Optional: override allowed attachment roots.
+ // Defaults include /Users/*/Library/Messages/Attachments
+ attachmentRoots: ["/Users/*/Library/Messages/Attachments"],
+ remoteAttachmentRoots: ["/Users/*/Library/Messages/Attachments"],
},
},
}
```
If `remoteHost` is not set, OpenClaw attempts to auto-detect it by parsing the SSH wrapper script.
+ `remoteHost` must be `host` or `user@host` (no spaces or SSH options).
+ OpenClaw uses strict host-key checking for SCP, so the relay host key must already exist in `~/.ssh/known_hosts`.
+ Attachment paths are validated against allowed roots (`attachmentRoots` / `remoteAttachmentRoots`).
@@ -224,13 +231,14 @@ exec ssh -T bot@mac-mini.tailnet-1234.ts.net imsg "$@"
```
Use SSH keys so both SSH and SCP are non-interactive.
+ Ensure the host key is trusted first (for example `ssh bot@mac-mini.tailnet-1234.ts.net`) so `known_hosts` is populated.
iMessage supports per-account config under `channels.imessage.accounts`.
- Each account can override fields such as `cliPath`, `dbPath`, `allowFrom`, `groupPolicy`, `mediaMaxMb`, and history settings.
+ Each account can override fields such as `cliPath`, `dbPath`, `allowFrom`, `groupPolicy`, `mediaMaxMb`, history settings, and attachment root allowlists.
@@ -241,6 +249,11 @@ exec ssh -T bot@mac-mini.tailnet-1234.ts.net imsg "$@"
- inbound attachment ingestion is optional: `channels.imessage.includeAttachments`
- remote attachment paths can be fetched via SCP when `remoteHost` is set
+ - attachment paths must match allowed roots:
+ - `channels.imessage.attachmentRoots` (local)
+ - `channels.imessage.remoteAttachmentRoots` (remote SCP mode)
+ - default root pattern: `/Users/*/Library/Messages/Attachments`
+ - SCP uses strict host-key checking (`StrictHostKeyChecking=yes`)
- outbound media size uses `channels.imessage.mediaMaxMb` (default 16 MB)
@@ -325,7 +338,9 @@ openclaw channels status --probe
Check:
- `channels.imessage.remoteHost`
+ - `channels.imessage.remoteAttachmentRoots`
- SSH/SCP key auth from the gateway host
+ - host key exists in `~/.ssh/known_hosts` on the gateway host
- remote path readability on the Mac running Messages
diff --git a/docs/channels/matrix.md b/docs/channels/matrix.md
index 93bcaada5680b..04205d9497110 100644
--- a/docs/channels/matrix.md
+++ b/docs/channels/matrix.md
@@ -190,6 +190,7 @@ Notes:
- `openclaw pairing approve matrix `
- Public DMs: `channels.matrix.dm.policy="open"` plus `channels.matrix.dm.allowFrom=["*"]`.
- `channels.matrix.dm.allowFrom` accepts full Matrix user IDs (example: `@user:server`). The wizard resolves display names to user IDs when directory search finds a single exact match.
+- Do not use display names or bare localparts (example: `"Alice"` or `"alice"`). They are ambiguous and are ignored for allowlist matching. Use full `@user:server` IDs.
## Rooms (groups)
diff --git a/docs/channels/mattermost.md b/docs/channels/mattermost.md
index f4353180e2af1..fa0d9393e0f7d 100644
--- a/docs/channels/mattermost.md
+++ b/docs/channels/mattermost.md
@@ -114,6 +114,26 @@ Use these target formats with `openclaw message send` or cron/webhooks:
Bare IDs are treated as channels.
+## Reactions (message tool)
+
+- Use `message action=react` with `channel=mattermost`.
+- `messageId` is the Mattermost post id.
+- `emoji` accepts names like `thumbsup` or `:+1:` (colons are optional).
+- Set `remove=true` (boolean) to remove a reaction.
+- Reaction add/remove events are forwarded as system events to the routed agent session.
+
+Examples:
+
+```
+message action=react channel=mattermost target=channel: messageId= emoji=thumbsup
+message action=react channel=mattermost target=channel: messageId= emoji=thumbsup remove=true
+```
+
+Config:
+
+- `channels.mattermost.actions.reactions`: enable/disable reaction actions (default true).
+- Per-account override: `channels.mattermost.accounts..actions.reactions`.
+
## Multi-account
Mattermost supports multiple accounts under `channels.mattermost.accounts`:
diff --git a/docs/channels/slack.md b/docs/channels/slack.md
index 46ce2f7fe229a..9fdd3fb89a2e4 100644
--- a/docs/channels/slack.md
+++ b/docs/channels/slack.md
@@ -137,17 +137,18 @@ For actions/directory reads, user token can be preferred when configured. For wr
- `channels.slack.dm.policy` controls DM access:
+ `channels.slack.dmPolicy` controls DM access (legacy: `channels.slack.dm.policy`):
- `pairing` (default)
- `allowlist`
- - `open` (requires `dm.allowFrom` to include `"*"`)
+ - `open` (requires `channels.slack.allowFrom` to include `"*"`; legacy: `channels.slack.dm.allowFrom`)
- `disabled`
DM flags:
- `dm.enabled` (default true)
- - `dm.allowFrom`
+ - `channels.slack.allowFrom` (preferred)
+ - `dm.allowFrom` (legacy)
- `dm.groupEnabled` (group DMs default false)
- `dm.groupChannels` (optional MPIM allowlist)
@@ -200,6 +201,12 @@ For actions/directory reads, user token can be preferred when configured. For wr
- Enable native Slack command handlers with `channels.slack.commands.native: true` (or global `commands.native: true`).
- When native commands are enabled, register matching slash commands in Slack (`/` names).
- If native commands are not enabled, you can run a single configured slash command via `channels.slack.slashCommand`.
+- Native arg menus now adapt their rendering strategy:
+ - up to 5 options: button blocks
+ - 6-100 options: static select menu
+ - more than 100 options: external select with async option filtering when interactivity options handlers are available
+ - if encoded option values exceed Slack limits, the flow falls back to buttons
+- For long option payloads, Slash command argument menus use a confirm dialog before dispatching a selected value.
Default slash command settings:
@@ -283,8 +290,28 @@ Available action groups in current Slack tooling:
- Message edits/deletes/thread broadcasts are mapped into system events.
- Reaction add/remove events are mapped into system events.
- Member join/leave, channel created/renamed, and pin add/remove events are mapped into system events.
+- Assistant thread status updates (for "is typing..." indicators in threads) use `assistant.threads.setStatus` and require bot scope `assistant:write`.
- `channel_id_changed` can migrate channel config keys when `configWrites` is enabled.
- Channel topic/purpose metadata is treated as untrusted context and can be injected into routing context.
+- Block actions and modal interactions emit structured `Slack interaction: ...` system events with rich payload fields:
+ - block actions: selected values, labels, picker values, and `workflow_*` metadata
+ - modal `view_submission` and `view_closed` events with routed channel metadata and form inputs
+
+## Ack reactions
+
+`ackReaction` sends an acknowledgement emoji while OpenClaw is processing an inbound message.
+
+Resolution order:
+
+- `channels.slack.accounts..ackReaction`
+- `channels.slack.ackReaction`
+- `messages.ackReaction`
+- agent identity emoji fallback (`agents.list[].identity.emoji`, else "👀")
+
+Notes:
+
+- Slack expects shortcodes (for example `"eyes"`).
+- Use `""` to disable the reaction for a channel or account.
## Manifest and scope checklist
@@ -325,6 +352,7 @@ Available action groups in current Slack tooling:
"mpim:history",
"users:read",
"app_mentions:read",
+ "assistant:write",
"reactions:read",
"reactions:write",
"pins:read",
@@ -399,7 +427,7 @@ openclaw doctor
Check:
- `channels.slack.dm.enabled`
- - `channels.slack.dm.policy`
+ - `channels.slack.dmPolicy` (or legacy `channels.slack.dm.policy`)
- pairing approvals / allowlist entries
```bash
@@ -433,20 +461,45 @@ openclaw pairing list slack
+## Text streaming
+
+OpenClaw supports Slack native text streaming via the Agents and AI Apps API.
+
+By default, streaming is enabled. Disable it per account:
+
+```yaml
+channels:
+ slack:
+ streaming: false
+```
+
+### Requirements
+
+1. Enable **Agents and AI Apps** in your Slack app settings.
+2. Ensure the app has the `assistant:write` scope.
+3. A reply thread must be available for that message. Thread selection still follows `replyToMode`.
+
+### Behavior
+
+- First text chunk starts a stream (`chat.startStream`).
+- Later text chunks append to the same stream (`chat.appendStream`).
+- End of reply finalizes stream (`chat.stopStream`).
+- Media and non-text payloads fall back to normal delivery.
+- If streaming fails mid-reply, OpenClaw falls back to normal delivery for remaining payloads.
+
## Configuration reference pointers
Primary reference:
- [Configuration reference - Slack](/gateway/configuration-reference#slack)
-High-signal Slack fields:
-
-- mode/auth: `mode`, `botToken`, `appToken`, `signingSecret`, `webhookPath`, `accounts.*`
-- DM access: `dm.enabled`, `dm.policy`, `dm.allowFrom`, `dm.groupEnabled`, `dm.groupChannels`
-- channel access: `groupPolicy`, `channels.*`, `channels.*.users`, `channels.*.requireMention`
-- threading/history: `replyToMode`, `replyToModeByChatType`, `thread.*`, `historyLimit`, `dmHistoryLimit`, `dms.*.historyLimit`
-- delivery: `textChunkLimit`, `chunkMode`, `mediaMaxMb`
-- ops/features: `configWrites`, `commands.native`, `slashCommand.*`, `actions.*`, `userToken`, `userTokenReadOnly`
+ High-signal Slack fields:
+ - mode/auth: `mode`, `botToken`, `appToken`, `signingSecret`, `webhookPath`, `accounts.*`
+ - DM access: `dm.enabled`, `dmPolicy`, `allowFrom` (legacy: `dm.policy`, `dm.allowFrom`), `dm.groupEnabled`, `dm.groupChannels`
+ - channel access: `groupPolicy`, `channels.*`, `channels.*.users`, `channels.*.requireMention`
+ - threading/history: `replyToMode`, `replyToModeByChatType`, `thread.*`, `historyLimit`, `dmHistoryLimit`, `dms.*.historyLimit`
+ - delivery: `textChunkLimit`, `chunkMode`, `mediaMaxMb`
+ - ops/features: `configWrites`, `commands.native`, `slashCommand.*`, `actions.*`, `userToken`, `userTokenReadOnly`
## Related
diff --git a/docs/channels/telegram.md b/docs/channels/telegram.md
index 630bf5f4b0da1..7e1d95d2febb9 100644
--- a/docs/channels/telegram.md
+++ b/docs/channels/telegram.md
@@ -221,23 +221,20 @@ curl "https://api.telegram.org/bot/getUpdates"
## Feature reference
-
- OpenClaw can stream partial replies with Telegram draft bubbles (`sendMessageDraft`).
+
+ OpenClaw can stream partial replies by sending a temporary Telegram message and editing it as text arrives.
- Requirements:
+ Requirement:
- `channels.telegram.streamMode` is not `"off"` (default: `"partial"`)
- - private chat
- - inbound update includes `message_thread_id`
- - bot topics are enabled (`getMe().has_topics_enabled`)
Modes:
- - `off`: no draft streaming
- - `partial`: frequent draft updates from partial text
- - `block`: chunked draft updates using `channels.telegram.draftChunk`
+ - `off`: no live preview
+ - `partial`: frequent preview updates from partial text
+ - `block`: chunked preview updates using `channels.telegram.draftChunk`
- `draftChunk` defaults for block mode:
+ `draftChunk` defaults for `streamMode: "block"`:
- `minChars: 200`
- `maxChars: 800`
@@ -245,13 +242,17 @@ curl "https://api.telegram.org/bot/getUpdates"
`maxChars` is clamped by `channels.telegram.textChunkLimit`.
- Draft streaming is DM-only; groups/channels do not use draft bubbles.
+ This works in direct chats and groups/topics.
- If you want early real Telegram messages instead of draft updates, use block streaming (`channels.telegram.blockStreaming: true`).
+ For text-only replies, OpenClaw keeps the same preview message and performs a final edit in place (no second message).
+
+ For complex replies (for example media payloads), OpenClaw falls back to normal final delivery and then cleans up the preview message.
+
+ `streamMode` is separate from block streaming. When block streaming is explicitly enabled for Telegram, OpenClaw skips the preview stream to avoid double-streaming.
Telegram-only reasoning stream:
- - `/reasoning stream` sends reasoning to the draft bubble while generating
+ - `/reasoning stream` sends reasoning to the live preview while generating
- final answer is sent without reasoning text
@@ -570,6 +571,23 @@ curl "https://api.telegram.org/bot/getUpdates"
+
+ `ackReaction` sends an acknowledgement emoji while OpenClaw is processing an inbound message.
+
+ Resolution order:
+
+ - `channels.telegram.accounts..ackReaction`
+ - `channels.telegram.ackReaction`
+ - `messages.ackReaction`
+ - agent identity emoji fallback (`agents.list[].identity.emoji`, else "👀")
+
+ Notes:
+
+ - Telegram expects unicode emoji (for example "👀").
+ - Use `""` to disable the reaction for a channel or account.
+
+
+
Channel config writes are enabled by default (`configWrites !== false`).
@@ -703,7 +721,7 @@ Primary reference:
- `channels.telegram.textChunkLimit`: outbound chunk size (chars).
- `channels.telegram.chunkMode`: `length` (default) or `newline` to split on blank lines (paragraph boundaries) before length chunking.
- `channels.telegram.linkPreview`: toggle link previews for outbound messages (default: true).
-- `channels.telegram.streamMode`: `off | partial | block` (draft streaming).
+- `channels.telegram.streamMode`: `off | partial | block` (live stream preview).
- `channels.telegram.mediaMaxMb`: inbound/outbound media cap (MB).
- `channels.telegram.retry`: retry policy for outbound Telegram API calls (attempts, minDelayMs, maxDelayMs, jitter).
- `channels.telegram.network.autoSelectFamily`: override Node autoSelectFamily (true=enable, false=disable). Defaults to disabled on Node 22 to avoid Happy Eyeballs timeouts.
@@ -727,7 +745,7 @@ Telegram-specific high-signal fields:
- access control: `dmPolicy`, `allowFrom`, `groupPolicy`, `groupAllowFrom`, `groups`, `groups.*.topics.*`
- command/menu: `commands.native`, `customCommands`
- threading/replies: `replyToMode`
-- streaming: `streamMode`, `draftChunk`, `blockStreaming`
+- streaming: `streamMode` (preview), `draftChunk`, `blockStreaming`
- formatting/delivery: `textChunkLimit`, `chunkMode`, `linkPreview`, `responsePrefix`
- media/network: `mediaMaxMb`, `timeoutSeconds`, `retry`, `network.autoSelectFamily`, `proxy`
- webhook: `webhookUrl`, `webhookSecret`, `webhookPath`, `webhookHost`
@@ -739,4 +757,5 @@ Telegram-specific high-signal fields:
- [Pairing](/channels/pairing)
- [Channel routing](/channels/channel-routing)
+- [Multi-agent routing](/concepts/multi-agent)
- [Troubleshooting](/channels/troubleshooting)
diff --git a/docs/channels/whatsapp.md b/docs/channels/whatsapp.md
index 23bbb38f747cf..a6fb427bdc2d5 100644
--- a/docs/channels/whatsapp.md
+++ b/docs/channels/whatsapp.md
@@ -144,6 +144,8 @@ OpenClaw recommends running WhatsApp on a separate number when possible. (The ch
`allowFrom` accepts E.164-style numbers (normalized internally).
+ Multi-account override: `channels.whatsapp.accounts..dmPolicy` (and `allowFrom`) take precedence over channel-level defaults for that account.
+
Runtime behavior details:
- pairings are persisted in channel allow-store and merged with configured `allowFrom`
@@ -167,6 +169,7 @@ OpenClaw recommends running WhatsApp on a separate number when possible. (The ch
Sender allowlist fallback:
- if `groupAllowFrom` is unset, runtime falls back to `allowFrom` when available
+ - sender allowlists are evaluated before mention/reply activation
Note: if no `channels.whatsapp` block exists at all, runtime group-policy fallback is effectively `open`.
@@ -181,6 +184,11 @@ OpenClaw recommends running WhatsApp on a separate number when possible. (The ch
- configured mention regex patterns (`agents.list[].groupChat.mentionPatterns`, fallback `messages.groupChat.mentionPatterns`)
- implicit reply-to-bot detection (reply sender matches bot identity)
+ Security note:
+
+ - quote/reply only satisfies mention gating; it does **not** grant sender authorization
+ - with `groupPolicy: "allowlist"`, non-allowlisted senders are still blocked even if they reply to an allowlisted user's message
+
Session-level activation command:
- `/activation mention`
@@ -405,6 +413,7 @@ Behavior notes:
- `groupAllowFrom` / `allowFrom`
- `groups` allowlist entries
- mention gating (`requireMention` + mention patterns)
+ - duplicate keys in `openclaw.json` (JSON5): later entries override earlier ones, so keep a single `groupPolicy` per scope
@@ -431,4 +440,5 @@ High-signal WhatsApp fields:
- [Pairing](/channels/pairing)
- [Channel routing](/channels/channel-routing)
+- [Multi-agent routing](/concepts/multi-agent)
- [Troubleshooting](/channels/troubleshooting)
diff --git a/docs/channels/zalo.md b/docs/channels/zalo.md
index c595c5e6dde83..cda126f564913 100644
--- a/docs/channels/zalo.md
+++ b/docs/channels/zalo.md
@@ -115,6 +115,9 @@ Multi-account support: use `channels.zalo.accounts` with per-account tokens and
- Webhook URL must use HTTPS.
- Zalo sends events with `X-Bot-Api-Secret-Token` header for verification.
- Gateway HTTP handles webhook requests at `channels.zalo.webhookPath` (defaults to the webhook URL path).
+ - Requests must use `Content-Type: application/json` (or `+json` media types).
+ - Duplicate events (`event_name + message_id`) are ignored for a short replay window.
+ - Burst traffic is rate-limited per path/source and may return HTTP 429.
**Note:** getUpdates (polling) and webhook are mutually exclusive per Zalo API docs.
diff --git a/docs/ci.md b/docs/ci.md
index cdf5b126a2889..64d4df0ec1c47 100644
--- a/docs/ci.md
+++ b/docs/ci.md
@@ -34,12 +34,11 @@ Jobs are ordered so cheap checks fail before expensive ones run:
## Runners
-| Runner | Jobs |
-| ------------------------------- | ----------------------------- |
-| `blacksmith-4vcpu-ubuntu-2404` | Most Linux jobs |
-| `blacksmith-4vcpu-windows-2025` | `checks-windows` |
-| `macos-latest` | `macos`, `ios` |
-| `ubuntu-latest` | Scope detection (lightweight) |
+| Runner | Jobs |
+| -------------------------------- | ------------------------------------------ |
+| `blacksmith-16vcpu-ubuntu-2404` | Most Linux jobs, including scope detection |
+| `blacksmith-16vcpu-windows-2025` | `checks-windows` |
+| `macos-latest` | `macos`, `ios` |
## Local Equivalents
diff --git a/docs/cli/acp.md b/docs/cli/acp.md
index 46b78cce6f51d..9535509016d23 100644
--- a/docs/cli/acp.md
+++ b/docs/cli/acp.md
@@ -21,6 +21,9 @@ openclaw acp
# Remote Gateway
openclaw acp --url wss://gateway-host:18789 --token
+# Remote Gateway (token from file)
+openclaw acp --url wss://gateway-host:18789 --token-file ~/.openclaw/gateway.token
+
# Attach to an existing session key
openclaw acp --session agent:main:main
@@ -40,7 +43,7 @@ It spawns the ACP bridge and lets you type prompts interactively.
openclaw acp client
# Point the spawned bridge at a remote Gateway
-openclaw acp client --server-args --url wss://gateway-host:18789 --token
+openclaw acp client --server-args --url wss://gateway-host:18789 --token-file ~/.openclaw/gateway.token
# Override the server command (default: openclaw)
openclaw acp client --server "node" --server-args openclaw.mjs acp --url ws://127.0.0.1:19001
@@ -66,6 +69,8 @@ Example direct run (no config write):
```bash
openclaw acp --url wss://gateway-host:18789 --token
+# preferred for local process safety
+openclaw acp --url wss://gateway-host:18789 --token-file ~/.openclaw/gateway.token
```
## Selecting agents
@@ -153,7 +158,9 @@ Learn more about session keys at [/concepts/session](/concepts/session).
- `--url `: Gateway WebSocket URL (defaults to gateway.remote.url when configured).
- `--token `: Gateway auth token.
+- `--token-file `: read Gateway auth token from file.
- `--password `: Gateway auth password.
+- `--password-file `: read Gateway auth password from file.
- `--session `: default session key.
- `--session-label