Vendor OpenClaw source as Adolf fork baseline
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled

Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
This commit is contained in:
2026-07-05 09:36:54 +00:00
parent 3216769225
commit bedb527145
21108 changed files with 6010766 additions and 0 deletions

View File

@@ -0,0 +1,116 @@
{
"images": [
{
"idiom": "watch",
"role": "notificationCenter",
"subtype": "38mm",
"size": "24x24",
"scale": "2x",
"filename": "watch-notification-38@2x.png"
},
{
"idiom": "watch",
"role": "notificationCenter",
"subtype": "42mm",
"size": "27.5x27.5",
"scale": "2x",
"filename": "watch-notification-42@2x.png"
},
{
"idiom": "watch",
"role": "companionSettings",
"size": "29x29",
"scale": "2x",
"filename": "watch-companion-29@2x.png"
},
{
"idiom": "watch",
"role": "companionSettings",
"size": "29x29",
"scale": "3x",
"filename": "watch-companion-29@3x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "38mm",
"size": "40x40",
"scale": "2x",
"filename": "watch-app-38@2x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "40mm",
"size": "44x44",
"scale": "2x",
"filename": "watch-app-40@2x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "41mm",
"size": "46x46",
"scale": "2x",
"filename": "watch-app-41@2x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "44mm",
"size": "50x50",
"scale": "2x",
"filename": "watch-app-44@2x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "45mm",
"size": "51x51",
"scale": "2x",
"filename": "watch-app-45@2x.png"
},
{
"idiom": "watch",
"role": "quickLook",
"subtype": "38mm",
"size": "86x86",
"scale": "2x",
"filename": "watch-quicklook-38@2x.png"
},
{
"idiom": "watch",
"role": "quickLook",
"subtype": "42mm",
"size": "98x98",
"scale": "2x",
"filename": "watch-quicklook-42@2x.png"
},
{
"idiom": "watch",
"role": "quickLook",
"subtype": "44mm",
"size": "108x108",
"scale": "2x",
"filename": "watch-quicklook-44@2x.png"
},
{
"idiom": "watch",
"role": "quickLook",
"subtype": "45mm",
"size": "117x117",
"scale": "2x",
"filename": "watch-quicklook-45@2x.png"
},
{
"idiom": "watch-marketing",
"size": "1024x1024",
"scale": "1x",
"filename": "watch-marketing-1024.png"
}
],
"info": {
"version": 1,
"author": "xcode"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 504 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

View File

@@ -0,0 +1,116 @@
{
"images": [
{
"idiom": "watch",
"role": "notificationCenter",
"subtype": "38mm",
"size": "24x24",
"scale": "2x",
"filename": "watch-notification-38@2x.png"
},
{
"idiom": "watch",
"role": "notificationCenter",
"subtype": "42mm",
"size": "27.5x27.5",
"scale": "2x",
"filename": "watch-notification-42@2x.png"
},
{
"idiom": "watch",
"role": "companionSettings",
"size": "29x29",
"scale": "2x",
"filename": "watch-companion-29@2x.png"
},
{
"idiom": "watch",
"role": "companionSettings",
"size": "29x29",
"scale": "3x",
"filename": "watch-companion-29@3x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "38mm",
"size": "40x40",
"scale": "2x",
"filename": "watch-app-38@2x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "40mm",
"size": "44x44",
"scale": "2x",
"filename": "watch-app-40@2x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "41mm",
"size": "46x46",
"scale": "2x",
"filename": "watch-app-41@2x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "44mm",
"size": "50x50",
"scale": "2x",
"filename": "watch-app-44@2x.png"
},
{
"idiom": "watch",
"role": "appLauncher",
"subtype": "45mm",
"size": "51x51",
"scale": "2x",
"filename": "watch-app-45@2x.png"
},
{
"idiom": "watch",
"role": "quickLook",
"subtype": "38mm",
"size": "86x86",
"scale": "2x",
"filename": "watch-quicklook-38@2x.png"
},
{
"idiom": "watch",
"role": "quickLook",
"subtype": "42mm",
"size": "98x98",
"scale": "2x",
"filename": "watch-quicklook-42@2x.png"
},
{
"idiom": "watch",
"role": "quickLook",
"subtype": "44mm",
"size": "108x108",
"scale": "2x",
"filename": "watch-quicklook-44@2x.png"
},
{
"idiom": "watch",
"role": "quickLook",
"subtype": "45mm",
"size": "117x117",
"scale": "2x",
"filename": "watch-quicklook-45@2x.png"
},
{
"idiom": "watch-marketing",
"size": "1024x1024",
"scale": "1x",
"filename": "watch-marketing-1024.png"
}
],
"info": {
"version": 1,
"author": "xcode"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

View File

@@ -0,0 +1,6 @@
{
"info": {
"version": 1,
"author": "xcode"
}
}

View File

@@ -0,0 +1,12 @@
{
"images": [
{
"filename": "openclaw-icon.png",
"idiom": "universal"
}
],
"info": {
"author": "xcode",
"version": 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>OpenClaw</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(OPENCLAW_MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(OPENCLAW_BUILD_VERSION)</string>
<key>UIAppFonts</key>
<array>
<string>RedHatDisplay[wght].ttf</string>
<string>Inter[opsz,wght].ttf</string>
<string>Inter-Italic[opsz,wght].ttf</string>
<string>JetBrainsMono-Regular.ttf</string>
<string>JetBrainsMono-Medium.ttf</string>
<string>JetBrainsMono-SemiBold.ttf</string>
</array>
<key>WKApplication</key>
<true/>
<key>WKCompanionAppBundleIdentifier</key>
<string>$(OPENCLAW_COMPANION_APP_BUNDLE_ID)</string>
</dict>
</plist>

View File

@@ -0,0 +1,183 @@
import SwiftUI
@main
struct OpenClawWatchApp: App {
@Environment(\.scenePhase) private var scenePhase
@State private var inboxStore = WatchInboxStore(
requestNotificationAuthorization: !OpenClawWatchApp.isScreenshotMode)
@State private var receiver: WatchConnectivityReceiver?
@State private var execApprovalRefreshTask: Task<Void, Never>?
private static let screenshotModeDefaultsKey = "openclaw.watch.screenshotMode"
private static let isScreenshotMode = ProcessInfo.processInfo.arguments.contains(
"--openclaw-watch-screenshot-mode")
|| ProcessInfo.processInfo.environment["OPENCLAW_WATCH_SCREENSHOT_MODE"] == "1"
|| UserDefaults.standard.bool(forKey: OpenClawWatchApp.screenshotModeDefaultsKey)
var body: some Scene {
WindowGroup {
WatchInboxView(
store: self.inboxStore,
onAction: { action in
guard let receiver = self.receiver else { return }
let draft = self.inboxStore.makeReplyDraft(action: action)
self.inboxStore.markReplySending(actionLabel: action.label)
Task { @MainActor in
let result = await receiver.sendReply(draft)
self.inboxStore.markReplyResult(result, actionLabel: action.label)
}
},
onExecApprovalDecision: { approvalId, decision in
guard let receiver = self.receiver else { return }
self.inboxStore.markExecApprovalSending(approvalId: approvalId, decision: decision)
Task { @MainActor in
let result = await receiver.sendExecApprovalResolve(
approvalId: approvalId,
decision: decision)
self.inboxStore.markExecApprovalSendResult(
approvalId: approvalId,
decision: decision,
result: result)
}
},
onRefreshExecApprovalReview: {
self.refreshExecApprovalReview(force: true)
},
onRefreshAppSnapshot: {
self.refreshAppSnapshot()
},
onAppCommand: { command in
self.sendAppCommand(command)
},
onSendChatMessage: { text in
self.sendChatMessage(text)
})
.task {
if OpenClawWatchApp.isScreenshotMode {
self.inboxStore.configureScreenshotFixture()
return
}
if self.receiver == nil {
let receiver = WatchConnectivityReceiver(store: self.inboxStore)
receiver.activate()
self.receiver = receiver
}
self.refreshAppSnapshot()
self.refreshExecApprovalReview()
}
.onChange(of: self.scenePhase) { _, newPhase in
guard newPhase == .active else { return }
self.refreshAppSnapshot()
self.refreshExecApprovalReview()
}
}
}
private func refreshAppSnapshot() {
guard let receiver else { return }
self.inboxStore.markAppSnapshotRequestStarted()
Task { @MainActor in
let result = await receiver.requestAppSnapshot()
self.inboxStore.markAppSnapshotRequestResult(result)
}
}
private func sendAppCommand(_ command: WatchAppCommand) {
guard let receiver else { return }
let message = self.inboxStore.makeAppCommand(command)
self.inboxStore.markAppCommandSending(command)
Task { @MainActor in
let result = await receiver.sendAppCommand(message)
self.inboxStore.markAppCommandResult(result, command: command)
}
}
private func sendChatMessage(_ text: String) {
guard let receiver else { return }
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
guard self.inboxStore.hasGatewayTaggedAppSnapshot else {
self.inboxStore.markAppCommandBlocked(.sendChat, reason: "refreshing iPhone state")
self.refreshAppSnapshot()
return
}
let message = self.inboxStore.makeAppCommand(.sendChat, text: trimmed)
self.inboxStore.markAppCommandSending(.sendChat)
Task { @MainActor in
let result = await receiver.sendAppCommand(message)
self.inboxStore.markAppCommandResult(result, command: .sendChat)
try? await Task.sleep(nanoseconds: 900_000_000)
self.refreshAppSnapshot()
}
}
private func refreshExecApprovalReview(force: Bool = false) {
guard let receiver else { return }
guard force || self.inboxStore.shouldAutoRequestExecApprovalSnapshot else { return }
self.execApprovalRefreshTask?.cancel()
self.execApprovalRefreshTask = Task { @MainActor in
self.inboxStore.beginExecApprovalReviewLoading()
for attempt in 0..<5 {
if Task.isCancelled { return }
await receiver.requestExecApprovalSnapshot()
if !self.inboxStore.execApprovals.isEmpty
|| self.inboxStore.hasCompletedExecApprovalSnapshotRefresh
{
self.inboxStore.markExecApprovalReviewLoaded()
return
}
if attempt < 4 {
try? await Task.sleep(nanoseconds: 700_000_000)
}
}
if self.inboxStore.execApprovals.isEmpty {
self.inboxStore.markExecApprovalReviewUnavailable(
"Couldn't load approval from your iPhone yet.")
}
}
}
}
@MainActor
extension WatchInboxStore {
fileprivate func configureScreenshotFixture() {
let sentAtMs = Int(Date().timeIntervalSince1970 * 1000)
self.greetingTextOverride = "Good morning"
self.consume(
execApprovalSnapshot: WatchExecApprovalSnapshotMessage(
approvals: [],
sentAtMs: sentAtMs,
snapshotId: nil),
transport: "screenshot")
self.consume(
appSnapshot: WatchAppSnapshotMessage(
gatewayStatusText: "Connected",
gatewayConnected: true,
agentName: "Molty",
agentAvatarURL: nil,
agentAvatarText: "M",
sessionKey: "watch-screenshot-session",
gatewayStableID: "watch-screenshot-gateway",
talkStatusText: "Ready",
talkEnabled: true,
talkListening: false,
talkSpeaking: false,
pendingApprovalCount: 0,
chatItems: [
WatchChatItem(
id: "watch-screenshot-user-chat",
role: "user",
text: "What's on deck?",
timestampMs: sentAtMs - 90000),
WatchChatItem(
id: "watch-screenshot-molty-chat",
role: "assistant",
text: "Gateway is online and ready.",
timestampMs: sentAtMs - 30000),
],
chatStatusText: "Live gateway conversation",
sentAtMs: sentAtMs,
snapshotId: "watch-screenshot-now-face"))
}
}

View File

@@ -0,0 +1,43 @@
import SwiftUI
enum WatchClawType {
static func avatar(size: CGFloat) -> Font {
self.body(size: size, weight: .bold, relativeTo: .caption)
}
static func label(size: CGFloat = 10, weight: Font.Weight = .bold) -> Font {
self.body(size: size, weight: weight, relativeTo: .caption2)
}
static func title(size: CGFloat, weight: Font.Weight = .semibold) -> Font {
self.display(size: size, weight: weight, relativeTo: .headline)
}
static func body(
size: CGFloat,
weight: Font.Weight = .regular,
relativeTo textStyle: Font.TextStyle = .body) -> Font
{
.custom("Inter-Regular", size: size, relativeTo: textStyle).weight(weight)
}
static func symbol(size: CGFloat, weight: Font.Weight) -> Font {
.system(size: size, weight: weight)
}
static var captionSemiBold: Font {
body(size: 12, weight: .semibold, relativeTo: .caption)
}
static var captionBold: Font {
body(size: 12, weight: .bold, relativeTo: .caption)
}
static var caption2: Font {
body(size: 11, relativeTo: .caption2)
}
private static func display(size: CGFloat, weight: Font.Weight, relativeTo textStyle: Font.TextStyle) -> Font {
.custom("RedHatDisplay-Regular", size: size, relativeTo: textStyle).weight(weight)
}
}

View File

@@ -0,0 +1,613 @@
import Foundation
import WatchConnectivity
struct WatchReplyDraft {
var replyId: String
var promptId: String
var actionId: String
var actionLabel: String?
var sessionKey: String?
var note: String?
var sentAtMs: Int
}
struct WatchReplySendResult: Equatable {
var deliveredImmediately: Bool
var queuedForDelivery: Bool
var transport: String
var errorMessage: String?
}
final class WatchConnectivityReceiver: NSObject, @unchecked Sendable {
private typealias MessageSendContinuation = CheckedContinuation<Void, Error>
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 else { return }
session.delegate = self
session.activate()
}
private func ensureActivated() async {
guard let 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)
}
}
func requestExecApprovalSnapshot() async {
await self.ensureActivated()
guard let session else { return }
let request = WatchExecApprovalSnapshotRequestMessage(
requestId: UUID().uuidString,
sentAtMs: Self.nowMs())
let payload = Self.encodeSnapshotRequestPayload(request)
if session.isReachable {
do {
try await Self.sendMessage(payload, through: session)
return
} catch {
// Fall through to queued delivery.
}
}
_ = session.transferUserInfo(payload)
}
func requestAppSnapshot() async -> WatchReplySendResult {
await self.ensureActivated()
guard let session else {
return WatchReplySendResult(
deliveredImmediately: false,
queuedForDelivery: false,
transport: "none",
errorMessage: "watch session unavailable")
}
let request = WatchAppSnapshotRequestMessage(
requestId: UUID().uuidString,
sentAtMs: Self.nowMs())
let payload = Self.encodeAppSnapshotRequestPayload(request)
return await self.sendPayload(payload, session: session)
}
func sendReply(_ draft: WatchReplyDraft) async -> WatchReplySendResult {
await self.ensureActivated()
guard let session else {
return WatchReplySendResult(
deliveredImmediately: false,
queuedForDelivery: false,
transport: "none",
errorMessage: "watch session unavailable")
}
var payload: [String: Any] = [
"type": WatchPayloadType.reply.rawValue,
"replyId": draft.replyId,
"promptId": draft.promptId,
"actionId": draft.actionId,
"sentAtMs": draft.sentAtMs,
]
if let actionLabel = draft.actionLabel?.trimmingCharacters(in: .whitespacesAndNewlines),
!actionLabel.isEmpty
{
payload["actionLabel"] = actionLabel
}
if let sessionKey = draft.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines),
!sessionKey.isEmpty
{
payload["sessionKey"] = sessionKey
}
if let note = draft.note?.trimmingCharacters(in: .whitespacesAndNewlines), !note.isEmpty {
payload["note"] = note
}
return await self.sendPayload(payload, session: session)
}
func sendExecApprovalResolve(
approvalId: String,
decision: WatchExecApprovalDecision) async -> WatchReplySendResult
{
await self.ensureActivated()
guard let session else {
return WatchReplySendResult(
deliveredImmediately: false,
queuedForDelivery: false,
transport: "none",
errorMessage: "watch session unavailable")
}
let payload = Self.encodeExecApprovalResolvePayload(
WatchExecApprovalResolveMessage(
approvalId: approvalId,
decision: decision,
replyId: UUID().uuidString,
sentAtMs: Self.nowMs()))
return await self.sendPayload(payload, session: session)
}
func sendAppCommand(_ message: WatchAppCommandMessage) async -> WatchReplySendResult {
await self.ensureActivated()
guard let session else {
return WatchReplySendResult(
deliveredImmediately: false,
queuedForDelivery: false,
transport: "none",
errorMessage: "watch session unavailable")
}
return await self.sendPayload(Self.encodeAppCommandPayload(message), session: session)
}
private func sendPayload(_ payload: [String: Any], session: WCSession) async -> WatchReplySendResult {
if session.isReachable {
do {
try await Self.sendMessage(payload, through: session)
return WatchReplySendResult(
deliveredImmediately: true,
queuedForDelivery: false,
transport: "sendMessage",
errorMessage: nil)
} catch {
// Fall through to queued delivery below.
}
}
_ = session.transferUserInfo(payload)
return WatchReplySendResult(
deliveredImmediately: false,
queuedForDelivery: true,
transport: "transferUserInfo",
errorMessage: nil)
}
private static func sendMessage(_ payload: [String: Any], through session: WCSession) async throws {
try await withCheckedThrowingContinuation(isolation: nil) { (continuation: MessageSendContinuation) in
session.sendMessage(
payload,
replyHandler: { _ in continuation.resume(returning: ()) },
errorHandler: { error in continuation.resume(throwing: error) })
}
}
private static func nowMs() -> Int {
Int(Date().timeIntervalSince1970 * 1000)
}
private static func normalizeObject(_ value: Any) -> [String: Any]? {
if let object = value as? [String: Any] {
return object
}
if let object = value as? [AnyHashable: Any] {
var normalized: [String: Any] = [:]
normalized.reserveCapacity(object.count)
for (key, item) in object {
guard let stringKey = key as? String else {
continue
}
normalized[stringKey] = item
}
return normalized
}
return nil
}
private static func parseActions(_ value: Any?) -> [WatchPromptAction] {
guard let raw = value as? [Any] else {
return []
}
return raw.compactMap { item in
guard let obj = Self.normalizeObject(item) else {
return nil
}
let id = (obj["id"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let label = (obj["label"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !id.isEmpty, !label.isEmpty else {
return nil
}
let style = (obj["style"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
return WatchPromptAction(id: id, label: label, style: style)
}
}
private static func parseNotificationPayload(_ payload: [String: Any]) -> WatchNotifyMessage? {
guard let type = payload["type"] as? String,
type == WatchPayloadType.notify.rawValue
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
let promptId = (payload["promptId"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let sessionKey = (payload["sessionKey"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let kind = (payload["kind"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let details = (payload["details"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let expiresAtMs = (payload["expiresAtMs"] as? Int) ?? (payload["expiresAtMs"] as? NSNumber)?.intValue
let risk = (payload["risk"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let actions = Self.parseActions(payload["actions"])
return WatchNotifyMessage(
id: id,
title: title,
body: body,
sentAtMs: sentAtMs,
promptId: promptId,
sessionKey: sessionKey,
kind: kind,
details: details,
expiresAtMs: expiresAtMs,
risk: risk,
actions: actions)
}
private static func parseExecApprovalDecision(_ value: Any?) -> WatchExecApprovalDecision? {
let raw = (value as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return WatchExecApprovalDecision(rawValue: raw)
}
private static func parseExecApprovalItem(_ value: Any?) -> WatchExecApprovalItem? {
guard let payload = value.flatMap(normalizeObject) else {
return nil
}
let id = (payload["id"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let commandText = (payload["commandText"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !id.isEmpty, !commandText.isEmpty else {
return nil
}
let commandPreview = (payload["commandPreview"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let host = (payload["host"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
let nodeId = (payload["nodeId"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
let agentId = (payload["agentId"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
let expiresAtMs = (payload["expiresAtMs"] as? Int) ?? (payload["expiresAtMs"] as? NSNumber)?.intValue
let riskRaw = (payload["risk"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let risk = WatchRiskLevel(rawValue: riskRaw)
let allowedDecisions = (payload["allowedDecisions"] as? [Any] ?? []).compactMap {
Self.parseExecApprovalDecision($0)
}
return WatchExecApprovalItem(
id: id,
commandText: commandText,
commandPreview: commandPreview,
host: host,
nodeId: nodeId,
agentId: agentId,
expiresAtMs: expiresAtMs,
allowedDecisions: allowedDecisions,
risk: risk)
}
private static func parseExecApprovalPromptPayload(
_ payload: [String: Any]) -> WatchExecApprovalPromptMessage?
{
guard let type = payload["type"] as? String,
type == WatchPayloadType.execApprovalPrompt.rawValue,
let approval = parseExecApprovalItem(payload["approval"])
else {
return nil
}
let sentAtMs = (payload["sentAtMs"] as? Int) ?? (payload["sentAtMs"] as? NSNumber)?.intValue
let deliveryId = (payload["deliveryId"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
let resetResolvingState = payload["resetResolvingState"] as? Bool
return WatchExecApprovalPromptMessage(
approval: approval,
sentAtMs: sentAtMs,
deliveryId: deliveryId,
resetResolvingState: resetResolvingState)
}
private static func parseExecApprovalResolvedPayload(
_ payload: [String: Any]) -> WatchExecApprovalResolvedMessage?
{
guard let type = payload["type"] as? String,
type == WatchPayloadType.execApprovalResolved.rawValue
else {
return nil
}
let approvalId = (payload["approvalId"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !approvalId.isEmpty else { return nil }
let decision = Self.parseExecApprovalDecision(payload["decision"])
let resolvedAtMs = (payload["resolvedAtMs"] as? Int)
?? (payload["resolvedAtMs"] as? NSNumber)?.intValue
let source = (payload["source"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
return WatchExecApprovalResolvedMessage(
approvalId: approvalId,
decision: decision,
resolvedAtMs: resolvedAtMs,
source: source)
}
private static func parseExecApprovalExpiredPayload(
_ payload: [String: Any]) -> WatchExecApprovalExpiredMessage?
{
guard let type = payload["type"] as? String,
type == WatchPayloadType.execApprovalExpired.rawValue
else {
return nil
}
let approvalId = (payload["approvalId"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let rawReason = (payload["reason"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !approvalId.isEmpty,
let reason = WatchExecApprovalCloseReason(rawValue: rawReason)
else {
return nil
}
let expiredAtMs = (payload["expiredAtMs"] as? Int) ?? (payload["expiredAtMs"] as? NSNumber)?.intValue
return WatchExecApprovalExpiredMessage(
approvalId: approvalId,
reason: reason,
expiredAtMs: expiredAtMs)
}
private static func parseExecApprovalSnapshotPayload(
_ payload: [String: Any]) -> WatchExecApprovalSnapshotMessage?
{
guard let type = payload["type"] as? String,
type == WatchPayloadType.execApprovalSnapshot.rawValue
else {
return nil
}
let approvals = (payload["approvals"] as? [Any] ?? []).compactMap { item in
Self.parseExecApprovalItem(item)
}
let sentAtMs = (payload["sentAtMs"] as? Int) ?? (payload["sentAtMs"] as? NSNumber)?.intValue
let snapshotId = (payload["snapshotId"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
return WatchExecApprovalSnapshotMessage(
approvals: approvals,
sentAtMs: sentAtMs,
snapshotId: snapshotId)
}
private static func parseAppSnapshotPayload(_ payload: [String: Any]) -> WatchAppSnapshotMessage? {
guard let type = payload["type"] as? String,
type == WatchPayloadType.appSnapshot.rawValue
else {
return nil
}
let gatewayStatusText = (payload["gatewayStatusText"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let agentName = (payload["agentName"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let agentAvatarURL = (payload["agentAvatarUrl"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let agentAvatarText = (payload["agentAvatarText"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let sessionKey = (payload["sessionKey"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let gatewayStableID = (payload["gatewayStableID"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let talkStatusText = (payload["talkStatusText"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let pendingApprovalCount = (payload["pendingApprovalCount"] as? Int)
?? (payload["pendingApprovalCount"] as? NSNumber)?.intValue
?? 0
let sentAtMs = (payload["sentAtMs"] as? Int) ?? (payload["sentAtMs"] as? NSNumber)?.intValue
let snapshotId = (payload["snapshotId"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
let chatItems = (payload["chatItems"] as? [Any])?.compactMap(Self.parseChatItem)
let chatStatusText = (payload["chatStatusText"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
return WatchAppSnapshotMessage(
gatewayStatusText: gatewayStatusText.isEmpty ? "Unknown" : gatewayStatusText,
gatewayConnected: Self.boolValue(payload["gatewayConnected"]),
agentName: agentName.isEmpty ? "Main" : agentName,
agentAvatarURL: agentAvatarURL?.isEmpty == false ? agentAvatarURL : nil,
agentAvatarText: agentAvatarText?.isEmpty == false ? agentAvatarText : nil,
sessionKey: sessionKey.isEmpty ? "main" : sessionKey,
gatewayStableID: gatewayStableID?.isEmpty == false ? gatewayStableID : nil,
talkStatusText: talkStatusText.isEmpty ? "Off" : talkStatusText,
talkEnabled: Self.boolValue(payload["talkEnabled"]),
talkListening: Self.boolValue(payload["talkListening"]),
talkSpeaking: Self.boolValue(payload["talkSpeaking"]),
pendingApprovalCount: max(0, pendingApprovalCount),
chatItems: chatItems,
chatStatusText: chatStatusText?.isEmpty == false ? chatStatusText : nil,
sentAtMs: sentAtMs,
snapshotId: snapshotId)
}
private static func parseChatItem(_ item: Any) -> WatchChatItem? {
guard let dict = item as? [String: Any] else { return nil }
guard let id = (dict["id"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines),
!id.isEmpty
else {
return nil
}
let trimmedRole = (dict["role"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let text = (dict["text"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
guard let text, !text.isEmpty else { return nil }
let timestampMs = (dict["timestampMs"] as? Int) ?? (dict["timestampMs"] as? NSNumber)?.intValue
return WatchChatItem(
id: id,
role: trimmedRole.isEmpty ? "assistant" : trimmedRole,
text: text,
timestampMs: timestampMs)
}
private static func boolValue(_ value: Any?) -> Bool {
if let bool = value as? Bool {
return bool
}
if let number = value as? NSNumber {
return number.boolValue
}
return false
}
private static func encodeAppSnapshotRequestPayload(
_ request: WatchAppSnapshotRequestMessage) -> [String: Any]
{
var payload: [String: Any] = [
"type": WatchPayloadType.appSnapshotRequest.rawValue,
"requestId": request.requestId,
]
if let sentAtMs = request.sentAtMs {
payload["sentAtMs"] = sentAtMs
}
return payload
}
private static func encodeAppCommandPayload(_ message: WatchAppCommandMessage) -> [String: Any] {
var payload: [String: Any] = [
"type": WatchPayloadType.appCommand.rawValue,
"command": message.command.rawValue,
"commandId": message.commandId,
]
if let sessionKey = message.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines),
!sessionKey.isEmpty
{
payload["sessionKey"] = sessionKey
}
if let gatewayStableID = message.gatewayStableID?.trimmingCharacters(in: .whitespacesAndNewlines),
!gatewayStableID.isEmpty
{
payload["gatewayStableID"] = gatewayStableID
}
if let text = message.text?.trimmingCharacters(in: .whitespacesAndNewlines),
!text.isEmpty
{
payload["text"] = text
}
if let sentAtMs = message.sentAtMs {
payload["sentAtMs"] = sentAtMs
}
return payload
}
private static func encodeSnapshotRequestPayload(
_ request: WatchExecApprovalSnapshotRequestMessage) -> [String: Any]
{
var payload: [String: Any] = [
"type": WatchPayloadType.execApprovalSnapshotRequest.rawValue,
"requestId": request.requestId,
]
if let sentAtMs = request.sentAtMs {
payload["sentAtMs"] = sentAtMs
}
return payload
}
private static func encodeExecApprovalResolvePayload(
_ message: WatchExecApprovalResolveMessage) -> [String: Any]
{
var payload: [String: Any] = [
"type": WatchPayloadType.execApprovalResolve.rawValue,
"approvalId": message.approvalId,
"decision": message.decision.rawValue,
"replyId": message.replyId,
]
if let sentAtMs = message.sentAtMs {
payload["sentAtMs"] = sentAtMs
}
return payload
}
}
extension WatchConnectivityReceiver: WCSessionDelegate {
func session(
_ session: WCSession,
activationDidCompleteWith activationState: WCSessionActivationState,
error _: (any Error)?)
{
if activationState == .activated, !session.receivedApplicationContext.isEmpty {
self.consumeIncomingPayload(
session.receivedApplicationContext,
transport: "receivedApplicationContext")
}
Task {
await self.requestExecApprovalSnapshot()
}
}
func session(_: WCSession, didReceiveMessage message: [String: Any]) {
self.consumeIncomingPayload(message, transport: "sendMessage")
}
func session(
_: WCSession,
didReceiveMessage message: [String: Any],
replyHandler: @escaping ([String: Any]) -> Void)
{
replyHandler(["ok": true])
self.consumeIncomingPayload(message, transport: "sendMessage")
}
func session(_: WCSession, didReceiveUserInfo userInfo: [String: Any]) {
self.consumeIncomingPayload(userInfo, transport: "transferUserInfo")
}
func session(_: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
self.consumeIncomingPayload(applicationContext, transport: "applicationContext")
}
private func consumeIncomingPayload(_ payload: [String: Any], transport: String) {
if let incoming = Self.parseNotificationPayload(payload) {
Task { @MainActor in
self.store.consume(message: incoming, transport: transport)
}
return
}
if let prompt = Self.parseExecApprovalPromptPayload(payload) {
Task { @MainActor in
self.store.consume(execApprovalPrompt: prompt, transport: transport)
}
return
}
if let resolved = Self.parseExecApprovalResolvedPayload(payload) {
Task { @MainActor in
self.store.consume(execApprovalResolved: resolved)
}
return
}
if let expired = Self.parseExecApprovalExpiredPayload(payload) {
Task { @MainActor in
self.store.consume(execApprovalExpired: expired)
}
return
}
if let snapshot = Self.parseExecApprovalSnapshotPayload(payload) {
Task { @MainActor in
self.store.consume(execApprovalSnapshot: snapshot, transport: transport)
}
return
}
if let snapshot = Self.parseAppSnapshotPayload(payload) {
Task { @MainActor in
self.store.consume(appSnapshot: snapshot)
}
}
}
}

View File

@@ -0,0 +1,821 @@
import Foundation
import Observation
import UserNotifications
import WatchKit
enum WatchPayloadType: String, Codable, Equatable {
case notify = "watch.notify"
case reply = "watch.reply"
case appSnapshot = "watch.app.snapshot"
case appSnapshotRequest = "watch.app.snapshotRequest"
case appCommand = "watch.app.command"
case execApprovalPrompt = "watch.execApproval.prompt"
case execApprovalResolve = "watch.execApproval.resolve"
case execApprovalResolved = "watch.execApproval.resolved"
case execApprovalExpired = "watch.execApproval.expired"
case execApprovalSnapshot = "watch.execApproval.snapshot"
case execApprovalSnapshotRequest = "watch.execApproval.snapshotRequest"
}
enum WatchRiskLevel: String, Codable, Equatable {
case low
case medium
case high
}
enum WatchExecApprovalDecision: String, Codable, Equatable {
case allowOnce = "allow-once"
case deny
}
enum WatchExecApprovalCloseReason: String, Codable, Equatable {
case expired
case notFound = "not-found"
case unavailable
case replaced
case resolved
}
struct WatchExecApprovalItem: Codable, Equatable, Identifiable {
var id: String
var commandText: String
var commandPreview: String?
var host: String?
var nodeId: String?
var agentId: String?
var expiresAtMs: Int?
var allowedDecisions: [WatchExecApprovalDecision]
var risk: WatchRiskLevel?
}
struct WatchExecApprovalPromptMessage: Codable, Equatable {
var approval: WatchExecApprovalItem
var sentAtMs: Int?
var deliveryId: String?
var resetResolvingState: Bool?
}
struct WatchExecApprovalResolvedMessage: Codable, Equatable {
var approvalId: String
var decision: WatchExecApprovalDecision?
var resolvedAtMs: Int?
var source: String?
}
struct WatchExecApprovalExpiredMessage: Codable, Equatable {
var approvalId: String
var reason: WatchExecApprovalCloseReason
var expiredAtMs: Int?
}
struct WatchExecApprovalSnapshotMessage: Codable, Equatable {
var approvals: [WatchExecApprovalItem]
var sentAtMs: Int?
var snapshotId: String?
}
struct WatchExecApprovalSnapshotRequestMessage: Codable, Equatable {
var requestId: String
var sentAtMs: Int?
}
struct WatchExecApprovalResolveMessage: Codable, Equatable {
var approvalId: String
var decision: WatchExecApprovalDecision
var replyId: String
var sentAtMs: Int?
}
struct WatchAppSnapshotMessage: Codable, Equatable {
var gatewayStatusText: String
var gatewayConnected: Bool
var agentName: String
var agentAvatarURL: String?
var agentAvatarText: String?
var sessionKey: String
var gatewayStableID: String?
var talkStatusText: String
var talkEnabled: Bool
var talkListening: Bool
var talkSpeaking: Bool
var pendingApprovalCount: Int
var chatItems: [WatchChatItem]?
var chatStatusText: String?
var sentAtMs: Int?
var snapshotId: String?
}
struct WatchChatItem: Codable, Equatable, Identifiable {
var id: String
var role: String
var text: String
var timestampMs: Int?
}
struct WatchAppSnapshotRequestMessage: Codable, Equatable {
var requestId: String
var sentAtMs: Int?
}
enum WatchAppCommand: String, Codable, Equatable {
case refresh
case openChat = "open-chat"
case sendChat = "send-chat"
case startTalk = "start-talk"
case stopTalk = "stop-talk"
}
struct WatchAppCommandMessage: Codable, Equatable {
var command: WatchAppCommand
var commandId: String
var sessionKey: String?
var gatewayStableID: String?
var text: String?
var sentAtMs: Int?
}
struct WatchPromptAction: Codable, Equatable, Identifiable {
var id: String
var label: String
var style: String?
}
struct WatchNotifyMessage {
var id: String?
var title: String
var body: String
var sentAtMs: Int?
var promptId: String?
var sessionKey: String?
var kind: String?
var details: String?
var expiresAtMs: Int?
var risk: String?
var actions: [WatchPromptAction]
}
struct WatchExecApprovalRecord: Codable, Equatable, Identifiable {
var approval: WatchExecApprovalItem
var transport: String
var updatedAt: Date
var isResolving: Bool
var pendingDecision: WatchExecApprovalDecision?
var statusText: String?
var statusAt: Date?
var id: String {
self.approval.id
}
}
@MainActor @Observable final class WatchInboxStore {
private struct PersistedState: Codable {
var title: String
var body: String
var transport: String
var updatedAt: Date
var lastDeliveryKey: String?
var promptId: String?
var sessionKey: String?
var kind: String?
var details: String?
var expiresAtMs: Int?
var risk: String?
var actions: [WatchPromptAction]?
var replyStatusText: String?
var replyStatusAt: Date?
var execApprovals: [WatchExecApprovalRecord]
var selectedExecApprovalID: String?
var lastExecApprovalSnapshotID: String?
var lastExecApprovalOutcomeText: String?
var lastExecApprovalOutcomeAt: Date?
var appSnapshot: WatchAppSnapshotMessage?
var appSnapshotUpdatedAt: Date?
var appSnapshotStatusText: String?
var appCommandStatusText: String?
}
private static let persistedStateKey = "watch.inbox.state.v2"
private static let defaultTitle = "OpenClaw"
private static let defaultBody = "Waiting for messages from your iPhone."
private let defaults: UserDefaults
var title = WatchInboxStore.defaultTitle
var body = WatchInboxStore.defaultBody
var transport = "none"
var updatedAt: Date?
var promptId: String?
var sessionKey: String?
var kind: String?
var details: String?
var expiresAtMs: Int?
var risk: String?
var actions: [WatchPromptAction] = []
var replyStatusText: String?
var replyStatusAt: Date?
var isReplySending = false
var execApprovals: [WatchExecApprovalRecord] = []
var selectedExecApprovalID: String?
var lastExecApprovalOutcomeText: String?
var lastExecApprovalOutcomeAt: Date?
var appSnapshot: WatchAppSnapshotMessage?
var appSnapshotUpdatedAt: Date?
var appSnapshotStatusText: String?
var appCommandStatusText: String?
var greetingTextOverride: String?
var isExecApprovalReviewLoading = false
var execApprovalReviewStatusText: String?
var execApprovalReviewStatusAt: Date?
private var lastExecApprovalSnapshotID: String?
private var hasCompletedExecApprovalSnapshotRefreshInSession = false
private var lastDeliveryKey: String?
init(
defaults: UserDefaults = .standard,
requestNotificationAuthorization: Bool = true)
{
self.defaults = defaults
self.restorePersistedState()
self.pruneExpiredExecApprovals(nowMs: Self.nowMs())
if requestNotificationAuthorization {
Task {
await self.ensureNotificationAuthorization()
}
}
}
var sortedExecApprovals: [WatchExecApprovalRecord] {
self.execApprovals.sorted { lhs, rhs in
let lhsExpires = lhs.approval.expiresAtMs ?? Int.max
let rhsExpires = rhs.approval.expiresAtMs ?? Int.max
if lhsExpires != rhsExpires {
return lhsExpires < rhsExpires
}
return lhs.updatedAt > rhs.updatedAt
}
}
var activeExecApproval: WatchExecApprovalRecord? {
if let selectedExecApprovalID,
let selected = execApprovals.first(where: { $0.id == selectedExecApprovalID })
{
return selected
}
return self.sortedExecApprovals.first
}
var shouldAutoRequestExecApprovalSnapshot: Bool {
self.execApprovals.isEmpty
&& self.actions.isEmpty
&& self.title == Self.defaultTitle
&& self.body == Self.defaultBody
&& !self.hasCompletedExecApprovalSnapshotRefreshInSession
}
var hasCompletedExecApprovalSnapshotRefresh: Bool {
self.hasCompletedExecApprovalSnapshotRefreshInSession
}
var shouldShowExecApprovalReviewStatus: Bool {
self.execApprovals.isEmpty && !(self.execApprovalReviewStatusText?.isEmpty ?? true)
}
var hasAppSnapshot: Bool {
self.appSnapshot != nil
}
var hasMessagePrompt: Bool {
self.title != Self.defaultTitle
|| self.body != Self.defaultBody
|| !self.actions.isEmpty
}
var gatewaySummaryText: String {
guard let appSnapshot else { return "Waiting for iPhone" }
return appSnapshot.gatewayConnected ? "Connected" : appSnapshot.gatewayStatusText
}
var talkSummaryText: String {
guard let appSnapshot else { return "Not synced" }
if appSnapshot.talkListening {
return "Listening"
}
if appSnapshot.talkSpeaking {
return "Speaking"
}
if appSnapshot.talkEnabled {
return appSnapshot.talkStatusText.isEmpty ? "Ready" : appSnapshot.talkStatusText
}
return "Off"
}
func beginExecApprovalReviewLoading() {
guard self.execApprovals.isEmpty else {
self.markExecApprovalReviewLoaded()
return
}
self.isExecApprovalReviewLoading = true
self.execApprovalReviewStatusText = "Loading approval from iPhone…"
self.execApprovalReviewStatusAt = Date()
}
func markExecApprovalReviewLoaded() {
self.isExecApprovalReviewLoading = false
self.execApprovalReviewStatusText = nil
self.execApprovalReviewStatusAt = nil
}
func markExecApprovalReviewUnavailable(_ message: String) {
guard self.execApprovals.isEmpty else {
self.markExecApprovalReviewLoaded()
return
}
self.isExecApprovalReviewLoading = false
self.execApprovalReviewStatusText = message
self.execApprovalReviewStatusAt = Date()
}
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.markExecApprovalReviewLoaded()
self.updatedAt = Date()
self.promptId = message.promptId
self.sessionKey = message.sessionKey
self.kind = message.kind
self.details = message.details
self.expiresAtMs = message.expiresAtMs
self.risk = message.risk
self.actions = message.actions
self.lastDeliveryKey = deliveryKey
self.replyStatusText = nil
self.replyStatusAt = nil
self.isReplySending = false
self.persistState()
Task {
await self.postLocalNotification(
identifier: deliveryKey,
title: normalizedTitle,
body: message.body,
risk: message.risk)
}
}
func consume(
execApprovalPrompt message: WatchExecApprovalPromptMessage,
transport: String)
{
self.pruneExpiredExecApprovals(nowMs: Self.nowMs())
self.upsertExecApproval(
message.approval,
transport: transport,
keepSelectionIfPossible: true,
resetResolvingState: message.resetResolvingState == true)
self.markExecApprovalReviewLoaded()
self.lastExecApprovalOutcomeText = nil
self.lastExecApprovalOutcomeAt = nil
Task {
await self.postLocalNotification(
identifier: "watch.execApproval.\(message.approval.id)",
title: "Exec approval required",
body: message.approval.commandPreview ?? message.approval.commandText,
risk: message.approval.risk?.rawValue)
}
}
func consume(
execApprovalSnapshot message: WatchExecApprovalSnapshotMessage,
transport: String)
{
let snapshotID = message.snapshotId?.trimmingCharacters(in: .whitespacesAndNewlines)
if let snapshotID, !snapshotID.isEmpty, snapshotID == lastExecApprovalSnapshotID {
return
}
let existingRecordsByID = Dictionary(
uniqueKeysWithValues: execApprovals.map { ($0.id, $0) })
self.execApprovals = message.approvals.map { approval in
self.mergedExecApprovalRecord(
approval: approval,
transport: transport,
existingRecord: existingRecordsByID[approval.id])
}
self.lastExecApprovalSnapshotID = snapshotID
self.hasCompletedExecApprovalSnapshotRefreshInSession = true
if let selectedExecApprovalID,
!self.execApprovals.contains(where: { $0.id == selectedExecApprovalID })
{
self.selectedExecApprovalID = self.sortedExecApprovals.first?.id
} else if selectedExecApprovalID == nil {
selectedExecApprovalID = self.sortedExecApprovals.first?.id
}
self.pruneExpiredExecApprovals(nowMs: Self.nowMs())
self.markExecApprovalReviewLoaded()
self.persistState()
}
func consume(appSnapshot message: WatchAppSnapshotMessage) {
let snapshotID = message.snapshotId?.trimmingCharacters(in: .whitespacesAndNewlines)
if let snapshotID, !snapshotID.isEmpty, snapshotID == appSnapshot?.snapshotId {
return
}
var merged = message
if merged.chatItems == nil {
merged.chatItems = self.appSnapshot?.chatItems
}
if merged.chatStatusText == nil {
merged.chatStatusText = self.appSnapshot?.chatStatusText
}
self.appSnapshot = merged
self.appSnapshotUpdatedAt = Date()
self.appSnapshotStatusText = nil
self.persistState()
}
func markAppSnapshotRequestStarted() {
self.appSnapshotStatusText = "Refreshing from iPhone…"
self.persistState()
}
func markAppSnapshotRequestResult(_ result: WatchReplySendResult) {
if let errorMessage = result.errorMessage, !errorMessage.isEmpty {
self.appSnapshotStatusText = "Refresh failed: \(errorMessage)"
} else if result.deliveredImmediately {
self.appSnapshotStatusText = "Refresh requested"
} else if result.queuedForDelivery {
self.appSnapshotStatusText = "Refresh queued"
} else {
self.appSnapshotStatusText = nil
}
self.persistState()
}
func makeAppCommand(_ command: WatchAppCommand, text: String? = nil) -> WatchAppCommandMessage {
let snapshotSessionKey = self.appSnapshot?.sessionKey.trimmingCharacters(in: .whitespacesAndNewlines)
return WatchAppCommandMessage(
command: command,
commandId: UUID().uuidString,
sessionKey: (snapshotSessionKey?.isEmpty == false) ? snapshotSessionKey : self.sessionKey,
gatewayStableID: self.appSnapshot?.gatewayStableID,
text: text,
sentAtMs: Self.nowMs())
}
var hasGatewayTaggedAppSnapshot: Bool {
let gatewayStableID = self.appSnapshot?.gatewayStableID?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return !gatewayStableID.isEmpty
}
func markAppCommandSending(_ command: WatchAppCommand) {
self.appCommandStatusText = "Sending \(Self.commandLabel(command))"
self.persistState()
}
func markAppCommandBlocked(_ command: WatchAppCommand, reason: String) {
self.appCommandStatusText = "\(Self.commandLabel(command)): \(reason)"
self.persistState()
}
func markAppCommandResult(_ result: WatchReplySendResult, command: WatchAppCommand) {
let label = Self.commandLabel(command)
if let errorMessage = result.errorMessage, !errorMessage.isEmpty {
self.appCommandStatusText = "\(label) failed: \(errorMessage)"
} else if result.deliveredImmediately {
self.appCommandStatusText = "\(label): sent"
} else if result.queuedForDelivery {
self.appCommandStatusText = "\(label): queued"
} else {
self.appCommandStatusText = "\(label): sent"
}
self.persistState()
}
func consume(execApprovalResolved message: WatchExecApprovalResolvedMessage) {
self.removeExecApproval(id: message.approvalId)
let statusText = switch message.decision {
case .allowOnce:
"Allowed once"
case .deny:
"Denied"
case nil:
"Approval resolved"
}
self.lastExecApprovalOutcomeText = statusText
self.lastExecApprovalOutcomeAt = Date()
self.persistState()
}
func consume(execApprovalExpired message: WatchExecApprovalExpiredMessage) {
self.removeExecApproval(id: message.approvalId)
let statusText = switch message.reason {
case .expired:
"Approval expired"
case .notFound:
"Approval no longer available"
case .resolved:
"Approval resolved elsewhere"
case .replaced:
"Approval replaced"
case .unavailable:
"Approval unavailable"
}
self.lastExecApprovalOutcomeText = statusText
self.lastExecApprovalOutcomeAt = Date()
self.persistState()
}
func selectExecApproval(id: String) {
let normalizedID = id.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalizedID.isEmpty else { return }
guard self.execApprovals.contains(where: { $0.id == normalizedID }) else { return }
self.selectedExecApprovalID = normalizedID
self.persistState()
}
func markExecApprovalSending(approvalId: String, decision: WatchExecApprovalDecision) {
guard let index = execApprovals.firstIndex(where: { $0.id == approvalId }) else { return }
self.execApprovals[index].isResolving = true
self.execApprovals[index].pendingDecision = decision
self.execApprovals[index].statusText = "Sending \(Self.decisionLabel(decision))"
self.execApprovals[index].statusAt = Date()
self.persistState()
}
func markExecApprovalSendResult(
approvalId: String,
decision: WatchExecApprovalDecision,
result: WatchReplySendResult)
{
guard let index = execApprovals.firstIndex(where: { $0.id == approvalId }) else { return }
if let errorMessage = result.errorMessage, !errorMessage.isEmpty {
self.execApprovals[index].isResolving = false
self.execApprovals[index].statusText = "Failed: \(errorMessage)"
} else if result.deliveredImmediately {
self.execApprovals[index].isResolving = true
self.execApprovals[index].statusText = "\(Self.decisionLabel(decision)): sent"
} else if result.queuedForDelivery {
self.execApprovals[index].isResolving = true
self.execApprovals[index].statusText = "\(Self.decisionLabel(decision)): queued"
} else {
self.execApprovals[index].isResolving = true
self.execApprovals[index].statusText = "\(Self.decisionLabel(decision)): sent"
}
self.execApprovals[index].pendingDecision = result.errorMessage == nil ? decision : nil
self.execApprovals[index].statusAt = Date()
self.persistState()
}
private func upsertExecApproval(
_ approval: WatchExecApprovalItem,
transport: String,
keepSelectionIfPossible: Bool,
resetResolvingState: Bool = false)
{
if let index = execApprovals.firstIndex(where: { $0.id == approval.id }) {
self.execApprovals[index] = self.mergedExecApprovalRecord(
approval: approval,
transport: transport,
existingRecord: self.execApprovals[index],
resetResolvingState: resetResolvingState)
} else {
self.execApprovals.append(
self.mergedExecApprovalRecord(
approval: approval,
transport: transport,
existingRecord: nil,
resetResolvingState: resetResolvingState))
}
if !keepSelectionIfPossible || self.selectedExecApprovalID == nil {
self.selectedExecApprovalID = approval.id
}
self.persistState()
}
private func mergedExecApprovalRecord(
approval: WatchExecApprovalItem,
transport: String,
existingRecord: WatchExecApprovalRecord?,
resetResolvingState: Bool = false) -> WatchExecApprovalRecord
{
// Preserve in-flight state across ordinary snapshot/prompt refreshes so duplicate
// submissions stay disabled, but clear it when the iPhone explicitly republishes a
// prompt after a failed resolve so the watch can retry.
let isResolving = resetResolvingState ? false : (existingRecord?.isResolving ?? false)
let pendingDecision = resetResolvingState ? nil : existingRecord?.pendingDecision
let statusText = resetResolvingState ? nil : existingRecord?.statusText
let statusAt = resetResolvingState ? nil : existingRecord?.statusAt
return WatchExecApprovalRecord(
approval: approval,
transport: transport,
updatedAt: Date(),
isResolving: isResolving,
pendingDecision: pendingDecision,
statusText: statusText,
statusAt: statusAt)
}
private func removeExecApproval(id: String) {
let normalizedID = id.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalizedID.isEmpty else { return }
self.execApprovals.removeAll { $0.id == normalizedID }
if self.selectedExecApprovalID == normalizedID {
self.selectedExecApprovalID = self.sortedExecApprovals.first?.id
}
self.persistState()
}
private func pruneExpiredExecApprovals(nowMs: Int) {
self.execApprovals.removeAll { record in
guard let expiresAtMs = record.approval.expiresAtMs else { return false }
return expiresAtMs <= nowMs
}
if let selectedExecApprovalID,
!self.execApprovals.contains(where: { $0.id == selectedExecApprovalID })
{
self.selectedExecApprovalID = self.sortedExecApprovals.first?.id
}
self.persistState()
}
private func restorePersistedState() {
guard let data = 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
self.promptId = state.promptId
self.sessionKey = state.sessionKey
self.kind = state.kind
self.details = state.details
self.expiresAtMs = state.expiresAtMs
self.risk = state.risk
self.actions = state.actions ?? []
self.replyStatusText = state.replyStatusText
self.replyStatusAt = state.replyStatusAt
self.execApprovals = state.execApprovals
self.selectedExecApprovalID = state.selectedExecApprovalID
self.lastExecApprovalSnapshotID = state.lastExecApprovalSnapshotID
self.lastExecApprovalOutcomeText = state.lastExecApprovalOutcomeText
self.lastExecApprovalOutcomeAt = state.lastExecApprovalOutcomeAt
self.appSnapshot = state.appSnapshot
self.appSnapshotUpdatedAt = state.appSnapshotUpdatedAt
self.appSnapshotStatusText = state.appSnapshotStatusText
self.appCommandStatusText = state.appCommandStatusText
}
private func persistState() {
let updatedAt = self.updatedAt ?? self.lastExecApprovalOutcomeAt ?? Date()
let state = PersistedState(
title: title,
body: body,
transport: transport,
updatedAt: updatedAt,
lastDeliveryKey: lastDeliveryKey,
promptId: promptId,
sessionKey: sessionKey,
kind: kind,
details: details,
expiresAtMs: expiresAtMs,
risk: risk,
actions: actions,
replyStatusText: replyStatusText,
replyStatusAt: replyStatusAt,
execApprovals: execApprovals,
selectedExecApprovalID: selectedExecApprovalID,
lastExecApprovalSnapshotID: lastExecApprovalSnapshotID,
lastExecApprovalOutcomeText: lastExecApprovalOutcomeText,
lastExecApprovalOutcomeAt: lastExecApprovalOutcomeAt,
appSnapshot: appSnapshot,
appSnapshotUpdatedAt: appSnapshotUpdatedAt,
appSnapshotStatusText: appSnapshotStatusText,
appCommandStatusText: appCommandStatusText)
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 mapHapticRisk(_ risk: String?) -> WKHapticType {
switch risk?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() {
case "high":
.failure
case "medium":
.notification
default:
.click
}
}
func makeReplyDraft(action: WatchPromptAction) -> WatchReplyDraft {
let prompt = self.promptId?.trimmingCharacters(in: .whitespacesAndNewlines)
return WatchReplyDraft(
replyId: UUID().uuidString,
promptId: (prompt?.isEmpty == false) ? prompt! : "unknown",
actionId: action.id,
actionLabel: action.label,
sessionKey: self.sessionKey,
note: nil,
sentAtMs: Self.nowMs())
}
func markReplySending(actionLabel: String) {
self.isReplySending = true
self.replyStatusText = "Sending \(actionLabel)"
self.replyStatusAt = Date()
self.persistState()
}
func markReplyResult(_ result: WatchReplySendResult, actionLabel: String) {
self.isReplySending = false
if let errorMessage = result.errorMessage, !errorMessage.isEmpty {
self.replyStatusText = "Failed: \(errorMessage)"
} else if result.deliveredImmediately {
self.replyStatusText = "\(actionLabel): sent"
} else if result.queuedForDelivery {
self.replyStatusText = "\(actionLabel): queued"
} else {
self.replyStatusText = "\(actionLabel): sent"
}
self.replyStatusAt = Date()
self.persistState()
}
private func postLocalNotification(identifier: String, title: String, body: String, risk: 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(self.mapHapticRisk(risk))
}
private static func decisionLabel(_ decision: WatchExecApprovalDecision) -> String {
switch decision {
case .allowOnce:
"Allow Once"
case .deny:
"Deny"
}
}
private static func commandLabel(_ command: WatchAppCommand) -> String {
switch command {
case .refresh:
"Refresh"
case .openChat:
"Open Chat"
case .sendChat:
"Chat"
case .startTalk:
"Start Talk"
case .stopTalk:
"Stop Talk"
}
}
private static func nowMs() -> Int {
Int(Date().timeIntervalSince1970 * 1000)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
"CFBundleDisplayName" = "OpenClaw";