Compare commits

..

8 Commits

Author SHA1 Message Date
Omar Shahine
d3c3562fcc perf: reuse gateway provider hooks for turn workspaces 2026-06-23 16:53:41 -07:00
Omar Shahine
1560b346e7 perf: reduce iMessage turn setup latency 2026-06-23 14:17:25 -07:00
Omar Shahine
c39247f2e9 fix(codex): account for source reply SDK surface 2026-06-23 07:29:03 -07:00
Omar Shahine
4337b4b572 fix(codex): accept numeric source message ids 2026-06-23 07:29:03 -07:00
Omar Shahine
9d08d4e98c fix(codex): recognize message tool source replies 2026-06-23 07:29:03 -07:00
Omar Shahine
8dafb6c3b5 fix(imessage): satisfy monitor lint 2026-06-23 07:28:59 -07:00
Omar Shahine
40259a1256 fix(imessage): balance early typing cleanup 2026-06-23 07:28:59 -07:00
Omar Shahine
1a4ebea073 perf(imessage): show typing before slow reply setup 2026-06-23 07:28:59 -07:00
142 changed files with 2410 additions and 2066 deletions

View File

@@ -220,7 +220,7 @@ jobs:
with:
name: ios-periphery-dead-code-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/ios-periphery
if-no-files-found: error
if-no-files-found: warn
retention-days: 14
- name: Fail on dead code

View File

@@ -89,6 +89,7 @@ jobs:
with:
ref: ${{ needs.validate_selected_ref.outputs.selected_revision }}
qa_profile: all
fail_on_qa_failure: false
secrets:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}

View File

@@ -20,6 +20,11 @@ on:
required: true
default: release
type: string
fail_on_qa_failure:
description: Fail the workflow when the QA profile command exits non-zero
required: false
default: true
type: boolean
workflow_call:
inputs:
ref:
@@ -35,6 +40,11 @@ on:
description: Taxonomy QA profile id to run
required: true
type: string
fail_on_qa_failure:
description: Fail the reusable workflow when the QA profile command exits non-zero
required: false
default: false
type: boolean
secrets:
OPENAI_API_KEY:
description: OpenAI API key used by live QA profile scenarios
@@ -357,8 +367,8 @@ jobs:
retention-days: 30
if-no-files-found: error
- name: Fail if QA profile failed
if: always()
- name: Fail if configured QA gate failed
if: always() && inputs.fail_on_qa_failure
env:
QA_EXIT_CODE: ${{ steps.run_profile.outputs.qa_exit_code }}
QA_PROFILE: ${{ steps.profile.outputs.profile }}

View File

@@ -67,9 +67,9 @@ Release behavior:
- App Store release uses canonical `ai.openclawfoundation.app*` bundle IDs through a temporary generated xcconfig in `apps/ios/build/AppStoreRelease.xcconfig`.
- App Store release uses manual `Apple Distribution` signing with profile names pinned in `apps/ios/Config/AppStoreSigning.json`.
- Fastlane owns one-time Developer Portal setup, encrypted `match` signing sync to the repo/branch pinned in `apps/ios/Config/AppStoreSigning.json`, and release handling.
- App Store release also switches the app to `OpenClawPushMode=appStore`, which derives relay transport, official distribution, the canonical production relay, production APNs, production relay profile, `appleStrict` proof, and the App-Attest-capable entitlement file.
- App Store release also switches the app to `OpenClawPushTransport=relay`, `OpenClawPushDistribution=official`, `OpenClawPushAPNsEnvironment=production`, `OpenClawPushRelayProfile=production`, `OpenClawPushProofPolicy=appleStrict`, and the App-Attest-capable entitlement file.
- `pnpm ios:release:upload` generates App Store screenshots and uploads release notes before archiving and uploading the IPA.
- The release archive is validated before upload by inspecting the exported IPA's signed entitlements, embedded App Store profile, and push mode. The upload fails if the IPA is not an App Store production relay build.
- `pnpm ios:release` remains a compatibility alias for `pnpm ios:release:upload`; prefer the explicit upload command in new release docs and automation.
- App Review submission is manual in App Store Connect. The release lane uploads a build and metadata, but does not submit for review.
- The release flow does not modify `apps/ios/.local-signing.xcconfig` or `apps/ios/LocalSigning.xcconfig`.
- `apps/ios/version.json` is the pinned iOS release version source.
@@ -83,8 +83,9 @@ Release behavior:
Relay behavior for App Store builds:
- App Store release builds use the canonical hosted relay at `https://ios-push-relay.openclaw.ai`.
- App Store release builds reject custom relay URL overrides. Future self-hosted relay support should use a separate explicit release path, not the public App Store build lane.
- Release builds default to `https://ios-push-relay.openclaw.ai`.
- Optional custom relay override: `OPENCLAW_PUSH_RELAY_BASE_URL=https://relay.example.com`
This must be a plain `https://host[:port][/path]` base URL without whitespace, query params, fragments, or xcconfig metacharacters.
Signing setup commands:
@@ -161,19 +162,25 @@ This should create `apps/ios/fastlane/.env` with non-secret App Store Connect va
Use `pnpm ios:release:signing:setup` for the initial portal setup, then `MATCH_PASSWORD=... pnpm ios:release:signing:sync:push` to publish encrypted Fastlane match assets to the shared private repo.
4. If you are starting a brand-new production release train, pin iOS to the current gateway version first:
4. Optional: set a custom official relay URL for the build. If unset, the release flow uses `https://ios-push-relay.openclaw.ai`.
```bash
export OPENCLAW_PUSH_RELAY_BASE_URL=https://relay.example.com
```
5. If you are starting a brand-new production release train, pin iOS to the current gateway version first:
```bash
pnpm ios:version:pin -- --from-gateway
```
5. Upload the build:
6. Upload the build:
```bash
pnpm ios:release:upload
```
6. Expected behavior:
7. Expected behavior:
- Fastlane reads `apps/ios/version.json`
- verifies synced iOS versioning artifacts
- resolves the next App Store Connect build number for that short version
@@ -181,16 +188,15 @@ pnpm ios:release:upload
- uploads release notes and screenshots to the editable App Store version
- generates `apps/ios/build/AppStoreRelease.xcconfig`
- archives `OpenClaw`
- validates the exported IPA's push mode, signed entitlements, and embedded App Store profile
- uploads the IPA to App Store Connect for TestFlight/App Review use
- leaves App Review submission for a maintainer to complete manually
7. Expected outputs after a successful run:
8. Expected outputs after a successful run:
- `apps/ios/build/app-store/OpenClaw-<version>.ipa`
- `apps/ios/build/app-store/OpenClaw-<version>.app.dSYM.zip`
- Fastlane log line like `Uploaded iOS App Store build: version=<version> short=<short> build=<build>`
8. If this is a fresh clone on a maintainer machine that already works elsewhere, it is OK to copy the non-secret `apps/ios/fastlane/.env` from another trusted local clone on the same Mac. The Keychain-backed private key remains machine-local and is not stored in the repo.
9. If this is a fresh clone on a maintainer machine that already works elsewhere, it is OK to copy the non-secret `apps/ios/fastlane/.env` from another trusted local clone on the same Mac. The Keychain-backed private key remains machine-local and is not stored in the repo.
## iOS Versioning Workflow
@@ -240,13 +246,13 @@ See `apps/ios/VERSIONING.md` for the detailed spec.
- `apps/ios/Sources/OpenClaw.entitlements` derives `aps-environment` from the active build configuration/signing override.
- App Attest relay builds use `apps/ios/Sources/OpenClawAppAttest.entitlements`; local/direct builds do not require App Attest provisioning.
- APNs token registration to gateway happens only after gateway connection (`push.apns.register`).
- Local/manual Debug builds default to `OpenClawPushMode=localSandbox`, direct APNs registration, and a development `aps-environment` entitlement. Local/manual Release builds default to `OpenClawPushMode=localProduction` and direct production APNs registration.
- Local/manual builds default to `OpenClawPushTransport=direct`, `OpenClawPushDistribution=local`, and a development `aps-environment` entitlement.
- 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`).
- The gateway host also needs direct APNs auth configured separately with `OPENCLAW_APNS_TEAM_ID`, `OPENCLAW_APNS_KEY_ID`, and either `OPENCLAW_APNS_PRIVATE_KEY_P8` or `OPENCLAW_APNS_PRIVATE_KEY_PATH`.
- Recommended gateway-host storage for the APNs `.p8` file is `~/.openclaw/credentials/apns/AuthKey_<KEYID>.p8` with restrictive permissions, then point `OPENCLAW_APNS_PRIVATE_KEY_PATH` at that file.
- `apps/ios/fastlane/.env` only covers App Store Connect / Fastlane auth; it does not provide gateway APNs credentials for local direct-push testing.
- Debug builds default to sandbox APNs through `OpenClawPushMode=localSandbox`; Release builds default to production APNs through `OpenClawPushMode=localProduction`.
- Debug builds default to `OpenClawPushAPNsEnvironment=sandbox`; Release builds default to `production`.
## APNs Expectations For Official Builds
@@ -255,7 +261,7 @@ See `apps/ios/VERSIONING.md` for the detailed spec.
- The relay registration is bound to the gateway identity fetched from `gateway.identity.get`, so another gateway cannot reuse that stored registration.
- The app persists the relay handle metadata locally so reconnects can republish the gateway registration without re-registering on every connect.
- If the relay base URL changes in a later build, the app refreshes the relay registration instead of reusing the old relay origin.
- App Store release mode uses the internal `production` relay profile, production APNs, App Attest, and a StoreKit app transaction JWS during registration.
- Production relay mode uses the `production` relay profile, production APNs, App Attest, and a StoreKit app transaction JWS during registration.
- Gateway-side relay sending is configured through `gateway.push.apns.relay.baseUrl` in `openclaw.json`. `OPENCLAW_APNS_RELAY_BASE_URL` remains a temporary env override only.
## Official Build Relay Trust Model

View File

@@ -82,10 +82,18 @@
<string>$(OPENCLAW_APP_GROUP_ID)</string>
<key>OpenClawCanonicalVersion</key>
<string>$(OPENCLAW_IOS_VERSION)</string>
<key>OpenClawPushMode</key>
<string>$(OPENCLAW_PUSH_MODE)</string>
<key>OpenClawPushAPNsEnvironment</key>
<string>$(OPENCLAW_PUSH_APNS_ENVIRONMENT)</string>
<key>OpenClawPushDistribution</key>
<string>$(OPENCLAW_PUSH_DISTRIBUTION)</string>
<key>OpenClawPushProofPolicy</key>
<string>$(OPENCLAW_PUSH_PROOF_POLICY)</string>
<key>OpenClawPushRelayBaseURL</key>
<string>$(OPENCLAW_PUSH_RELAY_BASE_URL)</string>
<key>OpenClawPushRelayProfile</key>
<string>$(OPENCLAW_PUSH_RELAY_PROFILE)</string>
<key>OpenClawPushTransport</key>
<string>$(OPENCLAW_PUSH_TRANSPORT)</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>

View File

@@ -27,16 +27,7 @@ enum PushProofPolicy: String {
case internalSimulator
}
enum PushBuildMode: String {
case localSandbox
case localProduction
case appStore
case deviceSandbox
case simulatorSandbox
}
struct PushBuildConfig {
let mode: PushBuildMode
let transport: PushTransportMode
let distribution: PushDistributionMode
let relayBaseURL: URL?
@@ -63,64 +54,31 @@ struct PushBuildConfig {
}
init(bundle: Bundle = .main) {
self.init(readValue: { bundle.object(forInfoDictionaryKey: $0) })
self.transport = Self.readEnum(
bundle: bundle,
key: "OpenClawPushTransport",
fallback: .direct)
self.distribution = Self.readEnum(
bundle: bundle,
key: "OpenClawPushDistribution",
fallback: .local)
self.apnsEnvironment = Self.readEnum(
bundle: bundle,
key: "OpenClawPushAPNsEnvironment",
fallback: Self.defaultAPNsEnvironment)
self.relayProfile = Self.readEnum(
bundle: bundle,
key: "OpenClawPushRelayProfile",
fallback: Self.defaultRelayProfile(apnsEnvironment: self.apnsEnvironment))
self.proofPolicy = Self.readEnum(
bundle: bundle,
key: "OpenClawPushProofPolicy",
fallback: Self.defaultProofPolicy(relayProfile: self.relayProfile))
self.relayBaseURL = Self.readURL(bundle: bundle, key: "OpenClawPushRelayBaseURL")
}
init(infoDictionary: [String: Any]) {
self.init(readValue: { infoDictionary[$0] })
}
private init(readValue: (String) -> Any?) {
self.mode = Self.readEnum(
readValue: readValue,
key: "OpenClawPushMode",
fallback: .localSandbox)
let relayBaseURLOverride = Self.readURL(
readValue: readValue,
key: "OpenClawPushRelayBaseURL")
switch self.mode {
case .localSandbox:
self.transport = .direct
self.distribution = .local
self.relayBaseURL = nil
self.apnsEnvironment = .sandbox
self.relayProfile = .deviceSandbox
self.proofPolicy = .appleDevelopment
case .localProduction:
self.transport = .direct
self.distribution = .local
self.relayBaseURL = nil
self.apnsEnvironment = .production
self.relayProfile = .production
self.proofPolicy = .appleStrict
case .appStore:
self.transport = .relay
self.distribution = .official
self.relayBaseURL = URL(string: "https://\(Self.openClawHostedRelayHost)")!
self.apnsEnvironment = .production
self.relayProfile = .production
self.proofPolicy = .appleStrict
case .deviceSandbox:
self.transport = .relay
self.distribution = .official
self.relayBaseURL = relayBaseURLOverride
?? URL(string: "https://\(Self.openClawSandboxRelayHost)")!
self.apnsEnvironment = .sandbox
self.relayProfile = .deviceSandbox
self.proofPolicy = .appleDevelopment
case .simulatorSandbox:
self.transport = .relay
self.distribution = .official
self.relayBaseURL = relayBaseURLOverride
?? URL(string: "https://\(Self.openClawSandboxRelayHost)")!
self.apnsEnvironment = .sandbox
self.relayProfile = .simulatorSandbox
self.proofPolicy = .internalSimulator
}
}
private static func readURL(readValue: (String) -> Any?, key: String) -> URL? {
guard let raw = readValue(key) as? String else { return nil }
private static func readURL(bundle: Bundle, key: String) -> URL? {
guard let raw = bundle.object(forInfoDictionaryKey: key) as? String else { return nil }
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return nil }
guard let components = URLComponents(string: trimmed),
@@ -138,12 +96,29 @@ struct PushBuildConfig {
}
private static func readEnum<T: RawRepresentable>(
readValue: (String) -> Any?,
bundle: Bundle,
key: String,
fallback: T)
-> T where T.RawValue == String {
guard let raw = readValue(key) as? String else { return fallback }
guard let raw = bundle.object(forInfoDictionaryKey: key) as? String else { return fallback }
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
return T(rawValue: trimmed) ?? T(rawValue: trimmed.lowercased()) ?? fallback
}
private static let defaultAPNsEnvironment: PushAPNsEnvironment = .sandbox
private static func defaultRelayProfile(apnsEnvironment: PushAPNsEnvironment) -> PushRelayProfile {
apnsEnvironment == .production ? .production : .deviceSandbox
}
private static func defaultProofPolicy(relayProfile: PushRelayProfile) -> PushProofPolicy {
switch relayProfile {
case .production:
.appleStrict
case .deviceSandbox:
.appleDevelopment
case .simulatorSandbox:
.internalSimulator
}
}
}

View File

@@ -69,7 +69,7 @@ actor PushRegistrationManager {
async throws -> String {
guard self.buildConfig.distribution == .official else {
throw PushRelayError.relayMisconfigured(
"Relay transport requires an official push build mode")
"Relay transport requires OpenClawPushDistribution=official")
}
try Self.validateRelayContract(
relayProfile: self.buildConfig.relayProfile,

View File

@@ -1,50 +0,0 @@
import Foundation
import Testing
@testable import OpenClaw
struct PushBuildConfigTests {
@Test func `app store mode derives production relay contract`() {
let config = PushBuildConfig(infoDictionary: [
"OpenClawPushMode": "appStore",
"OpenClawPushRelayBaseURL": "https://wrong.example.com",
])
#expect(config.mode == .appStore)
#expect(config.transport == .relay)
#expect(config.distribution == .official)
#expect(config.relayBaseURL?.absoluteString == "https://ios-push-relay.openclaw.ai")
#expect(config.apnsEnvironment == .production)
#expect(config.relayProfile == .production)
#expect(config.proofPolicy == .appleStrict)
}
@Test func `simulator sandbox mode derives internal proof contract`() {
let config = PushBuildConfig(infoDictionary: [
"OpenClawPushMode": "simulatorSandbox",
"OpenClawPushRelayBaseURL": "https://staging-relay.example.com",
])
#expect(config.mode == .simulatorSandbox)
#expect(config.transport == .relay)
#expect(config.distribution == .official)
#expect(config.relayBaseURL?.absoluteString == "https://staging-relay.example.com")
#expect(config.apnsEnvironment == .sandbox)
#expect(config.relayProfile == .simulatorSandbox)
#expect(config.proofPolicy == .internalSimulator)
}
@Test func `local release mode remains direct production push`() {
let config = PushBuildConfig(infoDictionary: [
"OpenClawPushMode": "localProduction",
"OpenClawPushRelayBaseURL": "https://ios-push-relay.openclaw.ai",
])
#expect(config.mode == .localProduction)
#expect(config.transport == .direct)
#expect(config.distribution == .local)
#expect(config.relayBaseURL == nil)
#expect(config.apnsEnvironment == .production)
#expect(config.relayProfile == .production)
#expect(config.proofPolicy == .appleStrict)
}
}

View File

@@ -754,11 +754,6 @@ def prepare_app_store_release!(version:, build_number:)
release_xcconfig
end
def validate_app_store_ipa!(ipa_path)
script_path = File.join(repo_root, "scripts", "ios-validate-app-store-ipa.sh")
sh(shell_join(["bash", script_path, "--ipa", ipa_path]))
end
def build_app_store_release(context)
version = context[:version]
project_path = File.join(ios_root, "OpenClaw.xcodeproj")
@@ -809,7 +804,6 @@ def build_app_store_release(context)
UI.user_error!("xcodebuild export produced multiple IPAs in #{output_directory}: #{exported_ipas.join(", ")}") if exported_ipas.length > 1
exported_ipa = exported_ipas.first
FileUtils.mv(exported_ipa, expected_ipa_path) unless exported_ipa == expected_ipa_path
validate_app_store_ipa!(expected_ipa_path)
{
archive_path: archive_path,
@@ -929,12 +923,25 @@ platform :ios do
ENV.delete("XCODE_XCCONFIG_FILE")
end
desc "Build + upload an App Store distribution build to App Store Connect"
lane :app_store do
context = prepare_app_store_context(require_api_key: true)
build = build_app_store_release(context)
upload_to_testflight(
api_key: context[:api_key],
ipa: build[:ipa_path],
skip_waiting_for_build_processing: true,
uses_non_exempt_encryption: false
)
UI.success("Uploaded iOS App Store build: version=#{build[:version]} short=#{build[:short_version]} build=#{build[:build_number]}")
ensure
ENV.delete("XCODE_XCCONFIG_FILE")
end
desc "Generate screenshots, update App Store version metadata, then upload an App Store build"
lane :release_upload do
unless ENV["OPENCLAW_IOS_RELEASE_WRAPPER"] == "1"
UI.user_error!("Use `pnpm ios:release:upload`; direct Fastlane TestFlight upload is disabled.")
end
release_signing_check!
preserve_local_signing do
screenshots

View File

@@ -112,9 +112,12 @@ Upload to App Store Connect:
pnpm ios:release:upload
```
Direct Fastlane TestFlight upload is disabled. Use the package script so the
release wrapper, App Store push mode, and exported-IPA validation gate all run
in the same path.
Direct Fastlane entry point:
```bash
cd apps/ios
fastlane ios release_upload
```
Maintainer recovery path for a fresh clone on the same Mac:
@@ -141,7 +144,13 @@ fastlane ios auth_check
pnpm ios:version:pin -- --from-gateway
```
5. Upload:
5. Set the official relay URL before release:
```bash
export OPENCLAW_PUSH_RELAY_BASE_URL=https://relay.example.com
```
6. Upload:
```bash
pnpm ios:release:upload
@@ -150,7 +159,6 @@ pnpm ios:release:upload
Quick verification after upload:
- confirm `apps/ios/build/app-store/OpenClaw-<version>.ipa` exists
- confirm Fastlane validates the exported IPA before upload
- confirm Fastlane prints `Uploaded iOS App Store build: version=<version> short=<short> build=<build>`
- remember that App Store Connect/TestFlight processing can take a few minutes after the upload succeeds
@@ -167,7 +175,5 @@ Versioning rules:
- `pnpm ios:version:check` validates that checked-in iOS version artifacts are in sync
- The release flow regenerates `apps/ios/OpenClaw.xcodeproj` from `apps/ios/project.yml` before archiving
- Local App Store signing uses a temporary generated xcconfig with profile names from `apps/ios/Config/AppStoreSigning.json` and leaves local development signing overrides untouched
- App Store release uses `OpenClawPushMode=appStore`, which derives the canonical production hosted relay, production APNs, production relay profile, and `appleStrict` proof. The release lane rejects custom production relay URL overrides.
- The exported IPA is validated before upload by inspecting its push mode, signed entitlements, and embedded App Store profile.
- `pnpm ios:release:upload` generates and uploads screenshots and release notes before archiving, then uploads the IPA without submitting it for App Review
- See `apps/ios/VERSIONING.md` for the detailed workflow

View File

@@ -122,13 +122,21 @@ targets:
Debug:
OPENCLAW_CODE_SIGN_ENTITLEMENTS: Sources/OpenClaw.entitlements
OPENCLAW_APNS_ENTITLEMENT_ENVIRONMENT: development
OPENCLAW_PUSH_MODE: localSandbox
OPENCLAW_PUSH_TRANSPORT: direct
OPENCLAW_PUSH_DISTRIBUTION: local
OPENCLAW_PUSH_RELAY_BASE_URL: ""
OPENCLAW_PUSH_APNS_ENVIRONMENT: sandbox
OPENCLAW_PUSH_RELAY_PROFILE: deviceSandbox
OPENCLAW_PUSH_PROOF_POLICY: appleDevelopment
Release:
OPENCLAW_CODE_SIGN_ENTITLEMENTS: Sources/OpenClaw.entitlements
OPENCLAW_APNS_ENTITLEMENT_ENVIRONMENT: production
OPENCLAW_PUSH_MODE: localProduction
OPENCLAW_PUSH_TRANSPORT: direct
OPENCLAW_PUSH_DISTRIBUTION: local
OPENCLAW_PUSH_RELAY_BASE_URL: ""
OPENCLAW_PUSH_APNS_ENVIRONMENT: production
OPENCLAW_PUSH_RELAY_PROFILE: production
OPENCLAW_PUSH_PROOF_POLICY: appleStrict
info:
path: Sources/Info.plist
properties:
@@ -170,8 +178,12 @@ targets:
NSSpeechRecognitionUsageDescription: OpenClaw uses on-device speech recognition for talk mode and voice wake.
NSSupportsLiveActivities: true
ITSAppUsesNonExemptEncryption: false
OpenClawPushMode: "$(OPENCLAW_PUSH_MODE)"
OpenClawPushTransport: "$(OPENCLAW_PUSH_TRANSPORT)"
OpenClawPushDistribution: "$(OPENCLAW_PUSH_DISTRIBUTION)"
OpenClawPushRelayBaseURL: "$(OPENCLAW_PUSH_RELAY_BASE_URL)"
OpenClawPushAPNsEnvironment: "$(OPENCLAW_PUSH_APNS_ENVIRONMENT)"
OpenClawPushRelayProfile: "$(OPENCLAW_PUSH_RELAY_PROFILE)"
OpenClawPushProofPolicy: "$(OPENCLAW_PUSH_PROOF_POLICY)"
UISupportedInterfaceOrientations:
- UIInterfaceOrientationPortrait
- UIInterfaceOrientationPortraitUpsideDown

View File

@@ -579,7 +579,7 @@ When `imsg launch` is running and `openclaw channels status --probe` reports `pr
</Accordion>
<Accordion title="Read receipts and typing">
When the private API bridge is up, accepted inbound chats are marked read before dispatch and a typing bubble is shown to the sender while the agent generates. Disable read-marking with:
When the private API bridge is up, accepted inbound chats are marked read and direct chats show a typing bubble as soon as the turn is accepted, while the agent prepares context and generates. Disable read-marking with:
```json5
{

View File

@@ -23,8 +23,8 @@ OpenClaw agent or Gateway.
```bash
openclaw skills search "calendar"
openclaw skills install @owner/<slug>
openclaw skills update @owner/<slug>
openclaw skills install <slug>
openclaw skills update <slug>
openclaw skills verify <slug>
openclaw plugins search "calendar"

View File

@@ -24,13 +24,13 @@ where you have publisher access.
Skills are published from a skill folder. The public page is:
```text
https://clawhub.ai/<owner>/skills/<slug>
https://clawhub.ai/<owner>/<slug>
```
Example:
```text
https://clawhub.ai/alice/skills/review-helper
https://clawhub.ai/alice/review-helper
```
The publish request includes the selected owner, slug, version, changelog, and

View File

@@ -25,16 +25,16 @@ Related:
```bash
openclaw skills search "calendar"
openclaw skills search --limit 20 --json
openclaw skills install @owner/<slug>
openclaw skills install @owner/<slug> --version <version>
openclaw skills install <slug>
openclaw skills install <slug> --version <version>
openclaw skills install git:owner/repo
openclaw skills install git:owner/repo@main
openclaw skills install ./path/to/skill --as custom-name
openclaw skills install @owner/<slug> --force
openclaw skills install @owner/<slug> --agent <id>
openclaw skills install @owner/<slug> --global
openclaw skills update @owner/<slug>
openclaw skills update @owner/<slug> --global
openclaw skills install <slug> --force
openclaw skills install <slug> --agent <id>
openclaw skills install <slug> --global
openclaw skills update <slug>
openclaw skills update <slug> --global
openclaw skills update --all
openclaw skills update --all --agent <id>
openclaw skills update --all --global
@@ -64,8 +64,8 @@ openclaw skills workshop reject <proposal-id> --reason "Not reusable"
openclaw skills workshop quarantine <proposal-id> --reason "Needs security review"
```
`search`, `update`, and `verify` use ClawHub directly. `install @owner/<slug>`
installs a ClawHub skill, `install git:owner/repo[@ref]` clones a Git skill, and
`search`, `update`, and `verify` use ClawHub directly. `install <slug>` installs
a ClawHub skill, `install git:owner/repo[@ref]` clones a Git skill, and
`install ./path` copies a local skill directory. By default, `install`, `update`,
and `verify` target the active workspace `skills/` directory; with `--global`,
they target the shared managed skills directory. `list`/`info`/`check` still
@@ -94,15 +94,15 @@ Notes:
`SKILL.md`.
- `install --as <slug>` overrides the inferred slug for Git and local directory
installs.
- `install --version <version>` applies only to ClawHub skill refs.
- `install --version <version>` applies only to ClawHub skill slugs.
- `install --force` overwrites an existing workspace skill folder for the same
slug.
- `--global` targets the shared managed skills directory and cannot be combined
with `--agent <id>`.
- `--agent <id>` targets one configured agent workspace and overrides current
working directory inference.
- `update @owner/<slug>` updates a single tracked skill. Add `--global` to
target the shared managed skills directory instead of the workspace.
- `update <slug>` updates a single tracked skill. Add `--global` to target the
shared managed skills directory instead of the workspace.
- `update --all` updates tracked ClawHub installs in the selected workspace, or
in the shared managed skills directory when combined with `--global`.
- `verify <slug>` prints ClawHub's `clawhub.skill.verify.v1` JSON envelope by

View File

@@ -602,7 +602,7 @@ See [Inferred commitments](/concepts/commitments).
- `remote.transport`: `ssh` (default) or `direct` (ws/wss). For `direct`, `remote.url` must be `wss://` for public hosts; plaintext `ws://` is accepted only for loopback, LAN, link-local, `.local`, `.ts.net`, and Tailscale CGNAT hosts.
- `remote.remotePort`: gateway port on the remote SSH host. Defaults to `18789`; use this when the local tunnel port differs from the remote gateway port.
- `gateway.remote.token` / `.password` are remote-client credential fields. They do not configure gateway auth by themselves.
- `gateway.push.apns.relay.baseUrl`: base HTTPS URL for the external APNs relay used after relay-backed iOS builds publish registrations to the gateway. Public App Store/TestFlight builds use the hosted OpenClaw relay. Custom relay URLs must match a deliberately separate iOS build/deployment path whose relay URL points at that relay.
- `gateway.push.apns.relay.baseUrl`: base HTTPS URL for the external APNs relay used by official/TestFlight iOS builds after they publish relay-backed registrations to the gateway. This URL must match the relay URL compiled into the iOS build.
- `gateway.push.apns.relay.timeoutMs`: gateway-to-relay send timeout in milliseconds. Defaults to `10000`.
- Relay-backed registrations are delegated to a specific gateway identity. The paired iOS app fetches `gateway.identity.get`, includes that identity in the relay registration, and forwards a registration-scoped send grant to the gateway. Another gateway cannot reuse that stored registration.
- `OPENCLAW_APNS_RELAY_BASE_URL` / `OPENCLAW_APNS_RELAY_TIMEOUT_MS`: temporary env overrides for the relay config above.

View File

@@ -337,9 +337,9 @@ candidate contains redacted secret placeholders such as `***`.
</Accordion>
<Accordion title="Enable relay-backed push for official iOS builds">
Relay-backed push for public App Store/TestFlight builds uses the hosted OpenClaw relay: `https://ios-push-relay.openclaw.ai`.
Relay-backed push uses the hosted OpenClaw relay by default: `https://ios-push-relay.openclaw.ai`.
Custom relay deployments require a deliberately separate iOS build/deployment path whose relay URL matches the gateway relay URL. If you are using a custom relay build, set this in gateway config:
To use a custom relay, set this in gateway config:
```json5
{
@@ -369,12 +369,12 @@ candidate contains redacted secret placeholders such as `***`.
- Uses a registration-scoped send grant forwarded by the paired iOS app. The gateway does not need a deployment-wide relay token.
- Binds each relay-backed registration to the gateway identity that the iOS app paired with, so another gateway cannot reuse the stored registration.
- Keeps local/manual iOS builds on direct APNs. Relay-backed sends apply only to official distributed builds that registered through the relay.
- Must match the relay base URL baked into the iOS build, so registration and send traffic reach the same relay deployment.
- Must match the relay base URL baked into the official/TestFlight iOS build, so registration and send traffic reach the same relay deployment.
End-to-end flow:
1. Install an official/TestFlight iOS build.
2. Optional: configure `gateway.push.apns.relay.baseUrl` on the gateway only when using a deliberately separate custom relay build.
2. Optional: configure `gateway.push.apns.relay.baseUrl` on the gateway only when using a custom relay deployment.
3. Pair the iOS app to the gateway and let both node and operator sessions connect.
4. The iOS app fetches the gateway identity, registers with the relay using App Attest plus the app receipt, and then publishes the relay-backed `push.apns.register` payload to the paired gateway.
5. The gateway stores the relay handle and send grant, then uses them for `push.test`, wake nudges, and reconnect wakes.
@@ -387,7 +387,7 @@ candidate contains redacted secret placeholders such as `***`.
Compatibility note:
- `OPENCLAW_APNS_RELAY_BASE_URL` and `OPENCLAW_APNS_RELAY_TIMEOUT_MS` still work as temporary env overrides.
- Custom gateway relay URLs must match the relay base URL baked into the iOS build. The public App Store release lane rejects custom iOS relay URL overrides.
- Custom gateway relay URLs must match the relay base URL baked into the official/TestFlight iOS build.
- `OPENCLAW_APNS_RELAY_ALLOW_HTTP=true` remains a loopback-only development escape hatch; do not persist HTTP relay URLs in config.
See [iOS App](/platforms/ios#relay-backed-push-for-official-builds) for the end-to-end flow and [Authentication and trust flow](/platforms/ios#authentication-and-trust-flow) for the relay security model.

View File

@@ -346,10 +346,10 @@ lives on the [First-run FAQ](/help/faq-first-run).
```bash
openclaw skills search "calendar"
openclaw skills search --limit 20
openclaw skills install @owner/<skill-slug>
openclaw skills install @owner/<skill-slug> --version <version>
openclaw skills install @owner/<skill-slug> --force
openclaw skills install @owner/<skill-slug> --global
openclaw skills install <skill-slug>
openclaw skills install <skill-slug> --version <version>
openclaw skills install <skill-slug> --force
openclaw skills install <skill-slug> --global
openclaw skills update --all
openclaw skills update --all --global
openclaw skills list --eligible
@@ -433,11 +433,11 @@ lives on the [First-run FAQ](/help/faq-first-run).
Install skills:
```bash
openclaw skills install @owner/<skill-slug>
openclaw skills install <skill-slug>
openclaw skills update --all
```
Native installs land in the active workspace `skills/` directory. For shared skills across all local agents, use `openclaw skills install @owner/<skill-slug> --global` (or place them manually in `~/.openclaw/skills/<name>/SKILL.md`). If only some agents should see a shared install, configure `agents.defaults.skills` or `agents.list[].skills`. Some skills expect binaries installed via Homebrew; on Linux that means Linuxbrew (see the Homebrew Linux FAQ entry above). See [Skills](/tools/skills), [Skills config](/tools/skills-config), and [ClawHub](/tools/clawhub).
Native installs land in the active workspace `skills/` directory. For shared skills across all local agents, use `openclaw skills install <slug> --global` (or place them manually in `~/.openclaw/skills/<name>/SKILL.md`). If only some agents should see a shared install, configure `agents.defaults.skills` or `agents.list[].skills`. Some skills expect binaries installed via Homebrew; on Linux that means Linuxbrew (see the Homebrew Linux FAQ entry above). See [Skills](/tools/skills), [Skills config](/tools/skills-config), and [ClawHub](/tools/clawhub).
</Accordion>

View File

@@ -75,9 +75,9 @@ openclaw gateway call node.list --params "{}"
Official distributed iOS builds use the external push relay instead of publishing the raw APNs
token to the gateway.
Official/TestFlight builds from the public App Store release lane use the hosted relay at `https://ios-push-relay.openclaw.ai`.
By default, official/TestFlight builds and gateways use the hosted relay at `https://ios-push-relay.openclaw.ai`.
Custom relay deployments require a deliberately separate iOS build/deployment path whose relay URL matches the gateway relay URL. The public App Store release lane does not accept custom relay URL overrides. If you are using a custom relay build, set the matching gateway relay URL:
Custom relay deployments can override the gateway relay URL:
```json5
{
@@ -100,7 +100,7 @@ How the flow works:
- The iOS app fetches the paired gateway identity and includes it in relay registration, so the relay-backed registration is delegated to that specific gateway.
- The app forwards that relay-backed registration to the paired gateway with `push.apns.register`.
- The gateway uses that stored relay handle for `push.test`, background wakes, and wake nudges.
- Custom gateway relay URLs must match the relay URL baked into the iOS build.
- Custom gateway relay URLs must match the relay URL baked into the official/TestFlight iOS build.
- If the app later connects to a different gateway or a build with a different relay base URL, it refreshes the relay registration instead of reusing the old binding.
What the gateway does **not** need for this path:
@@ -111,7 +111,7 @@ What the gateway does **not** need for this path:
Expected operator flow:
1. Install the official/TestFlight iOS build.
2. Optional: set `gateway.push.apns.relay.baseUrl` on the gateway only when using a deliberately separate custom relay build.
2. Optional: set `gateway.push.apns.relay.baseUrl` on the gateway only when using a custom relay deployment.
3. Pair the app to the gateway and let it finish connecting.
4. The app publishes `push.apns.register` automatically after it has an APNs token, the operator session is connected, and relay registration succeeds.
5. After that, `push.test`, reconnect wakes, and wake nudges can use the stored relay-backed registration.
@@ -130,7 +130,7 @@ compatible but does not count as a durable last-seen update.
Compatibility note:
- `OPENCLAW_APNS_RELAY_BASE_URL` still works as a temporary env override for the gateway.
- The public App Store release lane rejects `OPENCLAW_PUSH_RELAY_BASE_URL` for iOS builds.
- `OPENCLAW_PUSH_RELAY_BASE_URL` still works as a temporary env override for official/TestFlight iOS builds.
## Authentication and trust flow

View File

@@ -46,10 +46,8 @@ The default model is `embeddinggemma-300m-qat-Q8_0.gguf`. You can also point
## Native Runtime
Use Node 24 for the smoothest native install path. Source checkouts leave the
native build unapproved by default so normal workspace installs do not compile
llama.cpp. When you actually use local GGUF embeddings from source, approve and
rebuild the provider runtime:
Use Node 24 for the smoothest native install path. Source checkouts using pnpm
may need to approve and rebuild the native dependency:
```bash
pnpm approve-builds

View File

@@ -191,7 +191,6 @@ or npm install metadata. Those belong in your plugin code and `package.json`.
| `skills` | No | `string[]` | Skill directories to load, relative to the plugin root. |
| `name` | No | `string` | Human-readable plugin name. |
| `description` | No | `string` | Short summary shown in plugin surfaces. |
| `icon` | No | `string` | HTTPS image URL for marketplace/catalog cards. ClawHub accepts any valid `https://` URL and falls back to the default plugin icon when this is omitted or invalid. |
| `version` | No | `string` | Informational plugin version. |
| `uiHints` | No | `Record<string, object>` | UI labels, placeholders, and sensitivity hints for config fields. |

View File

@@ -67,7 +67,7 @@ Wraps papla.media TTS and sends results as Telegram voice notes (no annoying aut
<img src="/assets/showcase/papla-tts.jpg" alt="Telegram voice note output from TTS" />
</Card>
<Card title="CodexMonitor" icon="eye" href="https://clawhub.ai/odrobnik/skills/codexmonitor">
<Card title="CodexMonitor" icon="eye" href="https://clawhub.ai/odrobnik/codexmonitor">
**@odrobnik** • `devtools` `codex` `brew`
Homebrew-installed helper to list, inspect, and watch local OpenAI Codex sessions (CLI + VS Code).
@@ -75,7 +75,7 @@ Homebrew-installed helper to list, inspect, and watch local OpenAI Codex session
<img src="/assets/showcase/codexmonitor.png" alt="CodexMonitor on ClawHub" />
</Card>
<Card title="Bambu 3D Printer Control" icon="print" href="https://clawhub.ai/tobiasbischoff/skills/bambu-cli">
<Card title="Bambu 3D Printer Control" icon="print" href="https://clawhub.ai/tobiasbischoff/bambu-cli">
**@tobiasbischoff** • `hardware` `3d-printing` `skill`
Control and troubleshoot BambuLab printers: status, jobs, camera, AMS, calibration, and more.
@@ -83,7 +83,7 @@ Control and troubleshoot BambuLab printers: status, jobs, camera, AMS, calibrati
<img src="/assets/showcase/bambu-cli.png" alt="Bambu CLI skill on ClawHub" />
</Card>
<Card title="Vienna transport (Wiener Linien)" icon="train" href="https://clawhub.ai/hjanuschka/skills/wienerlinien">
<Card title="Vienna transport (Wiener Linien)" icon="train" href="https://clawhub.ai/hjanuschka/wienerlinien">
**@hjanuschka** • `travel` `transport` `skill`
Real-time departures, disruptions, elevator status, and routing for Vienna's public transport.
@@ -97,7 +97,7 @@ Real-time departures, disruptions, elevator status, and routing for Vienna's pub
Automated UK school meal booking via ParentPay. Uses mouse coordinates for reliable table cell clicking.
</Card>
<Card title="R2 upload (Send Me My Files)" icon="cloud-arrow-up" href="https://clawhub.ai/julianengel/skills/r2-upload">
<Card title="R2 upload (Send Me My Files)" icon="cloud-arrow-up" href="https://clawhub.ai/skills/r2-upload">
**@julianengel** • `files` `r2` `presigned-urls`
Upload to Cloudflare R2/S3 and generate secure presigned download links. Useful for remote OpenClaw instances.
@@ -267,7 +267,7 @@ Speech-first entry points, phone bridges, and transcription-heavy workflows.
Vapi voice assistant to OpenClaw HTTP bridge. Near real-time phone calls with your agent.
</Card>
<Card title="OpenRouter transcription" icon="microphone" href="https://clawhub.ai/obviyus/skills/openrouter-transcribe">
<Card title="OpenRouter transcription" icon="microphone" href="https://clawhub.ai/obviyus/openrouter-transcribe">
**@obviyus** • `transcription` `multilingual` `skill`
Multi-lingual audio transcription via OpenRouter (Gemini, and more). Available on ClawHub.
@@ -289,8 +289,8 @@ Packaging, deployment, and integrations that make OpenClaw easier to run and ext
OpenClaw gateway running on Home Assistant OS with SSH tunnel support and persistent state.
</Card>
<Card title="Home Assistant skill" icon="toggle-on" href="https://clawhub.ai/homeofe/skills/openclaw-homeassistant">
**@homeofe** • `homeassistant` `skill` `automation`
<Card title="Home Assistant skill" icon="toggle-on" href="https://clawhub.ai/skills/homeassistant">
**ClawHub**`homeassistant` `skill` `automation`
Control and automate Home Assistant devices via natural language.
@@ -303,8 +303,8 @@ Control and automate Home Assistant devices via natural language.
Batteries-included nixified OpenClaw configuration for reproducible deployments.
</Card>
<Card title="CalDAV calendar" icon="calendar" href="https://clawhub.ai/asleep123/skills/caldav-calendar">
**@asleep123** • `calendar` `caldav` `skill`
<Card title="CalDAV calendar" icon="calendar" href="https://clawhub.ai/skills/caldav-calendar">
**ClawHub**`calendar` `caldav` `skill`
Calendar skill using khal and vdirsyncer. Self-hosted calendar integration.

View File

@@ -225,7 +225,7 @@ See [Skill Workshop](/tools/skill-workshop) for the full proposal lifecycle.
metadata:
```bash
openclaw skills install @openclaw/clawhub-publish
openclaw skills install clawhub-publish
```
</Step>

View File

@@ -145,12 +145,12 @@ publish and sync.
| Action | Command |
| ---------------------------------- | ------------------------------------------------------ |
| Install a skill into the workspace | `openclaw skills install @owner/<slug>` |
| Install a skill into the workspace | `openclaw skills install <slug>` |
| Install from a Git repository | `openclaw skills install git:owner/repo@ref` |
| Install a local skill directory | `openclaw skills install ./path/to/skill --as my-tool` |
| Install for all local agents | `openclaw skills install @owner/<slug> --global` |
| Install for all local agents | `openclaw skills install <slug> --global` |
| Update all workspace skills | `openclaw skills update --all` |
| Update a shared managed skill | `openclaw skills update @owner/<slug> --global` |
| Update a shared managed skill | `openclaw skills update <slug> --global` |
| Update all shared managed skills | `openclaw skills update --all --global` |
| Verify a skill's trust envelope | `openclaw skills verify <slug>` |
| Print the generated Skill Card | `openclaw skills verify <slug> --card` |
@@ -179,7 +179,7 @@ publish and sync.
with detail pages for VirusTotal, ClawScan, and static analysis. The
command exits non-zero when ClawHub marks verification as failed. Publishers
recover false positives through the ClawHub dashboard or
`clawhub skill rescan @owner/<slug>`.
`clawhub skill rescan <slug>`.
</Accordion>
<Accordion title="Private archive installs">

View File

@@ -1,6 +1,5 @@
{
"id": "alibaba",
"icon": "https://cdn.simpleicons.org/alibabacloud/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "anthropic-vertex",
"name": "Anthropic Vertex",
"description": "OpenClaw Anthropic Vertex provider plugin for Claude models on Google Vertex AI.",
"icon": "https://cdn.simpleicons.org/anthropic/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "anthropic",
"icon": "https://cdn.simpleicons.org/anthropic/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "brave",
"name": "Brave",
"description": "OpenClaw Brave Search provider plugin for web search.",
"icon": "https://cdn.simpleicons.org/brave/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "cloudflare-ai-gateway",
"icon": "https://cdn.simpleicons.org/cloudflare/111111",
"activation": {
"onStartup": false
},

View File

@@ -1102,6 +1102,362 @@ describe("createCodexDynamicToolBridge", () => {
]);
});
it("marks delivered message-tool-only source replies as terminal", async () => {
const bridge = createBridgeWithToolResult(
"message",
textToolResult("Sent.", { messageId: "imessage-6264" }),
{ sourceReplyDeliveryMode: "message_tool_only" },
);
const result = await handleMessageToolCall(bridge, {
action: "send",
message: "visible reply",
});
expect(result).toEqual(expectInputText("Sent."));
expect(result.terminate).toBe(true);
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(true);
expect(Object.keys(result)).not.toContain("terminate");
});
it("keeps message-tool-only source replies terminal when middleware redacts receipt details", async () => {
const registry = createEmptyPluginRegistry();
registry.agentToolResultMiddlewares.push({
pluginId: "receipt-redactor",
pluginName: "Receipt redactor",
rawHandler: () => undefined,
handler: (event: { result: AgentToolResult<unknown> }) => ({
result: {
content: event.result.content,
details: { redacted: true },
},
}),
runtimes: ["codex"],
source: "test",
});
setActivePluginRegistry(registry);
const bridge = createBridgeWithToolResult(
"message",
textToolResult("Sent.", {
receipt: {
primaryPlatformMessageId: "imessage-6264",
platformMessageIds: ["imessage-6264"],
},
}),
{ sourceReplyDeliveryMode: "message_tool_only" },
);
const result = await handleMessageToolCall(bridge, {
action: "send",
message: "visible reply",
});
expect(result).toEqual(expectInputText("Sent."));
expect(result.terminate).toBe(true);
expect(Object.keys(result)).not.toContain("terminate");
});
it("does not treat target telemetry alone as delivered message-tool-only source reply evidence", async () => {
const bridge = createBridgeWithToolResult("message", textToolResult("Sent."), {
sourceReplyDeliveryMode: "message_tool_only",
currentChannelProvider: "imessage",
currentChannelId: "chat-1",
});
const result = await handleMessageToolCall(bridge, {
action: "send",
message: "visible reply",
});
expect(result).toEqual(expectInputText("Sent."));
expect(bridge.telemetry.messagingToolSentTargets).toEqual([
expect.objectContaining({
tool: "message",
provider: "imessage",
to: "chat-1",
text: "visible reply",
}),
]);
expect(result.terminate).toBeUndefined();
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(false);
});
it("keeps message-tool-only source replies terminal for explicit current source routes", async () => {
const bridge = createBridgeWithToolResult(
"message",
textToolResult("Sent.", { ok: true, messageId: "imessage-853" }),
{
sourceReplyDeliveryMode: "message_tool_only",
currentChannelProvider: "imessage",
currentChannelId: "imessage:+12069106512",
currentMessagingTarget: "+12069106512",
},
);
const result = await handleMessageToolCall(bridge, {
action: "reply",
channel: "imessage",
target: "+12069106512",
messageId: "853",
message: "visible reply",
buttons: [],
});
expect(result).toEqual(expectInputText("Sent."));
expect(result.terminate).toBe(true);
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(true);
expect(Object.keys(result)).not.toContain("terminate");
});
it("keeps message-tool-only source replies terminal when the reply receipt matches the current message id", async () => {
const bridge = createBridgeWithToolResult(
"message",
textToolResult("Sent.", {
ok: true,
messageId: "provider-message-1",
repliedTo: "provider-guid-857",
}),
{
sourceReplyDeliveryMode: "message_tool_only",
currentChannelProvider: "imessage",
currentChannelId: "imessage:any;-;+12069106512",
currentMessageId: "provider-guid-857",
},
);
const result = await handleMessageToolCall(bridge, {
action: "reply",
channel: "imessage",
target: "+12069106512",
messageId: "857",
message: "visible reply",
buttons: [],
});
expect(result).toEqual(expectInputText("Sent."));
expect(bridge.telemetry.messagingToolSentTargets).toEqual([
expect.objectContaining({
tool: "message",
provider: "imessage",
to: "+12069106512",
text: "visible reply",
}),
]);
expect(result.terminate).toBe(true);
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(true);
expect(Object.keys(result)).not.toContain("terminate");
});
it("keeps message-tool-only source replies terminal when a text receipt matches the current message id", async () => {
const receiptText = JSON.stringify({
ok: true,
messageId: "provider-message-1",
repliedTo: "provider-guid-861",
});
const bridge = createBridgeWithToolResult("message", textToolResult(receiptText), {
sourceReplyDeliveryMode: "message_tool_only",
currentChannelProvider: "imessage",
currentChannelId: "imessage:any;-;+12069106512",
currentMessageId: "provider-guid-861",
});
const result = await handleMessageToolCall(bridge, {
action: "reply",
channel: "imessage",
target: "+12069106512",
messageId: "861",
message: "visible reply",
buttons: [],
});
expect(result).toEqual(expectInputText(receiptText));
expect(result.terminate).toBe(true);
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(true);
expect(Object.keys(result)).not.toContain("terminate");
});
it("keeps message-tool-only source replies terminal for explicit native target segments", async () => {
const bridge = createBridgeWithToolResult("message", textToolResult("Sent.", { ok: true }), {
sourceReplyDeliveryMode: "message_tool_only",
currentChannelProvider: "imessage",
currentChannelId: "imessage:any;-;+12069106512",
});
const result = await handleMessageToolCall(bridge, {
action: "reply",
channel: "imessage",
target: "+12069106512",
messageId: "863",
message: "visible reply",
buttons: [],
});
expect(result).toEqual(expectInputText("Sent."));
expect(result.terminate).toBe(true);
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(true);
expect(Object.keys(result)).not.toContain("terminate");
});
it("keeps message-tool-only source replies terminal when the provider is only in the current channel id", async () => {
const bridge = createBridgeWithToolResult("message", textToolResult("Sent.", { ok: true }), {
sourceReplyDeliveryMode: "message_tool_only",
currentChannelId: "imessage:any;-;+12069106512",
});
const result = await handleMessageToolCall(bridge, {
action: "reply",
channel: "imessage",
target: "+12069106512",
messageId: "865",
message: "visible reply",
buttons: [],
});
expect(result).toEqual(expectInputText("Sent."));
expect(result.terminate).toBe(true);
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(true);
expect(Object.keys(result)).not.toContain("terminate");
});
it("records message-tool-owned terminal replies as delivered source replies", async () => {
const bridge = createBridgeWithToolResult(
"message",
{
...textToolResult("Sent.", { ok: true }),
terminate: true,
} as AgentToolResult<unknown>,
{ sourceReplyDeliveryMode: "message_tool_only" },
);
const result = await handleMessageToolCall(bridge, {
action: "reply",
channel: "imessage",
target: "+12069106512",
messageId: "867",
message: "visible reply",
buttons: [],
});
expect(result).toEqual(expectInputText("Sent."));
expect(result.terminate).toBe(true);
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(true);
expect(Object.keys(result)).not.toContain("terminate");
});
it("does not treat bare send telemetry as delivered message-tool-only source reply evidence", async () => {
const bridge = createBridgeWithToolResult("message", textToolResult("Sent."), {
sourceReplyDeliveryMode: "message_tool_only",
});
const result = await handleMessageToolCall(bridge, {
action: "send",
message: "visible reply",
});
expect(result).toEqual(expectInputText("Sent."));
expect(bridge.telemetry.didSendViaMessagingTool).toBe(true);
expect(result.terminate).toBeUndefined();
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(false);
});
it("does not let prior message-send telemetry terminate a later non-delivery tool result", async () => {
const execute = vi
.fn()
.mockResolvedValueOnce(textToolResult("Sent.", { messageId: "source-reply-1" }))
.mockResolvedValueOnce(textToolResult("No message sent.", { ok: true }));
const bridge = createCodexDynamicToolBridge({
tools: [createTool({ name: "message", execute })],
signal: new AbortController().signal,
hookContext: { sourceReplyDeliveryMode: "message_tool_only" },
});
const firstResult = await handleMessageToolCall(bridge, {
action: "send",
message: "visible reply",
});
const secondResult = await bridge.handleToolCall({
threadId: "thread-1",
turnId: "turn-1",
callId: "call-2",
namespace: null,
tool: "message",
arguments: { action: "inspect" },
});
expect(firstResult.terminate).toBe(true);
expect(bridge.telemetry.didSendViaMessagingTool).toBe(true);
expect(secondResult).toEqual(expectInputText("No message sent."));
expect(secondResult.terminate).toBeUndefined();
});
it("does not mark explicit message-tool sends as terminal source replies", async () => {
const bridge = createBridgeWithToolResult(
"message",
textToolResult("Sent.", { messageId: "other-chat-message" }),
{ sourceReplyDeliveryMode: "message_tool_only" },
);
const result = await handleMessageToolCall(bridge, {
action: "send",
target: "channel:other",
message: "cross-channel reply",
});
expect(result).toEqual(expectInputText("Sent."));
expect(result.terminate).toBeUndefined();
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(false);
});
it("does not mark mismatched explicit message-tool sends as terminal source replies", async () => {
const bridge = createBridgeWithToolResult("message", textToolResult("Sent."), {
sourceReplyDeliveryMode: "message_tool_only",
currentChannelProvider: "imessage",
currentChannelId: "imessage:+12069106512",
currentMessagingTarget: "+12069106512",
});
const result = await handleMessageToolCall(bridge, {
action: "reply",
channel: "slack",
target: "+12069106512",
messageId: "853",
message: "cross-provider reply",
});
expect(result).toEqual(expectInputText("Sent."));
expect(result.terminate).toBeUndefined();
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(false);
});
it("does not let matching reply receipts override explicit non-source routes", async () => {
const bridge = createBridgeWithToolResult(
"message",
textToolResult("Sent.", {
ok: true,
messageId: "other-chat-message",
repliedTo: "provider-guid-853",
}),
{
sourceReplyDeliveryMode: "message_tool_only",
currentChannelProvider: "imessage",
currentChannelId: "imessage:+12069106512",
currentMessagingTarget: "+12069106512",
currentMessageId: "provider-guid-853",
},
);
const result = await handleMessageToolCall(bridge, {
action: "reply",
channel: "imessage",
target: "other-chat",
message: "cross-channel reply",
});
expect(result).toEqual(expectInputText("Sent."));
expect(result.terminate).toBeUndefined();
expect(bridge.telemetry.didDeliverSourceReplyViaMessageTool).toBe(false);
});
it("does not record messaging side effects when the send fails", async () => {
const tool = createTool({
name: "message",

View File

@@ -18,6 +18,7 @@ import {
getChannelAgentToolMeta,
getPluginToolMeta,
type EmbeddedRunAttemptParams,
isDeliveredMessageToolOnlySourceReplyResult,
isReplaySafeToolCall,
isToolWrappedWithBeforeToolCallHook,
isToolResultError,
@@ -63,9 +64,11 @@ type CodexDynamicToolHookContext = {
currentChannelProvider?: string;
currentChannelId?: string;
currentMessagingTarget?: string;
currentMessageId?: string | number;
currentThreadId?: string;
replyToMode?: "off" | "first" | "all" | "batched";
hasRepliedRef?: { value: boolean };
sourceReplyDeliveryMode?: EmbeddedRunAttemptParams["sourceReplyDeliveryMode"];
onToolOutcome?: EmbeddedRunAttemptParams["onToolOutcome"];
allocateToolOutcomeOrdinal?: EmbeddedRunAttemptParams["allocateToolOutcomeOrdinal"];
};
@@ -100,6 +103,166 @@ function applyCurrentMessageProvider(
return { ...args, provider };
}
function normalizeRouteToken(value: string | number | undefined): string | undefined {
if (typeof value === "number") {
return Number.isFinite(value) ? String(value) : undefined;
}
const normalized = value?.trim().toLowerCase();
return normalized ? normalized : undefined;
}
function sourceRouteTokens(hookContext: CodexDynamicToolHookContext | undefined): Set<string> {
const tokens = new Set<string>();
const currentTarget = normalizeRouteToken(hookContext?.currentMessagingTarget);
const currentChannel = normalizeRouteToken(hookContext?.currentChannelId);
const currentProvider = normalizeRouteToken(hookContext?.currentChannelProvider);
if (currentTarget) {
tokens.add(currentTarget);
}
if (currentChannel) {
tokens.add(currentChannel);
}
const channelPrefixIndex = currentChannel?.indexOf(":") ?? -1;
if (channelPrefixIndex >= 0 && currentChannel) {
const unprefixedChannel = currentChannel.slice(channelPrefixIndex + 1);
if (unprefixedChannel) {
tokens.add(unprefixedChannel);
for (const segment of unprefixedChannel.split(/[;,]/u)) {
const token = normalizeRouteToken(segment);
if (token) {
tokens.add(token);
}
}
}
}
if (currentProvider && currentChannel?.startsWith(`${currentProvider}:`)) {
const unprefixedChannel = currentChannel.slice(currentProvider.length + 1);
if (unprefixedChannel) {
tokens.add(unprefixedChannel);
}
}
return tokens;
}
function routeTokenMatchesSource(
token: string | undefined,
hookContext: CodexDynamicToolHookContext | undefined,
): boolean {
const normalized = normalizeRouteToken(token);
return normalized !== undefined && sourceRouteTokens(hookContext).has(normalized);
}
function routeProviderMatchesSource(
provider: string | undefined,
hookContext: CodexDynamicToolHookContext | undefined,
): boolean {
const normalized = normalizeRouteToken(provider);
if (!normalized) {
return false;
}
const currentProvider = normalizeRouteToken(hookContext?.currentChannelProvider);
const currentChannel = normalizeRouteToken(hookContext?.currentChannelId);
return currentProvider === normalized || currentChannel?.startsWith(`${normalized}:`) === true;
}
function routeTokenMatchesCurrentMessage(
token: string | undefined,
hookContext: CodexDynamicToolHookContext | undefined,
): boolean {
const normalized = normalizeRouteToken(token);
return (
normalized !== undefined && normalized === normalizeRouteToken(hookContext?.currentMessageId)
);
}
function replyReceiptMatchesCurrentMessage(
value: unknown,
hookContext: CodexDynamicToolHookContext | undefined,
depth = 0,
): boolean {
if (depth > 4 || value === null) {
return false;
}
if (typeof value === "string") {
const trimmed = value.trim();
if (!trimmed || !["{", "["].includes(trimmed[0] ?? "")) {
return false;
}
try {
return replyReceiptMatchesCurrentMessage(JSON.parse(trimmed), hookContext, depth + 1);
} catch {
return false;
}
}
if (typeof value !== "object") {
return false;
}
if (Array.isArray(value)) {
return value.some((item) => replyReceiptMatchesCurrentMessage(item, hookContext, depth + 1));
}
const record = value as Record<string, unknown>;
for (const key of ["repliedTo", "replyTo", "replyToId", "replyToIdFull"]) {
if (
routeTokenMatchesCurrentMessage(
typeof record[key] === "string" ? record[key] : undefined,
hookContext,
)
) {
return true;
}
}
for (const key of [
"content",
"details",
"payload",
"receipt",
"result",
"results",
"sendResult",
"text",
]) {
if (replyReceiptMatchesCurrentMessage(record[key], hookContext, depth + 1)) {
return true;
}
}
return false;
}
function hasExplicitNonSourceMessageRoute(
args: Record<string, unknown>,
hookContext: CodexDynamicToolHookContext | undefined,
messagingTarget: MessagingToolSend | undefined,
): boolean {
const currentProvider = normalizeRouteToken(hookContext?.currentChannelProvider);
for (const key of EXPLICIT_MESSAGE_PROVIDER_KEYS) {
const provider = normalizeRouteToken(typeof args[key] === "string" ? args[key] : undefined);
if (
provider &&
currentProvider !== provider &&
!routeProviderMatchesSource(provider, hookContext)
) {
return true;
}
}
const targetValues = [
...EXPLICIT_MESSAGE_TARGET_KEYS.map((key) =>
typeof args[key] === "string" ? args[key] : undefined,
),
...(Array.isArray(args.targets)
? args.targets.map((value) => (typeof value === "string" ? value : undefined))
: []),
].filter((value): value is string => normalizeRouteToken(value) !== undefined);
if (targetValues.length === 0) {
return false;
}
if (targetValues.some((value) => !routeTokenMatchesSource(value, hookContext))) {
return true;
}
return (
messagingTarget?.to !== undefined && !routeTokenMatchesSource(messagingTarget.to, hookContext)
);
}
/** Runtime bridge returned to Codex app-server attempt code. */
export type CodexDynamicToolBridge = {
availableSpecs: CodexDynamicToolSpec[];
@@ -114,6 +277,7 @@ export type CodexDynamicToolBridge = {
) => Promise<CodexDynamicToolCallResponse>;
telemetry: {
didSendViaMessagingTool: boolean;
didDeliverSourceReplyViaMessageTool: boolean;
messagingToolSentTexts: string[];
messagingToolSentMediaUrls: string[];
messagingToolSentTargets: MessagingToolSend[];
@@ -132,6 +296,8 @@ export const CODEX_OPENCLAW_DYNAMIC_TOOL_NAMESPACE = "openclaw";
// Keep OpenClaw session spawning searchable in Codex mode so Codex's native
// spawn_agent remains the primary Codex subagent surface.
const ALWAYS_DIRECT_DYNAMIC_TOOL_NAMES = new Set(["sessions_yield"]);
const EXPLICIT_MESSAGE_PROVIDER_KEYS = ["channel", "provider"];
const EXPLICIT_MESSAGE_TARGET_KEYS = ["target", "to", "channelId"];
const DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS = 16_000;
/**
@@ -176,6 +342,7 @@ export function createCodexDynamicToolBridge(params: {
emitQuarantinedDynamicToolDiagnostics(quarantinedTools, params.hookContext);
const telemetry: CodexDynamicToolBridge["telemetry"] = {
didSendViaMessagingTool: false,
didDeliverSourceReplyViaMessageTool: false,
messagingToolSentTexts: [],
messagingToolSentMediaUrls: [],
messagingToolSentTargets: [],
@@ -333,10 +500,9 @@ export function createCodexDynamicToolBridge(params: {
executedArgs,
params.hookContext?.currentChannelProvider,
);
const messagingTarget =
isMessagingTool(toolName) && isMessagingToolSendAction(toolName, executedArgs)
? extractMessagingToolSend(toolName, messagingTelemetryArgs, messagingContext)
: undefined;
const messagingTarget = isMessagingTool(toolName)
? extractMessagingToolSend(toolName, messagingTelemetryArgs, messagingContext)
: undefined;
const confirmedMessagingTarget =
!rawIsError && messagingTarget
? extractMessagingToolSendResult(messagingTarget, telemetryRawResult)
@@ -358,12 +524,46 @@ export function createCodexDynamicToolBridge(params: {
},
terminalType,
);
const blocksSourceReplyTermination = hasExplicitNonSourceMessageRoute(
executedArgs,
params.hookContext,
confirmedMessagingTarget,
);
const deliveredSourceReply = isDeliveredMessageToolOnlySourceReplyResult({
sourceReplyDeliveryMode: params.hookContext?.sourceReplyDeliveryMode,
toolName,
args: executedArgs,
result,
hookResult: rawResult,
isError: resultIsError,
allowExplicitSourceRoute: !blocksSourceReplyTermination,
});
const receiptConfirmedSourceReply =
params.hookContext?.sourceReplyDeliveryMode === "message_tool_only" &&
toolName === "message" &&
normalizeRouteToken(
typeof executedArgs.action === "string" ? executedArgs.action : undefined,
) === "reply" &&
!resultIsError &&
!blocksSourceReplyTermination &&
(replyReceiptMatchesCurrentMessage(rawResult, params.hookContext) ||
replyReceiptMatchesCurrentMessage(result, params.hookContext));
const toolConfirmedSourceReply =
params.hookContext?.sourceReplyDeliveryMode === "message_tool_only" &&
toolName === "message" &&
!resultIsError &&
(rawResult.terminate === true || result.terminate === true);
if (deliveredSourceReply || receiptConfirmedSourceReply || toolConfirmedSourceReply) {
telemetry.didDeliverSourceReplyViaMessageTool = true;
}
withDynamicToolTermination(
response,
rawResult.terminate === true ||
result.terminate === true ||
isToolResultYield(rawResult) ||
isToolResultYield(result),
isToolResultYield(result) ||
deliveredSourceReply ||
receiptConfirmedSourceReply,
);
const asyncStarted =
isAsyncStartedToolResult(rawResult) || isAsyncStartedToolResult(result);
@@ -803,7 +1003,7 @@ function collectToolTelemetry(params: {
}
if (
!isMessagingTool(params.toolName) ||
!isMessagingToolSendAction(params.toolName, params.args)
(!isMessagingToolSendAction(params.toolName, params.args) && !params.messagingTarget)
) {
return;
}

View File

@@ -794,6 +794,19 @@ describe("CodexAppServerEventProjector", () => {
expect(result.toolMediaUrls).toStrictEqual([]);
});
it("propagates message-tool-only source reply delivery telemetry", async () => {
const projector = await createProjector();
const result = projector.buildResult({
...buildEmptyToolTelemetry(),
didSendViaMessagingTool: true,
didDeliverSourceReplyViaMessageTool: true,
});
expect(result.didSendViaMessagingTool).toBe(true);
expect(result.didDeliverSourceReplyViaMessageTool).toBe(true);
});
it("does not promote repeated tool progress text to the final assistant reply", async () => {
const onToolResult = vi.fn();
const projector = await createProjector({

View File

@@ -53,6 +53,7 @@ import { attachCodexMirrorIdentity, buildCodexUserPromptMessage } from "./transc
export type CodexAppServerToolTelemetry = {
didSendViaMessagingTool: boolean;
didDeliverSourceReplyViaMessageTool?: boolean;
messagingToolSentTexts: string[];
messagingToolSentMediaUrls: string[];
messagingToolSentTargets: MessagingToolSend[];
@@ -412,6 +413,8 @@ export class CodexAppServerEventProjector {
currentAttemptAssistant,
...(this.lastNativeToolError ? { lastToolError: this.lastNativeToolError } : {}),
didSendViaMessagingTool: toolTelemetry.didSendViaMessagingTool,
didDeliverSourceReplyViaMessageTool:
toolTelemetry.didDeliverSourceReplyViaMessageTool === true,
messagingToolSentTexts: toolTelemetry.messagingToolSentTexts,
messagingToolSentMediaUrls: toolTelemetry.messagingToolSentMediaUrls,
messagingToolSentTargets: toolTelemetry.messagingToolSentTargets,

View File

@@ -841,9 +841,11 @@ export async function runCodexAppServerAttempt(
currentChannelProvider: resolveCodexMessageToolProvider(params),
currentChannelId: params.currentChannelId,
currentMessagingTarget: params.currentMessagingTarget,
currentMessageId: params.currentMessageId,
currentThreadId: params.currentThreadTs,
replyToMode: params.replyToMode,
hasRepliedRef: params.hasRepliedRef,
sourceReplyDeliveryMode: params.sourceReplyDeliveryMode,
onToolOutcome: onCodexToolOutcome,
allocateToolOutcomeOrdinal: allocateCodexToolOutcomeOrdinal,
},

View File

@@ -1,6 +1,5 @@
{
"id": "copilot-proxy",
"icon": "https://cdn.simpleicons.org/githubcopilot/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "copilot",
"name": "GitHub Copilot agent runtime",
"description": "Registers the GitHub Copilot agent runtime.",
"icon": "https://cdn.simpleicons.org/githubcopilot/111111",
"version": "2026.6.2",
"activation": {
"onStartup": false,

View File

@@ -1,6 +1,5 @@
{
"id": "deepgram",
"icon": "https://cdn.simpleicons.org/deepgram/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "deepseek",
"icon": "https://cdn.simpleicons.org/deepseek/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "discord",
"name": "Discord",
"description": "OpenClaw Discord channel plugin for channels, DMs, commands, and app events.",
"icon": "https://cdn.simpleicons.org/discord/111111",
"skills": ["./skills"],
"activation": {
"onStartup": false

View File

@@ -1,6 +1,5 @@
{
"id": "duckduckgo",
"icon": "https://cdn.simpleicons.org/duckduckgo/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "elevenlabs",
"icon": "https://cdn.simpleicons.org/elevenlabs/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "google-meet",
"name": "Google Meet",
"description": "OpenClaw Google Meet participant plugin for joining calls through Chrome or Twilio transports.",
"icon": "https://cdn.simpleicons.org/googlemeet/111111",
"enabledByDefault": false,
"commandAliases": [{ "name": "googlemeet" }],
"activation": {

View File

@@ -1,6 +1,5 @@
{
"id": "google",
"icon": "https://cdn.simpleicons.org/google/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "googlechat",
"name": "Google Chat",
"description": "OpenClaw Google Chat channel plugin for spaces and direct messages.",
"icon": "https://cdn.simpleicons.org/googlechat/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "huggingface",
"icon": "https://cdn.simpleicons.org/huggingface/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "imessage",
"icon": "https://cdn.simpleicons.org/imessage/111111",
"activation": {
"onStartup": false
},

View File

@@ -68,6 +68,8 @@ export class IMessageRpcClient {
private readonly closed: Promise<void>;
private closedResolve: (() => void) | null = null;
private child: ChildProcessWithoutNullStreams | null = null;
private closeError: Error | null = null;
private stopping = false;
private stdoutBuffer = "";
private readonly stdoutDecoder = new StringDecoder("utf8");
private nextId = 1;
@@ -119,7 +121,9 @@ export class IMessageRpcClient {
});
child.on("error", (err) => {
this.failAll(err instanceof Error ? err : new Error(String(err)));
const closeError = err instanceof Error ? err : new Error(String(err));
this.closeError = closeError;
this.failAll(closeError);
this.closedResolve?.();
});
@@ -133,7 +137,9 @@ export class IMessageRpcClient {
if (this.child === child) {
this.flushStdoutBuffer();
}
this.failAll(this.buildCloseError(code, signal));
const closeError = this.buildCloseError(code, signal);
this.closeError = closeError;
this.failAll(closeError);
this.closedResolve?.();
});
}
@@ -142,6 +148,7 @@ export class IMessageRpcClient {
if (!this.child) {
return;
}
this.stopping = true;
this.stdoutBuffer = "";
this.stdoutDecoder.end();
this.child.stdin?.end();
@@ -163,6 +170,9 @@ export class IMessageRpcClient {
async waitForClose(): Promise<void> {
await this.closed;
if (this.closeError && !this.stopping) {
throw this.closeError;
}
}
async request<T = unknown>(

View File

@@ -3,6 +3,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { GetReplyOptions, MsgContext } from "openclaw/plugin-sdk/reply-runtime";
import { setVerbose } from "openclaw/plugin-sdk/runtime-env";
import type { waitForTransportReady } from "openclaw/plugin-sdk/transport-ready-runtime";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { createIMessageRpcClient } from "./client.js";
@@ -128,14 +129,86 @@ describe("iMessage monitor last-route updates", () => {
});
afterEach(() => {
setVerbose(false);
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllEnvs();
for (const dir of tempDirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("handles watch replay messages before watch.subscribe returns", async () => {
setCachedIMessagePrivateApiStatus("imsg", {
available: true,
v2Ready: true,
selectors: {},
rpcMethods: ["watch.subscribe", "send", "typing"],
});
let onNotification: ((message: { method: string; params: unknown }) => void) | undefined;
const client = {
request: vi.fn(async (method: string) => {
if (method === "watch.subscribe") {
onNotification?.({
method: "message",
params: {
id: 321,
guid: "replay-guid",
chat_id: 456,
sender: "+15550001111",
is_from_me: false,
text: "replayed during subscribe",
is_group: false,
created_at: new Date().toISOString(),
},
});
await Promise.resolve();
await Promise.resolve();
return { subscription: 1 };
}
return { ok: true };
}),
waitForClose: vi.fn(async () => {}),
stop: vi.fn(async () => {}),
};
createIMessageRpcClientMock.mockImplementation(async (params) => {
if (!params?.onNotification) {
throw new Error("expected iMessage notification handler");
}
onNotification = params.onNotification;
return client as never;
});
const runtime = { error: vi.fn(), exit: vi.fn(), log: vi.fn() };
await monitorIMessageProvider({
config: {
channels: {
imessage: {
dmPolicy: "allowlist",
allowFrom: ["+15550001111"],
sendReadReceipts: false,
},
},
messages: { inbound: { debounceMs: 0 } },
session: { mainKey: "main" },
} as never,
runtime,
});
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
expect(
runtime.error.mock.calls.some(([message]) =>
String(message).includes("imessage monitor client not initialized"),
),
).toBe(false);
});
it("keeps native typing alive when tool activity arrives before reply text", async () => {
setVerbose(true);
const consoleLogMock = vi.spyOn(console, "log").mockImplementation(() => {});
setCachedIMessagePrivateApiStatus("imsg", {
available: true,
v2Ready: true,
@@ -145,6 +218,13 @@ describe("iMessage monitor last-route updates", () => {
dispatchInboundMessageMock.mockImplementationOnce(async (params) => {
expect(params.replyOptions?.suppressDefaultToolProgressMessages).toBe(true);
expect(params.replyOptions?.allowProgressCallbacksWhenSourceDeliverySuppressed).toBe(true);
expect(typeof params.replyOptions?.onAgentRunStart).toBe("function");
expect(typeof params.replyOptions?.onAgentModelCallStart).toBe("function");
expect(typeof params.replyOptions?.onAgentModelPreparationPhase).toBe("function");
expect(typeof params.replyOptions?.onAgentModelFirstEvent).toBe("function");
expect(typeof params.replyOptions?.onAgentExecutionPhase).toBe("function");
expect(typeof params.replyOptions?.onModelSelected).toBe("function");
expect(params.replyOptions?.onToolResult).toBeUndefined();
let active = false;
let runComplete = false;
let dispatchIdle = false;
@@ -179,6 +259,39 @@ describe("iMessage monitor last-route updates", () => {
},
};
params.replyOptions?.onTypingController?.(typingController);
params.replyOptions?.onAgentRunStart?.("agent-run-1");
await params.replyOptions?.onAgentModelPreparationPhase?.({
phase: "candidate-run-starting",
provider: "openai",
model: "gpt-5.5",
attempt: 1,
total: 1,
});
params.replyOptions?.onModelSelected?.({
provider: "openai",
model: "gpt-5.5",
thinkLevel: undefined,
});
await params.replyOptions?.onAgentModelCallStart?.({
provider: "openai",
model: "gpt-5.5",
phase: "turn_starting",
});
await params.replyOptions?.onAgentModelFirstEvent?.({
provider: "openai",
model: "gpt-5.5",
stream: "tool",
phase: "start",
name: "exec",
});
await params.replyOptions?.onAgentExecutionPhase?.({
phase: "tool_execution_started",
provider: "openai",
model: "gpt-5.5",
backend: "codex-app-server",
tool: "exec",
toolCallId: "call-1",
});
await params.replyOptions?.onToolStart?.({ name: "exec", phase: "start" });
typingController.markRunComplete();
typingController.markDispatchIdle();
@@ -254,6 +367,128 @@ describe("iMessage monitor last-route updates", () => {
expect.any(Object),
);
});
const perfPhases = consoleLogMock.mock.calls
.map((call) => call.map(String).join(" "))
.filter((line) => line.includes("imessage perf:"))
.map((line) => line.match(/\bphase=([^ ]+)/)?.[1])
.filter((phase): phase is string => Boolean(phase));
expect(perfPhases).toEqual(
expect.arrayContaining([
"watch-received",
"debounce-flushed",
"processing-started",
"routed",
"context-ready",
"gateway-dispatch-started",
"agent-model-prep",
"model-selected",
"agent-run-started",
"agent-model-call-starting",
"agent-model-first-event",
"agent-execution-phase",
"tool-started",
"gateway-dispatch-finished",
]),
);
});
it("starts direct typing before dispatching the inbound turn", async () => {
setCachedIMessagePrivateApiStatus("imsg", {
available: true,
v2Ready: true,
selectors: {},
rpcMethods: ["watch.subscribe", "send", "typing"],
});
let onNotification: ((message: { method: string; params: unknown }) => void) | undefined;
const earlyTypingClient = {
request: vi.fn(async (method: string) => {
if (method === "typing") {
return { ok: true };
}
throw new Error(`unexpected imsg typing-client method ${method}`);
}),
stop: vi.fn(async () => {}),
};
const watchClient = {
request: vi.fn(async (method: string) => {
if (method === "watch.subscribe") {
return { subscription: 1 };
}
if (method === "typing") {
return { ok: true };
}
throw new Error(`unexpected imsg watch-client method ${method}`);
}),
waitForClose: vi.fn(async () => {
onNotification?.({
method: "message",
params: {
message: {
id: 12,
chat_id: 123,
sender: "+15550001111",
is_from_me: false,
text: "respond after a slow context build",
is_group: false,
created_at: new Date().toISOString(),
},
},
});
await vi.waitFor(() => {
expect(earlyTypingClient.request).toHaveBeenCalledWith(
"typing",
expect.objectContaining({ typing: true, to: "+15550001111" }),
expect.any(Object),
);
expect(dispatchInboundMessageMock).toHaveBeenCalledTimes(1);
});
}),
stop: vi.fn(async () => {}),
};
createIMessageRpcClientMock.mockImplementation(async (params) => {
if (params?.onNotification) {
onNotification = params.onNotification;
return watchClient as never;
}
return earlyTypingClient as never;
});
dispatchInboundMessageMock.mockImplementationOnce(async () => {
expect(earlyTypingClient.request).toHaveBeenCalledWith(
"typing",
expect.objectContaining({ typing: true, to: "+15550001111" }),
expect.any(Object),
);
return { queuedFinal: false, counts: { tool: 0, block: 0, final: 0 } } as const;
});
await monitorIMessageProvider({
config: {
channels: {
imessage: {
dmPolicy: "allowlist",
allowFrom: ["+15550001111"],
sendReadReceipts: false,
},
},
messages: { inbound: { debounceMs: 0 } },
session: { mainKey: "main" },
} as never,
runtime: { error: vi.fn(), exit: vi.fn(), log: vi.fn() },
});
expect(watchClient.request).not.toHaveBeenCalledWith(
"typing",
expect.objectContaining({ typing: true }),
expect.anything(),
);
await vi.waitFor(() => {
expect(earlyTypingClient.request).toHaveBeenCalledWith(
"typing",
expect.objectContaining({ typing: false, to: "+15550001111" }),
expect.any(Object),
);
});
});
it.each(["never", "message", "thinking"] as const)(
@@ -420,6 +655,87 @@ describe("iMessage monitor last-route updates", () => {
);
});
it("does not wait for read receipts before dispatching the inbound turn", async () => {
setCachedIMessagePrivateApiStatus("imsg", {
available: true,
v2Ready: true,
selectors: {},
rpcMethods: ["watch.subscribe", "read"],
});
let onNotification: ((message: { method: string; params: unknown }) => void) | undefined;
const readClient = {
request: vi.fn((method: string) => {
if (method === "read") {
return new Promise(() => {});
}
return Promise.reject(new Error(`unexpected imsg read-client method ${method}`));
}),
stop: vi.fn(async () => {}),
};
const watchClient = {
request: vi.fn((method: string) => {
if (method === "watch.subscribe") {
return Promise.resolve({ subscription: 1 });
}
return Promise.reject(new Error(`unexpected imsg watch-client method ${method}`));
}),
waitForClose: vi.fn(async () => {
onNotification?.({
method: "message",
params: {
message: {
id: 11,
chat_id: 123,
sender: "+15550001111",
is_from_me: false,
text: "respond without waiting for read receipt",
is_group: false,
created_at: new Date().toISOString(),
},
},
});
await vi.waitFor(() => {
expect(dispatchInboundMessageMock).toHaveBeenCalledTimes(1);
});
}),
stop: vi.fn(async () => {}),
};
createIMessageRpcClientMock.mockImplementation(async (params) => {
if (params?.onNotification) {
onNotification = params.onNotification;
return watchClient as never;
}
return readClient as never;
});
await monitorIMessageProvider({
config: {
channels: {
imessage: {
dmPolicy: "allowlist",
allowFrom: ["+15550001111"],
},
},
messages: { inbound: { debounceMs: 0 } },
session: { mainKey: "main" },
} as never,
runtime: { error: vi.fn(), exit: vi.fn(), log: vi.fn() },
});
expect(readClient.request).toHaveBeenCalledWith(
"read",
expect.objectContaining({ to: "+15550001111" }),
expect.any(Object),
);
expect(watchClient.request).not.toHaveBeenCalledWith(
"read",
expect.anything(),
expect.anything(),
);
expect(dispatchInboundMessageMock).toHaveBeenCalledTimes(1);
});
it.each([
{
label: "flat true",

View File

@@ -1087,7 +1087,7 @@ function buildIMessageEchoScope(params: {
return scopes;
}
function buildDirectIMessageReplyTarget(params: {
export function buildDirectIMessageReplyTarget(params: {
cfg: OpenClawConfig;
accountId?: string | null;
sender: string;

View File

@@ -2,6 +2,7 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { performance } from "node:perf_hooks";
import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
import { CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY } from "openclaw/plugin-sdk/approval-handler-runtime";
import { logTypingFailure } from "openclaw/plugin-sdk/channel-feedback";
@@ -94,6 +95,7 @@ import {
releaseIMessageInboundReplay,
} from "./inbound-dedupe.js";
import {
buildDirectIMessageReplyTarget,
buildIMessageInboundContext,
rememberIMessageSkippedFromMeForSelfChatDedupe,
resolveIMessageReactionContext,
@@ -118,6 +120,64 @@ const IMESSAGE_TYPING_KEEPALIVE_MAX_DURATION_MS = 10 * 60_000;
const IMESSAGE_SPLIT_SEND_COMPAT_DEBOUNCE_MS = 7_000;
type IMessageTypingController = Parameters<NonNullable<GetReplyOptions["onTypingController"]>>[0];
type IMessagePerformanceTrace = {
accountId: string;
startedAtMs: number;
lastAtMs: number;
messageId: string;
chatId: string;
isGroup: boolean;
guidPresent: boolean;
sourceMessageCount: number;
};
function formatIMessagePerfMs(value: number): string {
return Math.max(0, value).toFixed(1);
}
function createIMessagePerformanceTrace(params: {
accountId: string;
message: IMessagePayload;
sourceMessageCount?: number;
}): IMessagePerformanceTrace {
const now = performance.now();
return {
accountId: params.accountId,
startedAtMs: now,
lastAtMs: now,
messageId: params.message.id != null ? String(params.message.id) : "unknown",
chatId: params.message.chat_id != null ? String(params.message.chat_id) : "unknown",
isGroup: params.message.is_group === true,
guidPresent: typeof params.message.guid === "string" && params.message.guid.trim().length > 0,
sourceMessageCount: params.sourceMessageCount ?? 1,
};
}
function markIMessagePerformanceTrace(
trace: IMessagePerformanceTrace | undefined,
phase: string,
fields: Record<string, string | number | boolean | undefined> = {},
): void {
if (!trace || !shouldLogVerbose()) {
return;
}
const now = performance.now();
const totalMs = now - trace.startedAtMs;
const deltaMs = now - trace.lastAtMs;
trace.lastAtMs = now;
const extra = Object.entries(fields)
.filter((entry): entry is [string, string | number | boolean] => entry[1] !== undefined)
.map(([key, value]) => `${key}=${String(value)}`)
.join(" ");
logVerbose(
`imessage perf: phase=${phase} total_ms=${formatIMessagePerfMs(totalMs)} ` +
`delta_ms=${formatIMessagePerfMs(deltaMs)} account=${trace.accountId} ` +
`chat_id=${trace.chatId} group=${trace.isGroup} message_id=${trace.messageId} ` +
`guid=${trace.guidPresent ? "present" : "missing"} sources=${trace.sourceMessageCount}` +
(extra ? ` ${extra}` : ""),
);
}
function resolveConfiguredIMessageTypingMode(cfg: OpenClawConfig) {
return cfg.session?.typingMode ?? cfg.agents?.defaults?.typingMode;
}
@@ -592,6 +652,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
const { debouncer: inboundDebouncer } = createChannelInboundDebouncer<{
message: IMessagePayload;
perfTrace?: IMessagePerformanceTrace;
// Exact replay-guard key claimed for this row at ingestion (GUID or, for a
// GUID-less row, the composite fallback). Carried through so flush commits
// or releases the same key it claimed, even after a debounce merge rewrites
@@ -653,14 +714,29 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
// dispatch throws so a transient failure can retry on a later re-emit. Per
// unit so a failure in one bucket entry cannot strand another's claim.
const dispatchUnit = async (
unitEntries: { message: IMessagePayload; replayKey: string | null }[],
unitEntries: {
message: IMessagePayload;
perfTrace?: IMessagePerformanceTrace;
replayKey: string | null;
}[],
message: IMessagePayload,
) => {
const perfTrace =
unitEntries[0]?.perfTrace ??
createIMessagePerformanceTrace({
accountId: accountInfo.accountId,
message,
sourceMessageCount: unitEntries.length,
});
perfTrace.sourceMessageCount = unitEntries.length;
markIMessagePerformanceTrace(perfTrace, "debounce-flushed", {
merged: unitEntries.length > 1,
});
const keys = unitEntries
.map((entry) => entry.replayKey)
.filter((key): key is string => key !== null);
try {
await handleMessageNow(message);
await handleMessageNow(message, { perfTrace });
await commitIMessageInboundReplay({
guard: inboundReplayGuard,
accountId: accountInfo.accountId,
@@ -695,7 +771,11 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
// Standalone URL preview rows merge with the immediately preceding row;
// already-complete URL messages flush any pending ordinary row first.
if (messages.some(hasIMessageUrlBalloonBundleID)) {
let pending: { message: IMessagePayload; replayKey: string | null } | null = null;
let pending: {
message: IMessagePayload;
perfTrace?: IMessagePerformanceTrace;
replayKey: string | null;
} | null = null;
for (const entry of entries) {
if (isStandaloneIMessageUrlPreviewPayload(entry.message) && pending) {
const unitEntries = [pending, entry];
@@ -822,9 +902,13 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
async function handleMessageNow(
message: IMessagePayload,
options: { advanceCatchupCursor?: boolean } = {},
options: { advanceCatchupCursor?: boolean; perfTrace?: IMessagePerformanceTrace } = {},
) {
await handleMessageNowInner(message);
const perfTrace =
options.perfTrace ??
createIMessagePerformanceTrace({ accountId: accountInfo.accountId, message });
markIMessagePerformanceTrace(perfTrace, "processing-started");
await handleMessageNowInner(message, perfTrace);
if (options.advanceCatchupCursor !== false) {
await maybeAdvanceLiveCatchupCursor(message);
}
@@ -874,9 +958,13 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
};
}
async function handleMessageNowInner(rawMessage: IMessagePayload) {
async function handleMessageNowInner(
rawMessage: IMessagePayload,
perfTrace: IMessagePerformanceTrace,
) {
const message = await repairMessageConversationAnchor(rawMessage);
if (!message) {
markIMessagePerformanceTrace(perfTrace, "conversation-repair-dropped");
return;
}
@@ -903,6 +991,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
logVerboseMessage: logVerbose,
})
) {
markIMessagePerformanceTrace(perfTrace, "approval-reaction-handled");
return;
}
@@ -939,6 +1028,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
const rateLimitKey = `${accountInfo.accountId}:${conversationKey}`;
if (decision.kind === "drop") {
markIMessagePerformanceTrace(perfTrace, "dropped", { reason: decision.reason });
// Record echo/reflection drops so the rate limiter can detect sustained loops.
// Only loop-related drop reasons feed the counter; policy/mention/empty drops
// are normal and should not escalate.
@@ -985,13 +1075,16 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
// remaining messages as a safety net against amplification that slips
// through the primary guards.
if (decision.kind === "dispatch" && loopRateLimiter.isRateLimited(rateLimitKey)) {
markIMessagePerformanceTrace(perfTrace, "rate-limited");
logVerbose(`imessage: rate-limited conversation ${conversationKey} (echo loop detected)`);
return;
}
if (decision.kind === "pairing") {
markIMessagePerformanceTrace(perfTrace, "pairing-started");
const sender = (message.sender ?? "").trim();
if (!sender) {
markIMessagePerformanceTrace(perfTrace, "pairing-dropped", { reason: "missing-sender" });
return;
}
await createChannelPairingChallengeIssuer({
@@ -1032,13 +1125,101 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
}
if (decision.kind === "reaction") {
markIMessagePerformanceTrace(perfTrace, "reaction-enqueued");
enqueueIMessageReactionSystemEvent({ decision, runtime, logVerbose });
return;
}
markIMessagePerformanceTrace(perfTrace, "routed", {
agent: decision.route.agentId,
session: decision.route.sessionKey,
});
const storePath = resolveStorePath(cfg.session?.store, {
agentId: decision.route.agentId,
});
const privateApiStatus = getCachedIMessagePrivateApiStatus(cliPath);
const supportsTyping = imessageRpcSupportsMethod(privateApiStatus, "typing");
const supportsRead = imessageRpcSupportsMethod(privateApiStatus, "read");
if (privateApiStatus?.available === true) {
// Surface a single warning per restart when the bridge is up but we
// had to gate off typing/read because the imsg build pre-dates the
// capability list. Otherwise the user sees no typing bubble / no
// "Read" receipt with no visible reason.
if (!supportsTyping || !supportsRead) {
warnIfImsgUpgradeNeeded.fireOnce(privateApiStatus.rpcMethods, runtime);
}
}
const configuredTypingMode = resolveConfiguredIMessageTypingMode(cfg);
const sendPolicy = resolveSendPolicy({
cfg,
entry: getSessionEntry({ storePath, sessionKey: decision.route.sessionKey }),
sessionKey: decision.route.sessionKey,
channel: "imessage",
chatType: decision.isGroup ? "group" : "direct",
});
const shouldStartDirectTyping =
supportsTyping &&
!decision.isGroup &&
sendPolicy !== "deny" &&
(configuredTypingMode === undefined || configuredTypingMode === "instant");
const earlyDirectTypingTarget = shouldStartDirectTyping
? buildDirectIMessageReplyTarget({
cfg,
accountId: decision.route.accountId,
sender: decision.sender,
})
: undefined;
let stopEarlyDirectTyping: (() => void) | undefined;
if (earlyDirectTypingTarget) {
markIMessagePerformanceTrace(perfTrace, "early-typing-start-queued");
// Start channel-native feedback before the expensive history/context/model
// path. Use a short-lived client so a slow typing RPC cannot block the
// monitor client's watch stream. Stop is sequenced after start so fast
// command replies cannot leave a late true after typing:false.
const earlyDirectTypingStarted = sendIMessageTyping(earlyDirectTypingTarget, true, {
cfg,
accountId: accountInfo.accountId,
}).then(
() => true,
(err: unknown) => {
logTypingFailure({
log: (msg) => logVerbose(msg),
channel: "imessage",
action: "start",
target: earlyDirectTypingTarget,
error: err,
});
return false;
},
);
let earlyTypingStopQueued = false;
stopEarlyDirectTyping = () => {
if (earlyTypingStopQueued) {
return;
}
earlyTypingStopQueued = true;
void earlyDirectTypingStarted
.then(async (started) => {
if (!started) {
return;
}
await sendIMessageTyping(earlyDirectTypingTarget, false, {
cfg,
accountId: accountInfo.accountId,
});
})
.catch((err: unknown) => {
logTypingFailure({
log: (msg) => logVerbose(msg),
channel: "imessage",
action: "stop",
target: earlyDirectTypingTarget,
error: err,
});
});
};
}
const stagedAttachments = remoteHost
? []
: await stageIMessageAttachments(validAttachments, {
@@ -1098,6 +1279,10 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
allowFrom,
normalizeEntry: normalizeIMessageHandle,
});
markIMessagePerformanceTrace(perfTrace, "context-ready", {
has_media: mediaAttachments.length > 0,
dm_history: dmHistory?.inboundHistory?.length ?? 0,
});
if (shouldLogVerbose()) {
const preview = truncateUtf16Safe(ctxPayload.Body ?? "", 200).replace(/\n/g, "\\n");
logVerbose(
@@ -1107,31 +1292,20 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
);
}
const privateApiStatus = getCachedIMessagePrivateApiStatus(cliPath);
const supportsTyping = imessageRpcSupportsMethod(privateApiStatus, "typing");
const supportsRead = imessageRpcSupportsMethod(privateApiStatus, "read");
if (privateApiStatus?.available === true) {
// Surface a single warning per restart when the bridge is up but we
// had to gate off typing/read because the imsg build pre-dates the
// capability list. Otherwise the user sees no typing bubble / no
// "Read" receipt with no visible reason.
if (!supportsTyping || !supportsRead) {
warnIfImsgUpgradeNeeded.fireOnce(privateApiStatus.rpcMethods, runtime);
}
}
const sendReadReceipts = imessageCfg.sendReadReceipts !== false;
const typingTarget = ctxPayload.To;
if (supportsRead && sendReadReceipts && typingTarget) {
try {
await markIMessageChatRead(typingTarget, {
cfg,
accountId: accountInfo.accountId,
client: getActiveClient(),
});
} catch (err) {
// Read receipts are best-effort channel UI. Do not put them on the
// critical path before model dispatch; slow private-API reads otherwise
// make accepted iMessage turns feel stuck before the agent starts. Use
// a short-lived client so a stuck read cannot block monitor-client typing.
void markIMessageChatRead(typingTarget, {
cfg,
accountId: accountInfo.accountId,
}).catch((err: unknown) => {
runtime.error?.(`imessage: mark read failed: ${String(err)}`);
}
});
}
const { onModelSelected, ...replyPipeline } = createChannelMessageReplyPipeline({
@@ -1191,62 +1365,81 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
...replyPipeline,
humanDelay: resolveHumanDelayConfig(cfg, decision.route.agentId),
deliver: async (payload, info) => {
markIMessagePerformanceTrace(perfTrace, "reply-delivery-started", {
kind: info.kind,
});
const target = ctxPayload.To;
if (!target) {
markIMessagePerformanceTrace(perfTrace, "reply-delivery-dropped", {
reason: "missing-target",
kind: info.kind,
});
runtime.error?.(danger("imessage: missing delivery target"));
return;
}
const durable = await deliverInboundReplyWithMessageSendContext({
cfg,
channel: "imessage",
accountId: accountInfo.accountId,
agentId: decision.route.agentId,
ctxPayload,
payload,
info,
to: target,
deps: {
imessage: createIMessageEchoCachingSend({
accountId: accountInfo.accountId,
sentMessageCache,
}),
},
});
if (durable.status === "failed") {
throw durable.error;
try {
const durable = await deliverInboundReplyWithMessageSendContext({
cfg,
channel: "imessage",
accountId: accountInfo.accountId,
agentId: decision.route.agentId,
ctxPayload,
payload,
info,
to: target,
deps: {
imessage: createIMessageEchoCachingSend({
accountId: accountInfo.accountId,
sentMessageCache,
}),
},
});
if (durable.status === "failed") {
throw durable.error;
}
if (durable.status === "handled_visible" || durable.status === "handled_no_send") {
markIMessagePerformanceTrace(perfTrace, "reply-delivery-finished", {
kind: info.kind,
status: durable.status,
});
return;
}
await deliverReplies({
cfg,
replies: [payload],
target,
accountId: accountInfo.accountId,
runtime,
maxBytes: mediaMaxBytes,
textLimit,
sentMessageCache,
});
markIMessagePerformanceTrace(perfTrace, "reply-delivery-finished", {
kind: info.kind,
status: "sent",
});
} catch (err) {
markIMessagePerformanceTrace(perfTrace, "reply-delivery-failed", {
kind: info.kind,
});
throw err;
}
if (durable.status === "handled_visible" || durable.status === "handled_no_send") {
return;
}
await deliverReplies({
cfg,
replies: [payload],
target,
accountId: accountInfo.accountId,
runtime,
maxBytes: mediaMaxBytes,
textLimit,
sentMessageCache,
});
},
onError: (err, info) => {
markIMessagePerformanceTrace(perfTrace, "reply-error", {
kind: info.kind,
});
runtime.error?.(danger(`imessage ${info.kind} reply failed: ${String(err)}`));
},
});
let directTypingController: IMessageTypingController | undefined;
const configuredTypingMode = resolveConfiguredIMessageTypingMode(cfg);
const sendPolicy = resolveSendPolicy({
cfg,
entry: getSessionEntry({ storePath, sessionKey: decision.route.sessionKey }),
sessionKey: decision.route.sessionKey,
channel: "imessage",
chatType: decision.isGroup ? "group" : "direct",
});
const shouldStartToolTyping =
!decision.isGroup &&
sendPolicy !== "deny" &&
(configuredTypingMode === undefined || configuredTypingMode === "instant");
const directToolTypingOptions = shouldStartToolTyping
const directToolTypingOptions: Pick<
GetReplyOptions,
| "allowProgressCallbacksWhenSourceDeliverySuppressed"
| "onToolStart"
| "onTypingController"
| "suppressDefaultToolProgressMessages"
> = shouldStartDirectTyping
? ({
// iMessage's native typing bubble is channel-owned UI, not a
// visible tool-progress message. The suppress flag is what lets
@@ -1265,6 +1458,20 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
},
} as const)
: {};
const directToolTypingOnToolStart = directToolTypingOptions.onToolStart;
const tracedDirectToolTypingOptions: typeof directToolTypingOptions =
directToolTypingOnToolStart
? {
...directToolTypingOptions,
onToolStart: async (payload) => {
markIMessagePerformanceTrace(perfTrace, "tool-started", {
tool: payload.name,
phase: payload.phase,
});
await directToolTypingOnToolStart(payload);
},
}
: directToolTypingOptions;
const configuredBlockStreaming = resolveChannelStreamingBlockEnabled(accountInfo.config);
const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
route: decision.route,
@@ -1325,13 +1532,16 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
historyMap: groupHistories,
limit: historyLimit,
},
onPreDispatchFailure: () =>
settleReplyDispatcher({
onPreDispatchFailure: () => {
stopEarlyDirectTyping?.();
void settleReplyDispatcher({
dispatcher,
onSettled: () => markDispatchIdle(),
}),
});
},
runDispatch: async () => {
try {
markIMessagePerformanceTrace(perfTrace, "gateway-dispatch-started");
return await dispatchInboundMessage({
ctx: ctxPayload,
cfg,
@@ -1342,12 +1552,65 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
typeof configuredBlockStreaming === "boolean"
? !configuredBlockStreaming
: undefined,
onModelSelected,
...directToolTypingOptions,
...tracedDirectToolTypingOptions,
onAgentRunStart: (runId) => {
markIMessagePerformanceTrace(perfTrace, "agent-run-started", {
run_id: runId,
});
},
onAgentModelCallStart: (modelCall) => {
markIMessagePerformanceTrace(perfTrace, "agent-model-call-starting", {
provider: modelCall.provider,
model: modelCall.model,
event_phase: modelCall.phase,
});
},
onAgentModelPreparationPhase: (prep) => {
markIMessagePerformanceTrace(perfTrace, "agent-model-prep", {
prep_phase: prep.phase,
provider: prep.provider,
model: prep.model,
candidate_count: prep.candidateCount,
attempt: prep.attempt,
total: prep.total,
});
},
onAgentModelFirstEvent: (event) => {
markIMessagePerformanceTrace(perfTrace, "agent-model-first-event", {
provider: event.provider,
model: event.model,
stream: event.stream,
event_phase: event.phase,
kind: event.kind,
name: event.name,
});
},
onAgentExecutionPhase: (phase) => {
markIMessagePerformanceTrace(perfTrace, "agent-execution-phase", {
execution_phase: phase.phase,
provider: phase.provider,
model: phase.model,
backend: phase.backend,
source: phase.source,
tool: phase.tool,
tool_call_id: phase.toolCallId,
item_id: phase.itemId,
});
},
onModelSelected: (modelSelection) => {
markIMessagePerformanceTrace(perfTrace, "model-selected", {
provider: modelSelection.provider,
model: modelSelection.model,
think_level: modelSelection.thinkLevel,
});
onModelSelected(modelSelection);
},
},
});
} finally {
markIMessagePerformanceTrace(perfTrace, "gateway-dispatch-finished");
markDispatchIdle();
stopEarlyDirectTyping?.();
}
},
}),
@@ -1370,6 +1633,11 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
runtime.error?.(`imessage: dropping malformed RPC message payload (keys=${shape})`);
return;
}
const perfTrace = createIMessagePerformanceTrace({
accountId: accountInfo.accountId,
message,
});
markIMessagePerformanceTrace(perfTrace, "watch-received");
if (!imsgEmitsBalloonMetadata && hasIMessageBalloonMetadata(message)) {
imsgEmitsBalloonMetadata = true;
}
@@ -1390,6 +1658,9 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
? IMESSAGE_RECOVERY_MAX_AGE_MS
: IMESSAGE_STALE_INBOUND_THRESHOLD_MS;
if (isStaleIMessageBacklog(message, Date.now(), staleThresholdMs)) {
markIMessagePerformanceTrace(perfTrace, "stale-backlog-suppressed", {
recovery: isRecoveryReplay,
});
staleBacklogSuppressed += 1;
runtime.log?.(
warn(
@@ -1418,6 +1689,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
}
const repairedMessage = await repairMessageConversationAnchor(message);
if (!repairedMessage) {
markIMessagePerformanceTrace(perfTrace, "conversation-repair-dropped");
return;
}
// Replay dedupe: a recovered bridge can re-emit a row already dispatched.
@@ -1433,13 +1705,14 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
message: repairedMessage,
});
if (!replay.claimed) {
markIMessagePerformanceTrace(perfTrace, "duplicate-dropped");
logVerbose(
`imessage: dropping duplicate inbound notification account=${accountInfo.accountId}`,
);
return;
}
trackPendingRecoveryReplayRow(repairedMessage);
await inboundDebouncer.enqueue({ message: repairedMessage, replayKey: replay.key });
await inboundDebouncer.enqueue({ message: repairedMessage, perfTrace, replayKey: replay.key });
};
await waitForTransportReady({
@@ -1502,6 +1775,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
let keepAttemptClient = false;
try {
attemptClient = requireWatchClient(await createWatchClient());
client = attemptClient;
let attemptSubscriptionId: number | null = null;
attemptDetachAbortHandler = attachIMessageMonitorAbortHandler({
abortSignal: abort,
@@ -1527,7 +1801,6 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
{ timeoutMs: probeTimeoutMs },
);
attemptSubscriptionId = result?.subscription ?? null;
client = attemptClient;
detachAbortHandler = attemptDetachAbortHandler;
keepAttemptClient = true;
break;
@@ -1577,7 +1850,11 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
// cannot keep emitting notifications into the next retry window.
attemptDetachAbortHandler();
attemptDetachAbortHandler = () => {};
await attemptClient?.stop();
const failedClient = attemptClient;
await failedClient?.stop();
if (client === failedClient) {
client = undefined;
}
attemptClient = undefined;
await waitForWatchSubscribeRetryDelay({
ms: WATCH_SUBSCRIBE_RETRY_DELAY_MS,
@@ -1588,8 +1865,12 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
}
} finally {
if (!keepAttemptClient) {
const failedClient = attemptClient;
attemptDetachAbortHandler();
await attemptClient?.stop();
await failedClient?.stop();
if (client === failedClient) {
client = undefined;
}
}
}
}

View File

@@ -179,6 +179,36 @@ describe("createIMessageRpcClient", () => {
expect(onNotification).not.toHaveBeenCalled();
});
it("rejects waitForClose when imsg exits without an explicit stop", async () => {
vi.stubEnv("VITEST", "");
vi.stubEnv("NODE_ENV", "");
const child = createMockChildProcess();
spawnMock.mockReturnValue(child);
const { IMessageRpcClient } = await import("./client.js");
const client = new IMessageRpcClient();
await client.start();
const closed = client.waitForClose();
child.emit("close", 0, null);
await expect(closed).rejects.toThrow("imsg rpc closed");
});
it("does not reject waitForClose for an intentional stop", async () => {
vi.stubEnv("VITEST", "");
vi.stubEnv("NODE_ENV", "");
const child = createMockChildProcess();
spawnMock.mockReturnValue(child);
const { IMessageRpcClient } = await import("./client.js");
const client = new IMessageRpcClient();
await client.start();
const closed = client.waitForClose();
await client.stop();
await expect(closed).resolves.toBeUndefined();
});
});
describe("imessage setup status", () => {

View File

@@ -2,7 +2,6 @@
"id": "line",
"name": "LINE",
"description": "OpenClaw LINE channel plugin for LINE Bot API chats.",
"icon": "https://cdn.simpleicons.org/line/111111",
"activation": {
"onStartup": false
},

View File

@@ -11,9 +11,7 @@ openclaw plugins install @openclaw/llama-cpp-provider
```
Restart the Gateway after installing or updating the plugin. Use Node 24 for
native installs and updates. Source checkouts leave the native build unapproved
by default; run `pnpm approve-builds` and `pnpm rebuild node-llama-cpp` before
using local GGUF embeddings from source.
native installs and updates.
## Configure

View File

@@ -1,6 +1,5 @@
{
"id": "lmstudio",
"icon": "https://cdn.simpleicons.org/lmstudio/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "matrix",
"name": "Matrix",
"description": "OpenClaw Matrix channel plugin for rooms and direct messages.",
"icon": "https://cdn.simpleicons.org/matrix/111111",
"commandAliases": [{ "name": "matrix" }],
"activation": {
"onStartup": false,

View File

@@ -1,6 +1,5 @@
{
"id": "mattermost",
"icon": "https://cdn.simpleicons.org/mattermost/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "minimax",
"icon": "https://cdn.simpleicons.org/minimax/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "mistral",
"icon": "https://cdn.simpleicons.org/mistralai/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "nextcloud-talk",
"name": "Nextcloud Talk",
"description": "OpenClaw Nextcloud Talk channel plugin for conversations.",
"icon": "https://cdn.simpleicons.org/nextcloud/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "nvidia",
"icon": "https://cdn.simpleicons.org/nvidia/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "ollama",
"icon": "https://cdn.simpleicons.org/ollama/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "opencode-go",
"icon": "https://cdn.simpleicons.org/opencode/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "opencode",
"icon": "https://cdn.simpleicons.org/opencode/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "openrouter",
"icon": "https://cdn.simpleicons.org/openrouter/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "perplexity",
"icon": "https://cdn.simpleicons.org/perplexity/111111",
"activation": {
"onStartup": false
},

View File

@@ -11,11 +11,6 @@ import {
validateQaScenarioExecutionConfig,
} from "./scenario-catalog.js";
type CatalogScenario = ReturnType<typeof readQaScenarioPack>["scenarios"][number];
type FlowCatalogScenario = CatalogScenario & {
execution: Extract<CatalogScenario["execution"], { kind: "flow" }>;
};
function listScenarioMarkdownPaths(dir = "qa/scenarios"): string[] {
return fs
.readdirSync(dir, { withFileTypes: true })
@@ -29,32 +24,6 @@ function listScenarioMarkdownPaths(dir = "qa/scenarios"): string[] {
.toSorted();
}
function isFlowScenario(scenario: CatalogScenario): scenario is FlowCatalogScenario {
return scenario.execution.kind === "flow";
}
function requireFlowScenario(scenario: CatalogScenario): FlowCatalogScenario {
expect(scenario.execution.kind).toBe("flow");
if (!isFlowScenario(scenario)) {
throw new Error(`expected ${scenario.id} to be a flow scenario`);
}
return scenario;
}
function flowContainsCall(value: unknown, callName: string): boolean {
if (Array.isArray(value)) {
return value.some((entry) => flowContainsCall(entry, callName));
}
if (!value || typeof value !== "object") {
return false;
}
const record = value as Record<string, unknown>;
return (
record.call === callName ||
Object.values(record).some((entry) => flowContainsCall(entry, callName))
);
}
describe("qa scenario catalog", () => {
const dottedCoverageIdPattern = /^[a-z0-9][a-z0-9-]*(?:\.[a-z0-9][a-z0-9-]*)+$/;
@@ -175,34 +144,6 @@ describe("qa scenario catalog", () => {
expect(fanoutConfig?.expectedReplyGroups?.flat()).toContain("subagent-2: ok");
});
it("loads explicit suite isolation metadata from per-scenario YAML", () => {
const staleLinks = requireFlowScenario(readQaScenarioById("subagent-stale-child-links"));
const kitchenSink = requireFlowScenario(readQaScenarioById("kitchen-sink-live-openai"));
expect(staleLinks.execution.suiteIsolation).toBe("isolated");
expect(staleLinks.execution.isolationReason).toContain("gateway session");
expect(kitchenSink.execution.suiteIsolation).toBe("isolated");
expect(kitchenSink.execution.isolationReason).toContain("plugin/channel/tool config");
});
it("requires explicit suite isolation for gateway state restart scenarios", () => {
const scenarios = readQaScenarioPack()
.scenarios.filter(isFlowScenario)
.filter((scenario) =>
flowContainsCall(scenario.execution.flow, "env.gateway.restartAfterStateMutation"),
);
expect(scenarios.map((scenario) => scenario.id).toSorted()).toEqual([
"kitchen-sink-live-openai",
"subagent-stale-child-links",
]);
expect(
scenarios
.filter((scenario) => scenario.execution.suiteIsolation !== "isolated")
.map((scenario) => scenario.id),
).toEqual([]);
});
it("loads scenario-declared gateway runtime options from YAML", () => {
const scenario = readQaScenarioById("control-ui-qa-channel-image-roundtrip");
const otelStdout = readQaScenarioById("otel-stdout-log-smoke");
@@ -575,6 +516,9 @@ describe("qa scenario catalog", () => {
expect(config?.expectedAdversarialDiagnostics).toContain(
"trusted tool policy registration requires id, description, and evaluate()",
);
expect(config?.expectedAdversarialDiagnostics).toContain(
"control UI descriptor registration requires id, surface, label, and valid optional fields",
);
expect(config?.expectedAdversarialDiagnostics).toContain(
"hosted media resolver registration missing resolver",
);

View File

@@ -70,8 +70,6 @@ const qaFlowScenarioExecutionSchema = z.object({
kind: z.literal("flow").default("flow"),
summary: z.string().trim().min(1).optional(),
channel: qaScenarioChannelSchema.optional(),
suiteIsolation: z.literal("isolated").optional(),
isolationReason: z.string().trim().min(1).optional(),
config: qaScenarioConfigSchema.optional(),
});

View File

@@ -51,27 +51,26 @@ describe("qa suite runtime launcher", () => {
beforeEach(() => {
runQaFlowSuite.mockReset();
runQaTestFileScenarios.mockReset();
runQaFlowSuite.mockImplementation(
async (params: { outputDir?: string; scenarioIds?: string[] } | undefined) => {
const outputDir = params?.outputDir ?? "/tmp/qa-flow";
const evidencePath = path.join(outputDir, "qa-evidence.json");
await writeEvidence(evidencePath);
const scenarioIds = params?.scenarioIds ?? ["channel-chat-baseline"];
return {
outputDir,
evidencePath,
reportPath: path.join(outputDir, "qa-suite-report.md"),
summaryPath: path.join(outputDir, "qa-suite-summary.json"),
report: "# QA Suite Report\n",
scenarios: scenarioIds.map((scenarioId) => ({
name: scenarioId,
runQaFlowSuite.mockImplementation(async (params: { outputDir?: string } | undefined) => {
const outputDir = params?.outputDir ?? "/tmp/qa-flow";
const evidencePath = path.join(outputDir, "qa-evidence.json");
await writeEvidence(evidencePath);
return {
outputDir,
evidencePath,
reportPath: path.join(outputDir, "qa-suite-report.md"),
summaryPath: path.join(outputDir, "qa-suite-summary.json"),
report: "# QA Suite Report\n",
scenarios: [
{
name: "channel-chat-baseline",
status: "pass",
steps: [],
})),
watchUrl: "http://127.0.0.1:43124",
};
},
);
},
],
watchUrl: "http://127.0.0.1:43124",
};
});
runQaTestFileScenarios.mockImplementation(
async (params: {
outputDir: string;
@@ -99,7 +98,6 @@ describe("qa suite runtime launcher", () => {
});
afterEach(async () => {
vi.unstubAllEnvs();
await Promise.all(
tempRoots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })),
);
@@ -173,60 +171,6 @@ describe("qa suite runtime launcher", () => {
).toEqual([{ id: "control-ui-chat-flow-playwright", kind: "playwright" }]);
});
it("serializes test-file runner partitions in one checkout", async () => {
const repoRoot = await makeTempRepo("qa-suite-test-file-serial-");
let releaseVitest!: () => void;
let markVitestStarted!: () => void;
const vitestStarted = new Promise<void>((resolve) => {
markVitestStarted = resolve;
});
const vitestBlocked = new Promise<void>((resolve) => {
releaseVitest = resolve;
});
runQaTestFileScenarios.mockImplementationOnce(
async (params: {
outputDir: string;
scenarios: Array<{ id: string; execution: { kind: "script" | "vitest" | "playwright" } }>;
}) => {
markVitestStarted();
await vitestBlocked;
const evidencePath = path.join(params.outputDir, "qa-evidence.json");
await writeEvidence(evidencePath);
const scenario = params.scenarios[0];
if (!scenario) {
throw new Error("expected scenario");
}
return {
outputDir: params.outputDir,
executionKind: scenario.execution.kind,
evidencePath,
results: params.scenarios.map((scenarioItem) => ({
durationMs: 1,
logPath: path.join(params.outputDir, `${scenarioItem.id}.log`),
scenario: scenarioItem,
status: "pass",
})),
};
},
);
const runPromise = runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/test-file-serial",
concurrency: 8,
scenarioIds: ["gateway-smoke", "control-ui-chat-flow-playwright"],
});
await vitestStarted;
await Promise.resolve();
expect(runQaTestFileScenarios).toHaveBeenCalledTimes(1);
releaseVitest();
await runPromise;
expect(runQaTestFileScenarios).toHaveBeenCalledTimes(2);
});
it("runs mixed flow and Vitest/Playwright scenarios as one suite", async () => {
const repoRoot = await makeTempRepo("qa-suite-mixed-");
const result = await runQaSuite({
@@ -276,426 +220,6 @@ describe("qa suite runtime launcher", () => {
);
});
it("keeps channel-driver unified flow partitions serial by default", async () => {
const repoRoot = await makeTempRepo("qa-suite-crabline-serial-");
await runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/crabline-serial",
channelDriverSelection: {
capabilityMatrixPath: "crabline-fake-provider-capabilities.json",
channel: "telegram",
channelDriver: "crabline",
smokeArtifactPath: "crabline-fake-provider-smoke.json",
},
scenarioIds: ["channel-chat-baseline", "dm-chat-baseline", "control-ui-chat-flow-playwright"],
});
const outputDir = path.join(repoRoot, ".artifacts", "qa-e2e", "crabline-serial");
expect(runQaFlowSuite).toHaveBeenCalledTimes(1);
expect(runQaFlowSuite).toHaveBeenCalledWith(
expect.objectContaining({
outputDir: path.join(outputDir, "flow"),
concurrency: 1,
scenarioIds: ["channel-chat-baseline", "dm-chat-baseline"],
}),
);
expect(runQaTestFileScenarios).toHaveBeenCalledTimes(1);
});
it("respects serial concurrency across unified suite partitions", async () => {
const repoRoot = await makeTempRepo("qa-suite-serial-");
let releaseFlow!: () => void;
let markFlowStarted!: () => void;
const flowStarted = new Promise<void>((resolve) => {
markFlowStarted = resolve;
});
const flowBlocked = new Promise<void>((resolve) => {
releaseFlow = resolve;
});
runQaFlowSuite.mockImplementationOnce(
async (params: { outputDir?: string; scenarioIds?: string[] } | undefined) => {
markFlowStarted();
await flowBlocked;
const outputDir = params?.outputDir ?? "/tmp/qa-flow";
const evidencePath = path.join(outputDir, "qa-evidence.json");
await writeEvidence(evidencePath);
const scenarioIds = params?.scenarioIds ?? ["channel-chat-baseline"];
return {
outputDir,
evidencePath,
reportPath: path.join(outputDir, "qa-suite-report.md"),
summaryPath: path.join(outputDir, "qa-suite-summary.json"),
report: "# QA Suite Report\n",
scenarios: scenarioIds.map((scenarioId) => ({
name: scenarioId,
status: "pass",
steps: [],
})),
watchUrl: "http://127.0.0.1:43124",
};
},
);
const runPromise = runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/serial",
concurrency: 1,
scenarioIds: [
"channel-chat-baseline",
"group-visible-reply-tool",
"control-ui-chat-flow-playwright",
],
});
await flowStarted;
await Promise.resolve();
expect(runQaFlowSuite).toHaveBeenCalledTimes(1);
expect(runQaTestFileScenarios).not.toHaveBeenCalled();
releaseFlow();
await runPromise;
expect(runQaFlowSuite).toHaveBeenCalledTimes(2);
expect(runQaTestFileScenarios).toHaveBeenCalledTimes(1);
});
it("keeps multiple isolated flow scenarios in separate serial partitions", async () => {
const repoRoot = await makeTempRepo("qa-suite-serial-isolated-");
await runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/serial-isolated",
concurrency: 1,
scenarioIds: [
"group-visible-reply-tool",
"runtime-tool-image-generate",
"control-ui-chat-flow-playwright",
],
});
const outputDir = path.join(repoRoot, ".artifacts", "qa-e2e", "serial-isolated");
expect(runQaFlowSuite).toHaveBeenCalledTimes(2);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "isolated-1"),
concurrency: 1,
workerStartStaggerMs: 0,
scenarioIds: ["group-visible-reply-tool"],
}),
);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "isolated-2"),
concurrency: 1,
workerStartStaggerMs: 0,
scenarioIds: ["runtime-tool-image-generate"],
}),
);
expect(runQaTestFileScenarios).toHaveBeenCalledTimes(1);
});
it("accounts for isolated flow worker weight in unified suite concurrency", async () => {
const repoRoot = await makeTempRepo("qa-suite-weighted-");
let releaseShared!: () => void;
let markSharedStarted!: () => void;
const sharedStarted = new Promise<void>((resolve) => {
markSharedStarted = resolve;
});
const sharedBlocked = new Promise<void>((resolve) => {
releaseShared = resolve;
});
runQaFlowSuite.mockImplementationOnce(
async (params: { outputDir?: string; scenarioIds?: string[] } | undefined) => {
markSharedStarted();
await sharedBlocked;
const outputDir = params?.outputDir ?? "/tmp/qa-flow";
const evidencePath = path.join(outputDir, "qa-evidence.json");
await writeEvidence(evidencePath);
const scenarioIds = params?.scenarioIds ?? ["channel-chat-baseline"];
return {
outputDir,
evidencePath,
reportPath: path.join(outputDir, "qa-suite-report.md"),
summaryPath: path.join(outputDir, "qa-suite-summary.json"),
report: "# QA Suite Report\n",
scenarios: scenarioIds.map((scenarioId) => ({
name: scenarioId,
status: "pass",
steps: [],
})),
watchUrl: "http://127.0.0.1:43124",
};
},
);
const runPromise = runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/weighted",
concurrency: 3,
scenarioIds: [
"channel-chat-baseline",
"group-visible-reply-tool",
"control-ui-chat-flow-playwright",
],
});
await sharedStarted;
await Promise.resolve();
expect(runQaFlowSuite).toHaveBeenCalledTimes(2);
await vi.waitFor(() => {
expect(runQaTestFileScenarios).toHaveBeenCalledTimes(1);
});
releaseShared();
await runPromise;
expect(runQaFlowSuite).toHaveBeenCalledTimes(2);
expect(runQaTestFileScenarios).toHaveBeenCalledTimes(1);
});
it("waits for already-started partitions before rejecting a unified suite", async () => {
const repoRoot = await makeTempRepo("qa-suite-reject-settle-");
let releaseTestFile!: () => void;
let markTestFileStarted!: () => void;
const testFileStarted = new Promise<void>((resolve) => {
markTestFileStarted = resolve;
});
const testFileBlocked = new Promise<void>((resolve) => {
releaseTestFile = resolve;
});
runQaFlowSuite.mockRejectedValueOnce(new Error("flow partition failed"));
runQaTestFileScenarios.mockImplementationOnce(
async (params: {
outputDir: string;
scenarios: Array<{ id: string; execution: { kind: "script" | "vitest" | "playwright" } }>;
}) => {
markTestFileStarted();
await testFileBlocked;
const evidencePath = path.join(params.outputDir, "qa-evidence.json");
await writeEvidence(evidencePath);
return {
outputDir: params.outputDir,
executionKind: params.scenarios[0]?.execution.kind ?? "playwright",
evidencePath,
results: params.scenarios.map((scenarioItem) => ({
durationMs: 1,
logPath: path.join(params.outputDir, `${scenarioItem.id}.log`),
scenario: scenarioItem,
status: "pass",
})),
};
},
);
const runPromise = runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/reject-settle",
concurrency: 2,
scenarioIds: ["channel-chat-baseline", "control-ui-chat-flow-playwright"],
});
let rejected = false;
void runPromise.catch(() => {
rejected = true;
});
await testFileStarted;
await Promise.resolve();
expect(rejected).toBe(false);
releaseTestFile();
await expect(runPromise).rejects.toThrow("flow partition failed");
expect(rejected).toBe(true);
});
it("shares ordinary flow scenarios and isolates flow scenarios with config patches", async () => {
const repoRoot = await makeTempRepo("qa-suite-partition-");
const result = await runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/smoke",
concurrency: 8,
scenarioIds: [
"channel-chat-baseline",
"group-visible-reply-tool",
"control-ui-chat-flow-playwright",
],
});
const outputDir = path.join(repoRoot, ".artifacts", "qa-e2e", "smoke");
expect(result.executionKind).toBe("suite");
expect(runQaFlowSuite).toHaveBeenCalledTimes(2);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "shared"),
concurrency: 1,
scenarioIds: ["channel-chat-baseline"],
}),
);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "isolated"),
concurrency: 1,
workerStartStaggerMs: 0,
scenarioIds: ["group-visible-reply-tool"],
}),
);
const summary = JSON.parse(
await fs.readFile(path.join(outputDir, "qa-suite-summary.json"), "utf8"),
) as {
scenarios?: Array<{ name?: unknown; status?: unknown }>;
};
expect(summary.scenarios).toMatchObject([
{ name: "channel-chat-baseline", status: "pass" },
{ name: "group-visible-reply-tool", status: "pass" },
{ name: "Control UI chat flow Playwright coverage", status: "pass" },
]);
});
it("spreads ordinary flow scenarios across bounded shared batches", async () => {
const repoRoot = await makeTempRepo("qa-suite-shared-batches-");
await runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/smoke",
concurrency: 8,
scenarioIds: [
"channel-chat-baseline",
"dm-chat-baseline",
"thread-follow-up",
"control-ui-chat-flow-playwright",
],
});
const outputDir = path.join(repoRoot, ".artifacts", "qa-e2e", "smoke");
expect(runQaFlowSuite).toHaveBeenCalledTimes(3);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "shared-1"),
concurrency: 1,
scenarioIds: ["channel-chat-baseline"],
}),
);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "shared-2"),
concurrency: 1,
scenarioIds: ["dm-chat-baseline"],
}),
);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
3,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "shared-3"),
concurrency: 1,
scenarioIds: ["thread-follow-up"],
}),
);
});
it("isolates flow scenarios that mutate shared runtime state", async () => {
const repoRoot = await makeTempRepo("qa-suite-shared-state-");
await runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/smoke",
concurrency: 8,
scenarioIds: [
"channel-chat-baseline",
"runtime-tool-image-generate",
"runtime-inventory-drift-check",
"session-memory-ranking",
"control-ui-chat-flow-playwright",
],
});
const outputDir = path.join(repoRoot, ".artifacts", "qa-e2e", "smoke");
expect(runQaFlowSuite).toHaveBeenCalledTimes(2);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "shared"),
concurrency: 1,
scenarioIds: ["channel-chat-baseline"],
}),
);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "isolated"),
concurrency: 3,
workerStartStaggerMs: 500,
scenarioIds: [
"runtime-tool-image-generate",
"runtime-inventory-drift-check",
"session-memory-ranking",
],
}),
);
});
it("isolates flow scenarios that restart after state mutations", async () => {
const repoRoot = await makeTempRepo("qa-suite-gateway-state-");
await runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/gateway-state",
concurrency: 8,
scenarioIds: [
"channel-chat-baseline",
"subagent-stale-child-links",
"control-ui-chat-flow-playwright",
],
});
const outputDir = path.join(repoRoot, ".artifacts", "qa-e2e", "gateway-state");
expect(runQaFlowSuite).toHaveBeenCalledTimes(2);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "shared"),
scenarioIds: ["channel-chat-baseline"],
}),
);
expect(runQaFlowSuite).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
outputDir: path.join(outputDir, "flow", "isolated"),
scenarioIds: ["subagent-stale-child-links"],
}),
);
});
it("preserves configured isolated worker start stagger overrides", async () => {
vi.stubEnv("OPENCLAW_QA_SUITE_WORKER_START_STAGGER_MS", "2500");
const repoRoot = await makeTempRepo("qa-suite-stagger-env-");
await runQaSuite({
repoRoot,
outputDir: ".artifacts/qa-e2e/stagger-env",
concurrency: 8,
scenarioIds: [
"runtime-tool-image-generate",
"runtime-inventory-drift-check",
"session-memory-ranking",
"control-ui-chat-flow-playwright",
],
});
const outputDir = path.join(repoRoot, ".artifacts", "qa-e2e", "stagger-env");
expect(runQaFlowSuite).toHaveBeenCalledWith(
expect.objectContaining({
outputDir: path.join(outputDir, "flow"),
concurrency: 3,
workerStartStaggerMs: 2500,
scenarioIds: [
"runtime-tool-image-generate",
"runtime-inventory-drift-check",
"session-memory-ranking",
],
}),
);
});
it("rejects runtime-pair requests for Vitest/Playwright scenarios", async () => {
await expect(
runQaSuite({

View File

@@ -12,21 +12,12 @@ import {
} from "./evidence-summary.js";
import { isQaFastModeEnabled } from "./model-selection.js";
import { DEFAULT_QA_PROVIDER_MODE } from "./providers/index.js";
import {
defaultQaSuiteConcurrencyForTransport,
normalizeQaTransportId,
} from "./qa-transport-registry.js";
import { defaultQaModelForMode, normalizeQaProviderMode } from "./run-config.js";
import {
readQaBootstrapScenarioCatalog,
type QaSeedScenarioWithSource,
} from "./scenario-catalog.js";
import {
normalizeQaSuiteConcurrency,
resolveQaSuiteOutputDir,
resolveQaSuiteWorkerStartStaggerMs,
scenarioRequiresIsolatedQaSuiteWorker,
} from "./suite-planning.js";
import { normalizeQaSuiteConcurrency, resolveQaSuiteOutputDir } from "./suite-planning.js";
import {
buildQaSuiteSummaryJson,
type QaSuiteResult,
@@ -72,40 +63,11 @@ type QaSuiteExecutionPlan =
testFileScenariosByKind: Map<QaTestFileExecutionKind, QaTestFileScenario[]>;
};
const MAX_SHARED_FLOW_PARTITIONS = 4;
const MAX_ISOLATED_FLOW_CONCURRENCY = 8;
const ISOLATED_FLOW_WORKER_START_STAGGER_MS = 500;
type QaUnifiedPartitionResult = {
evidenceSummaries: QaEvidenceSummaryJson[];
scenarioResults: Array<{
result: QaSuiteScenarioResult;
scenarioId: string;
}>;
};
type QaUnifiedPartitionTask = {
run: () => Promise<QaUnifiedPartitionResult>;
weight: number;
};
async function loadQaLabServerRuntime() {
const { startQaLabServer } = await import("./lab-server.js");
return startQaLabServer;
}
async function loadQaFlowSuiteRuntime() {
const [{ runQaFlowSuite }, startLab] = await Promise.all([
import("./suite.js"),
loadQaLabServerRuntime(),
]);
return async (params: QaSuiteRunParams | undefined) =>
await runQaFlowSuite({
...params,
startLab: params?.startLab ?? startLab,
});
}
function resolveRequestedScenarios(params: {
scenarioIds: readonly string[];
scenarios: ReturnType<typeof readQaBootstrapScenarioCatalog>["scenarios"];
@@ -194,100 +156,6 @@ function suitePartitionOutputDir(outputDir: string, kind: "flow" | QaTestFileExe
return path.join(outputDir, kind);
}
function flowSuitePartitionOutputDir(outputDir: string, partition: string) {
return path.join(suitePartitionOutputDir(outputDir, "flow"), partition);
}
function partitionSharedFlowScenarios(
scenarios: readonly QaSeedScenarioWithSource[],
concurrency: number,
) {
const partitionCount = Math.min(
Math.max(1, Math.floor(concurrency)),
MAX_SHARED_FLOW_PARTITIONS,
scenarios.length,
);
const partitions = Array.from({ length: partitionCount }, (): QaSeedScenarioWithSource[] => []);
for (const [index, scenario] of scenarios.entries()) {
const partition = partitions[index % partitionCount];
if (!partition) {
throw new Error("failed to partition shared QA flow scenarios");
}
partition.push(scenario);
}
return partitions.filter((partition) => partition.length > 0);
}
async function runWeightedUnifiedPartitionTasks(
tasks: readonly QaUnifiedPartitionTask[],
maxWeight: number,
) {
if (tasks.length === 0) {
return [];
}
const limit = Math.max(1, Math.floor(maxWeight));
const results: QaUnifiedPartitionResult[] = [];
let activeWeight = 0;
let settled = 0;
let nextIndex = 0;
return await new Promise<QaUnifiedPartitionResult[]>((resolve, reject) => {
let firstError: Error | undefined;
let finished = false;
const finishIfSettled = () => {
if (finished || activeWeight > 0) {
return;
}
finished = true;
if (firstError) {
reject(firstError);
return;
}
resolve(results);
};
const launch = () => {
if (firstError) {
finishIfSettled();
return;
}
while (nextIndex < tasks.length) {
const task = tasks[nextIndex];
if (!task) {
return;
}
const taskWeight = Math.max(1, Math.min(limit, Math.floor(task.weight)));
if (activeWeight > 0 && activeWeight + taskWeight > limit) {
return;
}
const index = nextIndex;
nextIndex += 1;
activeWeight += taskWeight;
task.run().then(
(result) => {
results[index] = result;
activeWeight -= taskWeight;
settled += 1;
if (settled === tasks.length) {
finishIfSettled();
return;
}
launch();
},
(error: unknown) => {
firstError = error instanceof Error ? error : new Error(String(error));
activeWeight -= taskWeight;
settled += 1;
finishIfSettled();
},
);
}
if (settled === tasks.length) {
finishIfSettled();
}
};
launch();
});
}
async function readQaSuiteEvidenceSummary(evidencePath: string) {
return validateQaEvidenceSummaryJson(JSON.parse(await fs.readFile(evidencePath, "utf8")));
}
@@ -429,134 +297,48 @@ async function runUnifiedQaSuite(params: {
typeof params.runParams?.fastMode === "boolean"
? params.runParams.fastMode
: isQaFastModeEnabled({ primaryModel, alternateModel });
const transportId = normalizeQaTransportId(params.runParams?.transportId);
const defaultConcurrency = params.runParams?.channelDriverSelection
? 1
: defaultQaSuiteConcurrencyForTransport(transportId);
const concurrency = normalizeQaSuiteConcurrency(
params.runParams?.concurrency,
params.plan.scenarios.length,
defaultConcurrency,
);
const evidenceSummaries: QaEvidenceSummaryJson[] = [];
const scenarioResultsById = new Map<string, QaSuiteScenarioResult>();
const partitionTasks: QaUnifiedPartitionTask[] = [];
if (params.plan.flowScenarios.length > 0) {
const sharedFlowScenarios = params.plan.flowScenarios.filter(
(scenario) => !scenarioRequiresIsolatedQaSuiteWorker(scenario),
);
const isolatedFlowScenarios = params.plan.flowScenarios.filter(
scenarioRequiresIsolatedQaSuiteWorker,
);
const sharedFlowPartitions = partitionSharedFlowScenarios(sharedFlowScenarios, concurrency);
const isolatedFlowConcurrency = Math.min(
concurrency,
MAX_ISOLATED_FLOW_CONCURRENCY,
isolatedFlowScenarios.length,
);
const isolatedFlowPartitions =
isolatedFlowConcurrency === 1 && isolatedFlowScenarios.length > 1
? isolatedFlowScenarios.map((scenario, index) => ({
kind: `isolated-${index + 1}`,
scenarios: [scenario],
concurrency: 1,
}))
: [
{
kind: "isolated",
scenarios: isolatedFlowScenarios,
concurrency: isolatedFlowConcurrency,
},
];
const flowPartitions = [
...sharedFlowPartitions.map((scenarios, index) => ({
kind: sharedFlowPartitions.length === 1 ? "shared" : `shared-${index + 1}`,
scenarios,
concurrency: 1,
})),
...isolatedFlowPartitions,
].filter((partition) => partition.scenarios.length > 0);
const runFlowSuite = await loadQaFlowSuiteRuntime();
for (const partition of flowPartitions) {
const isolatedPartition =
partition.kind === "isolated" || partition.kind.startsWith("isolated-");
partitionTasks.push({
weight: partition.concurrency,
run: async () => {
const result = await runFlowSuite({
...params.runParams,
outputDir:
flowPartitions.length === 1
? suitePartitionOutputDir(outputDir, "flow")
: flowSuitePartitionOutputDir(outputDir, partition.kind),
providerMode,
primaryModel,
alternateModel,
fastMode,
concurrency: partition.concurrency,
workerStartStaggerMs: isolatedPartition
? (params.runParams?.workerStartStaggerMs ??
resolveQaSuiteWorkerStartStaggerMs(
partition.concurrency,
process.env,
ISOLATED_FLOW_WORKER_START_STAGGER_MS,
))
: params.runParams?.workerStartStaggerMs,
scenarioIds: partition.scenarios.map((scenario) => scenario.id),
});
const scenarioResults: QaUnifiedPartitionResult["scenarioResults"] = [];
for (const [index, scenario] of partition.scenarios.entries()) {
const scenarioResult = result.scenarios[index];
if (scenarioResult) {
scenarioResults.push({ scenarioId: scenario.id, result: scenarioResult });
}
}
return {
evidenceSummaries: [await readQaSuiteEvidenceSummary(result.evidencePath)],
scenarioResults,
};
},
});
}
}
if (params.plan.testFileScenariosByKind.size > 0) {
partitionTasks.push({
weight: 1,
run: async () => {
const testFileEvidenceSummaries: QaEvidenceSummaryJson[] = [];
const testFileScenarioResults: QaUnifiedPartitionResult["scenarioResults"] = [];
for (const [kind, testFileScenarios] of params.plan.testFileScenariosByKind) {
const result = await runQaTestFileSuiteFromRuntime({
runParams: {
...params.runParams,
outputDir: suitePartitionOutputDir(outputDir, kind),
providerMode,
primaryModel,
scenarioIds: testFileScenarios.map((scenario) => scenario.id),
},
scenarios: testFileScenarios,
});
testFileEvidenceSummaries.push(await readQaSuiteEvidenceSummary(result.evidencePath));
testFileScenarioResults.push(
...result.results.map((scenarioResult) => ({
scenarioId: scenarioResult.scenario.id,
result: testFileScenarioResultToSuiteScenario(scenarioResult, repoRoot),
})),
);
}
return {
evidenceSummaries: testFileEvidenceSummaries,
scenarioResults: testFileScenarioResults,
};
},
const flowResult = await runQaFlowSuiteFromRuntime({
...params.runParams,
outputDir: suitePartitionOutputDir(outputDir, "flow"),
providerMode,
primaryModel,
alternateModel,
fastMode,
scenarioIds: params.plan.flowScenarios.map((scenario) => scenario.id),
});
}
const partitionResults = await runWeightedUnifiedPartitionTasks(partitionTasks, concurrency);
for (const partitionResult of partitionResults) {
for (const scenarioResult of partitionResult.scenarioResults) {
scenarioResultsById.set(scenarioResult.scenarioId, scenarioResult.result);
for (const [index, scenario] of params.plan.flowScenarios.entries()) {
const result = flowResult.scenarios[index];
if (result) {
scenarioResultsById.set(scenario.id, result);
}
}
evidenceSummaries.push(...partitionResult.evidenceSummaries);
evidenceSummaries.push(await readQaSuiteEvidenceSummary(flowResult.evidencePath));
}
for (const [kind, testFileScenarios] of params.plan.testFileScenariosByKind) {
const result = await runQaTestFileSuiteFromRuntime({
runParams: {
...params.runParams,
outputDir: suitePartitionOutputDir(outputDir, kind),
providerMode,
primaryModel,
scenarioIds: testFileScenarios.map((scenario) => scenario.id),
},
scenarios: testFileScenarios,
});
for (const scenarioResult of result.results) {
scenarioResultsById.set(
scenarioResult.scenario.id,
testFileScenarioResultToSuiteScenario(scenarioResult, repoRoot),
);
}
evidenceSummaries.push(await readQaSuiteEvidenceSummary(result.evidencePath));
}
const finishedAt = new Date();
const evidence = mergeQaEvidenceSummaries({
@@ -618,7 +400,10 @@ export async function runQaSuite(...args: [QaSuiteRunParams?]): Promise<QaSuiteR
export async function runQaFlowSuiteFromRuntime(
...args: [QaSuiteRunParams?]
): Promise<QaSuiteResult> {
return await (
await loadQaFlowSuiteRuntime()
)(args[0]);
const { runQaFlowSuite } = await import("./suite.js");
const params = args[0];
return await runQaFlowSuite({
...params,
startLab: params?.startLab ?? (await loadQaLabServerRuntime()),
});
}

View File

@@ -14,7 +14,6 @@ import {
resolveQaSuiteWorkerStartStaggerMs,
resolveQaSuiteOutputDir,
scenarioRequiresControlUi,
scenarioRequiresIsolatedQaSuiteWorker,
selectQaFlowSuiteScenarios,
shouldUseIsolatedQaSuiteScenarioWorkers,
} from "./suite-planning.js";
@@ -203,16 +202,6 @@ describe("qa suite planning helpers", () => {
}),
).toBe(1500);
}
expect(resolveQaSuiteWorkerStartStaggerMs(4, {}, 500)).toBe(500);
expect(
resolveQaSuiteWorkerStartStaggerMs(
4,
{
OPENCLAW_QA_SUITE_WORKER_START_STAGGER_MS: "25",
},
500,
),
).toBe(25);
});
it("keeps explicitly requested provider-specific scenarios", () => {
@@ -294,15 +283,6 @@ describe("qa suite planning helpers", () => {
).toThrow("Selected QA scenarios require multiple channels");
});
it("isolates flow scenarios with explicit suite isolation metadata", () => {
expect(
scenarioRequiresIsolatedQaSuiteWorker(
makeQaSuiteTestScenario("explicit-isolated", { suiteIsolation: "isolated" }),
),
).toBe(true);
expect(scenarioRequiresIsolatedQaSuiteWorker(makeQaSuiteTestScenario("plain"))).toBe(false);
});
it("collects unique scenario-declared bundled plugins in encounter order", () => {
const scenarios = [
makeQaSuiteTestScenario("generic", { plugins: ["active-memory", "memory-wiki"] }),

View File

@@ -12,12 +12,6 @@ import { applyQaMergePatch, isQaMergePatchObject } from "./suite-merge-patch.js"
const DEFAULT_QA_SUITE_CONCURRENCY = 64;
const DEFAULT_QA_SUITE_WORKER_START_STAGGER_MS = 1_500;
const QA_IMPLICIT_ISOLATION_FLOW_CALLS = new Set([
"ensureImageGenerationConfigured",
"forceMemoryIndex",
"patchConfig",
"writeWorkspaceSkill",
]);
type QaSeedScenario = ReturnType<typeof readQaBootstrapScenarioCatalog>["scenarios"][number];
@@ -215,35 +209,6 @@ function shouldUseIsolatedQaSuiteScenarioWorkers(params: {
);
}
function scenarioRequiresIsolatedQaSuiteWorker(scenario: QaSeedScenario) {
if (scenario.execution.kind !== "flow") {
return false;
}
return (
scenario.execution.suiteIsolation === "isolated" ||
isQaMergePatchObject(scenario.gatewayConfigPatch) ||
scenario.gatewayRuntime !== undefined ||
(Array.isArray(scenario.plugins) && scenario.plugins.length > 0) ||
normalizeLowercaseStringOrEmpty(scenario.surface) === "memory" ||
scenario.execution.config?.ensureImageGeneration === true ||
flowContainsImplicitIsolationCall(scenario.execution.flow)
);
}
function flowContainsImplicitIsolationCall(value: unknown): boolean {
if (Array.isArray(value)) {
return value.some(flowContainsImplicitIsolationCall);
}
if (!value || typeof value !== "object") {
return false;
}
const record = value as Record<string, unknown>;
if (typeof record.call === "string" && QA_IMPLICIT_ISOLATION_FLOW_CALLS.has(record.call)) {
return true;
}
return Object.values(record).some(flowContainsImplicitIsolationCall);
}
function scenarioRequiresControlUi(scenario: QaSeedScenario) {
return normalizeLowercaseStringOrEmpty(scenario.surface) === "control-ui";
}
@@ -266,18 +231,17 @@ function normalizeQaSuiteConcurrency(
function resolveQaSuiteWorkerStartStaggerMs(
concurrency: number,
env: NodeJS.ProcessEnv = process.env,
defaultStaggerMs = DEFAULT_QA_SUITE_WORKER_START_STAGGER_MS,
) {
if (concurrency <= 1) {
return 0;
}
const raw = env.OPENCLAW_QA_SUITE_WORKER_START_STAGGER_MS;
if (raw === undefined) {
return defaultStaggerMs;
return DEFAULT_QA_SUITE_WORKER_START_STAGGER_MS;
}
const parsed = parseStrictNonNegativeInteger(raw);
if (parsed === undefined) {
return defaultStaggerMs;
return DEFAULT_QA_SUITE_WORKER_START_STAGGER_MS;
}
return parsed;
}
@@ -365,7 +329,6 @@ export {
resolveQaSuiteWorkerStartStaggerMs,
resolveQaSuiteOutputDir,
scenarioRequiresControlUi,
scenarioRequiresIsolatedQaSuiteWorker,
scenarioMatchesQaProviderLane,
selectQaFlowSuiteScenarios,
shouldUseIsolatedQaSuiteScenarioWorkers,

View File

@@ -12,7 +12,6 @@ export function makeQaSuiteTestScenario(
gatewayConfigPatch?: Record<string, unknown>;
gatewayRuntime?: { forwardHostHome?: boolean; preserveDebugArtifacts?: boolean };
runtimeParityTier?: QaSuiteTestScenario["runtimeParityTier"];
suiteIsolation?: "isolated";
surface?: string;
} = {},
): QaSuiteTestScenario {
@@ -30,7 +29,6 @@ export function makeQaSuiteTestScenario(
execution: {
kind: "flow",
...(params.channel ? { channel: params.channel } : {}),
...(params.suiteIsolation ? { suiteIsolation: params.suiteIsolation } : {}),
...(params.config ? { config: params.config } : {}),
flow: { steps: [{ name: "noop", actions: [{ assert: "true" }] }] },
},

View File

@@ -150,7 +150,6 @@ export type QaSuiteRunParams = {
enabledPluginIds?: string[];
controlUiEnabled?: boolean;
transportReadyTimeoutMs?: number;
workerStartStaggerMs?: number;
forcedRuntime?: RuntimeId;
runtimePair?: [RuntimeId, RuntimeId];
captureRuntimeParityCell?: boolean;
@@ -468,7 +467,6 @@ function buildQaIsolatedScenarioWorkerParams(params: {
startLab: params.startLab,
controlUiEnabled: scenarioRequiresControlUi(params.scenario),
transportReadyTimeoutMs: params.input?.transportReadyTimeoutMs,
workerStartStaggerMs: params.input?.workerStartStaggerMs,
forcedRuntime: params.input?.forcedRuntime,
};
}
@@ -1289,8 +1287,7 @@ export async function runQaFlowSuite(params?: QaSuiteRunParams): Promise<QaSuite
try {
updateScenarioRun();
const workerStartStaggerMs =
params?.workerStartStaggerMs ?? resolveQaSuiteWorkerStartStaggerMs(concurrency);
const workerStartStaggerMs = resolveQaSuiteWorkerStartStaggerMs(concurrency);
writeQaSuiteProgress(progressEnabled, `scenario start stagger=${workerStartStaggerMs}ms`);
const scenarios: QaSuiteScenarioResult[] = await mapQaSuiteWithConcurrency(
selectedScenarios,

View File

@@ -1,6 +1,5 @@
{
"id": "qianfan",
"icon": "https://cdn.simpleicons.org/baidu/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "qqbot",
"name": "QQ Bot",
"description": "OpenClaw QQ Bot channel plugin for group and direct-message workflows.",
"icon": "https://cdn.simpleicons.org/qq/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "qwen",
"icon": "https://cdn.simpleicons.org/qwen/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "searxng",
"icon": "https://cdn.simpleicons.org/searxng/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "signal",
"icon": "https://cdn.simpleicons.org/signal/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "synology-chat",
"name": "Synology Chat",
"description": "Synology Chat channel plugin for OpenClaw channels and direct messages.",
"icon": "https://cdn.simpleicons.org/synology/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "telegram",
"icon": "https://cdn.simpleicons.org/telegram/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "twitch",
"name": "Twitch",
"description": "OpenClaw Twitch channel plugin for chat and moderation workflows.",
"icon": "https://cdn.simpleicons.org/twitch/111111",
"activation": {
"onStartup": false
},

View File

@@ -1,6 +1,5 @@
{
"id": "vercel-ai-gateway",
"icon": "https://cdn.simpleicons.org/vercel/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "whatsapp",
"name": "WhatsApp",
"description": "OpenClaw WhatsApp channel plugin for WhatsApp Web chats.",
"icon": "https://cdn.simpleicons.org/whatsapp/111111",
"skills": ["./skills"],
"activation": {
"onStartup": false

View File

@@ -1,6 +1,5 @@
{
"id": "xiaomi",
"icon": "https://cdn.simpleicons.org/xiaomi/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "zalo",
"name": "Zalo",
"description": "OpenClaw Zalo channel plugin for bot and webhook chats.",
"icon": "https://cdn.simpleicons.org/zalo/111111",
"activation": {
"onStartup": false
},

View File

@@ -2,7 +2,6 @@
"id": "zalouser",
"name": "Zalo Personal",
"description": "OpenClaw Zalo Personal Account plugin via native zca-js integration.",
"icon": "https://cdn.simpleicons.org/zalo/111111",
"activation": {
"onStartup": false
},

View File

@@ -1613,6 +1613,7 @@
"ios:build": "bash -lc './scripts/ios-configure-signing.sh && ./scripts/ios-write-version-xcconfig.sh && cd apps/ios && xcodegen generate && xcodebuild -project OpenClaw.xcodeproj -scheme OpenClaw -destination \"${IOS_DEST:-platform=iOS Simulator,name=iPhone 17}\" -configuration Debug build'",
"ios:gen": "bash -lc './scripts/ios-configure-signing.sh && ./scripts/ios-write-version-xcconfig.sh && cd apps/ios && xcodegen generate'",
"ios:open": "bash -lc './scripts/ios-configure-signing.sh && ./scripts/ios-write-version-xcconfig.sh && cd apps/ios && xcodegen generate && open OpenClaw.xcodeproj'",
"ios:release": "bash scripts/ios-release.sh",
"ios:release:archive": "bash scripts/ios-release-archive.sh",
"ios:release:prepare": "bash scripts/ios-release-prepare.sh",
"ios:release:signing:check": "bash -lc 'source ./scripts/lib/ios-fastlane.sh && cd apps/ios && run_ios_fastlane ios signing_check'",

View File

@@ -134,6 +134,7 @@ allowBuilds:
"@discordjs/opus": false
esbuild: true
koffi: false
node-llama-cpp: true
protobufjs: true
tree-sitter-bash: false
openclaw: true

View File

@@ -105,7 +105,7 @@ flow:
- lambda:
params: [text]
expr: "config.expectedReplyGroups.every((group) => group.some((needle) => normalizeLowercaseStringOrEmpty(text).includes(needle)))"
- expr: "env.providerMode === 'mock-openai' ? 10000 : 30000"
- expr: liveTurnTimeoutMs(env, 120000)
- expr: "env.providerMode === 'mock-openai' ? 100 : 250"
- if:
expr: "Boolean(env.mock)"
@@ -157,63 +157,31 @@ flow:
catchAs: attemptError
catch:
- if:
expr: "/timed out after/i.test(formatErrorMessage(attemptError))"
expr: "Boolean(env.mock) && /timed out after/i.test(formatErrorMessage(attemptError))"
then:
- call: readRawQaSessionStore
saveAs: timeoutStore
args:
- ref: env
- set: timeoutChildEntries
value:
expr: "Object.entries(timeoutStore).map(([key, entry]) => ({ ...entry, key })).filter((entry) => entry.spawnedBy === sessionKey)"
- set: timeoutChildRows
value:
expr: "timeoutChildEntries"
- set: timeoutAlphaSessionKey
value:
expr: "timeoutChildEntries.find((entry) => entry.label === alphaLabel)?.key ?? ''"
- set: timeoutBetaSessionKey
value:
expr: "timeoutChildEntries.find((entry) => entry.label === betaLabel)?.key ?? ''"
expr: "Object.values(timeoutStore).filter((entry) => entry.spawnedBy === sessionKey)"
- set: timeoutSawAlpha
value:
expr: "timeoutChildRows.some((entry) => entry.label === alphaLabel)"
- set: timeoutSawBeta
value:
expr: "timeoutChildRows.some((entry) => entry.label === betaLabel)"
- set: timeoutSpawnRequests
value:
expr: "[...(await fetchJson(`${env.mock.baseUrl}/debug/requests`))].filter((request) => request.plannedToolName === 'sessions_spawn' && /subagent fanout synthesis check/i.test(String(request.allInputText ?? '')))"
- if:
expr: "Boolean(env.mock)"
expr: "timeoutSawAlpha && timeoutSawBeta && timeoutSpawnRequests.length >= 2"
then:
- set: timeoutSpawnRequests
value:
expr: "[...(await fetchJson(`${env.mock.baseUrl}/debug/requests`))].filter((request) => request.plannedToolName === 'sessions_spawn' && /subagent fanout synthesis check/i.test(String(request.allInputText ?? '')))"
- if:
expr: "timeoutSawAlpha && timeoutSawBeta && timeoutSpawnRequests.length >= 2"
then:
- set: details
value: "subagent-1: ok\nsubagent-2: ok"
- set: lastError
value: __done__
else:
- set: timeoutAlphaTranscript
value:
expr: "timeoutAlphaSessionKey ? await readSessionTranscriptSummary(env, timeoutAlphaSessionKey) : null"
- set: timeoutBetaTranscript
value:
expr: "timeoutBetaSessionKey ? await readSessionTranscriptSummary(env, timeoutBetaSessionKey) : null"
- set: timeoutAlphaOk
value:
expr: "normalizeLowercaseStringOrEmpty(timeoutAlphaTranscript?.finalText) === 'ok'"
- set: timeoutBetaOk
value:
expr: "normalizeLowercaseStringOrEmpty(timeoutBetaTranscript?.finalText) === 'ok'"
- if:
expr: "timeoutSawAlpha && timeoutSawBeta && timeoutAlphaOk && timeoutBetaOk"
then:
- set: details
value: "subagent-1: ok\nsubagent-2: ok"
- set: lastError
value: __done__
- set: details
value: "subagent-1: ok\nsubagent-2: ok"
- set: lastError
value: __done__
- if:
expr: "lastError !== '__done__'"
then:

View File

@@ -24,8 +24,6 @@ scenario:
- extensions/qa-lab/src/gateway-child.ts
execution:
kind: flow
suiteIsolation: isolated
isolationReason: Seeds persisted gateway session/subagent state and restarts the gateway.
summary: Seed stale subagent session state on disk, restart the real gateway, then assert sessions.list filters only the stale child links.
flow:

View File

@@ -29,9 +29,6 @@ title: OpenClaw QA Scenario Pack
# - use `scenario.execution.kind: vitest`, `playwright`, or `script`
# plus `scenario.execution.path` for native tests or evidence producers that
# provide evidence without a top-level `flow`
# - use `scenario.execution.suiteIsolation: isolated` for flow scenarios that
# mutate gateway/runtime state in non-obvious ways; add `isolationReason`
# so reviewers know why the suite scheduler must not share the worker
# - use `runtimeParityTier` for runtime-pair gate membership: `standard`,
# `optional`, `live-only`, or `soak`
# - treat the old `coverage: ["id"]` / `coverage: - id` list shape as invalid

View File

@@ -29,8 +29,6 @@ scenario:
- scripts/e2e/kitchen-sink-plugin-docker.sh
execution:
kind: flow
suiteIsolation: isolated
isolationReason: Mutates gateway plugin/channel/tool config across gateway restarts.
summary: Install @openclaw/kitchen-sink, restart the gateway, exercise command inventory/tool/channel/OpenAI-or-block paths, and record CPU/RSS/log evidence.
config:
requiredProviderMode: live-frontier
@@ -96,6 +94,7 @@ scenario:
- only bundled plugins can register Codex app-server extension factories
- compaction provider "kitchen-sink-compaction-provider" registration missing summarize
- context engine registration missing id
- control UI descriptor registration requires id, surface, label, and valid optional fields
- hosted media resolver registration missing resolver
- "http route registration missing or invalid auth: /kitchen-sink/http-route"
- "plugin must declare contracts.embeddingProviders for adapter: kitchen-sink-embedding-provider"

View File

@@ -6,6 +6,10 @@ usage() {
Usage:
scripts/ios-release-prepare.sh --build-number 7 [--team-id TEAMID]
Optional custom relay:
OPENCLAW_PUSH_RELAY_BASE_URL=https://relay.example.com \
scripts/ios-release-prepare.sh --build-number 7 [--team-id TEAMID]
Prepares local App Store release inputs without touching local signing overrides:
- reads apps/ios/version.json and writes apps/ios/build/Version.xcconfig
- writes apps/ios/build/AppStoreRelease.xcconfig with canonical bundle IDs
@@ -28,6 +32,9 @@ CANONICAL_TEAM_ID="FWJYW4S8P8"
BUILD_NUMBER=""
TEAM_ID="${IOS_DEVELOPMENT_TEAM:-}"
DEFAULT_IOS_PUSH_RELAY_BASE_URL="https://ios-push-relay.openclaw.ai"
PUSH_RELAY_BASE_URL="${OPENCLAW_PUSH_RELAY_BASE_URL:-${IOS_PUSH_RELAY_BASE_URL:-${DEFAULT_IOS_PUSH_RELAY_BASE_URL}}}"
PUSH_RELAY_BASE_URL_XCCONFIG=""
IOS_VERSION=""
RELEASE_SIGNING_XCCONFIG=""
@@ -54,6 +61,31 @@ write_generated_file() {
mv -f "${tmp_file}" "${output_path}"
}
validate_push_relay_base_url() {
local value="$1"
if [[ "${value}" =~ [[:space:]] ]]; then
echo "Invalid OPENCLAW_PUSH_RELAY_BASE_URL: whitespace is not allowed." >&2
exit 1
fi
if [[ "${value}" == *'$'* || "${value}" == *'('* || "${value}" == *')'* || "${value}" == *'='* ]]; then
echo "Invalid OPENCLAW_PUSH_RELAY_BASE_URL: contains forbidden xcconfig characters." >&2
exit 1
fi
if [[ ! "${value}" =~ ^https://[A-Za-z0-9.-]+(:([0-9]{1,5}))?(/[A-Za-z0-9._~!&*+,;:@%/-]*)?$ ]]; then
echo "Invalid OPENCLAW_PUSH_RELAY_BASE_URL: expected https://host[:port][/path]." >&2
exit 1
fi
local port="${BASH_REMATCH[2]:-}"
if [[ -n "${port}" ]] && (( 10#${port} > 65535 )); then
echo "Invalid OPENCLAW_PUSH_RELAY_BASE_URL: port must be between 1 and 65535." >&2
exit 1
fi
}
require_option_value() {
local option="$1"
local value="${2-}"
@@ -112,10 +144,14 @@ if [[ "${TEAM_ID}" != "${CANONICAL_TEAM_ID}" ]]; then
exit 1
fi
if [[ -n "${OPENCLAW_PUSH_RELAY_BASE_URL:-}" || -n "${IOS_PUSH_RELAY_BASE_URL:-}" ]]; then
echo "iOS App Store release uses the canonical hosted push relay; custom relay URL overrides are not allowed." >&2
exit 1
fi
validate_push_relay_base_url "${PUSH_RELAY_BASE_URL}"
# `.xcconfig` treats `//` as a comment opener. Break the URL with a helper setting
# so Xcode still resolves it back to `https://...` at build time.
PUSH_RELAY_BASE_URL_XCCONFIG="$(
printf '%s' "${PUSH_RELAY_BASE_URL}" \
| sed 's#//#$(OPENCLAW_URL_SLASH)$(OPENCLAW_URL_SLASH)#g'
)"
prepare_build_dir
@@ -152,8 +188,13 @@ OPENCLAW_WATCH_APP_BUNDLE_ID = ai.openclawfoundation.app.watchkitapp
OPENCLAW_CODE_SIGN_ENTITLEMENTS = Sources/OpenClawAppAttest.entitlements
OPENCLAW_APNS_ENTITLEMENT_ENVIRONMENT = production
OPENCLAW_APP_ATTEST_ENVIRONMENT = production
OPENCLAW_PUSH_MODE = appStore
OPENCLAW_PUSH_RELAY_BASE_URL =
OPENCLAW_PUSH_TRANSPORT = relay
OPENCLAW_PUSH_DISTRIBUTION = official
OPENCLAW_URL_SLASH = /
OPENCLAW_PUSH_RELAY_BASE_URL = ${PUSH_RELAY_BASE_URL_XCCONFIG}
OPENCLAW_PUSH_APNS_ENVIRONMENT = production
OPENCLAW_PUSH_RELAY_PROFILE = production
OPENCLAW_PUSH_PROOF_POLICY = appleStrict
EOF
(

View File

@@ -51,5 +51,5 @@ done
(
cd "${ROOT_DIR}/apps/ios"
OPENCLAW_IOS_RELEASE_WRAPPER=1 IOS_RELEASE_BUILD_NUMBER="${BUILD_NUMBER}" run_ios_fastlane ios release_upload
IOS_RELEASE_BUILD_NUMBER="${BUILD_NUMBER}" run_ios_fastlane ios release_upload
)

5
scripts/ios-release.sh Executable file
View File

@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
exec bash "${ROOT_DIR}/scripts/ios-release-upload.sh" "$@"

View File

@@ -97,8 +97,12 @@ if [[ "${push_sandbox_simulator}" == "1" ]]; then
fi
xcodebuild_overrides+=(
"OPENCLAW_PUSH_MODE=simulatorSandbox"
"OPENCLAW_PUSH_TRANSPORT=relay"
"OPENCLAW_PUSH_DISTRIBUTION=official"
"OPENCLAW_PUSH_RELAY_BASE_URL=${push_relay_base_url}"
"OPENCLAW_PUSH_APNS_ENVIRONMENT=sandbox"
"OPENCLAW_PUSH_RELAY_PROFILE=simulatorSandbox"
"OPENCLAW_PUSH_PROOF_POLICY=internalSimulator"
"OPENCLAW_APNS_ENTITLEMENT_ENVIRONMENT=development"
)
fi

View File

@@ -1,195 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'EOF'
Usage:
scripts/ios-validate-app-store-ipa.sh --ipa apps/ios/build/app-store/OpenClaw-<version>.ipa
Validates the exported iOS App Store IPA before App Store Connect upload.
EOF
}
IPA_PATH=""
EXPECTED_TEAM_ID="FWJYW4S8P8"
EXPECTED_BUNDLE_ID="ai.openclawfoundation.app"
EXPECTED_PROFILE_NAME="OpenClaw App Store ai.openclawfoundation.app"
EXPECTED_APP_GROUP="group.ai.openclawfoundation.app.shared"
EXPECTED_PUSH_MODE="appStore"
PLIST_BUDDY_BIN="${IOS_VALIDATE_PLIST_BUDDY_BIN:-/usr/libexec/PlistBuddy}"
CODESIGN_BIN="${IOS_VALIDATE_CODESIGN_BIN:-codesign}"
SECURITY_BIN="${IOS_VALIDATE_SECURITY_BIN:-security}"
UNZIP_BIN="${IOS_VALIDATE_UNZIP_BIN:-unzip}"
require_option_value() {
local option="$1"
local value="${2-}"
if [[ -z "${value}" || "${value}" == --* ]]; then
echo "Missing value for ${option}." >&2
usage >&2
exit 1
fi
}
while [[ $# -gt 0 ]]; do
case "$1" in
--ipa)
require_option_value "$1" "${2-}"
IPA_PATH="$2"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
if [[ -z "${IPA_PATH}" ]]; then
echo "Missing required --ipa." >&2
usage >&2
exit 1
fi
if [[ ! -f "${IPA_PATH}" ]]; then
echo "IPA not found: ${IPA_PATH}" >&2
exit 1
fi
tmp_dir="$(mktemp -d -t openclaw-ios-ipa.XXXXXX)"
trap 'rm -rf "${tmp_dir}"' EXIT
"${UNZIP_BIN}" -q "${IPA_PATH}" -d "${tmp_dir}"
payload_dir="${tmp_dir}/Payload"
if [[ ! -d "${payload_dir}" ]]; then
echo "Invalid IPA: missing Payload directory." >&2
exit 1
fi
app_paths=()
while IFS= read -r app_bundle; do
app_paths+=("${app_bundle}")
done < <(find "${payload_dir}" -maxdepth 1 -type d -name "*.app" | sort)
if [[ "${#app_paths[@]}" -ne 1 ]]; then
echo "Invalid IPA: expected exactly one app bundle in Payload, found ${#app_paths[@]}." >&2
exit 1
fi
app_path="${app_paths[0]}"
info_plist="${app_path}/Info.plist"
embedded_profile="${app_path}/embedded.mobileprovision"
entitlements_plist="${tmp_dir}/entitlements.plist"
profile_plist="${tmp_dir}/profile.plist"
if [[ ! -f "${info_plist}" ]]; then
echo "Invalid IPA: missing app Info.plist." >&2
exit 1
fi
if [[ ! -f "${embedded_profile}" ]]; then
echo "Invalid IPA: missing embedded.mobileprovision." >&2
exit 1
fi
plist_value() {
local plist="$1"
local key_path="$2"
"${PLIST_BUDDY_BIN}" -c "Print:${key_path}" "${plist}" 2>/dev/null || true
}
plist_has_key() {
local plist="$1"
local key_path="$2"
"${PLIST_BUDDY_BIN}" -c "Print:${key_path}" "${plist}" >/dev/null 2>&1
}
assert_plist_string() {
local plist="$1"
local key_path="$2"
local expected="$3"
local label="$4"
local actual
actual="$(plist_value "${plist}" "${key_path}")"
if [[ "${actual}" != "${expected}" ]]; then
echo "Invalid IPA: ${label}; expected ${expected}, got ${actual:-missing}." >&2
exit 1
fi
}
assert_plist_key_absent() {
local plist="$1"
local key_path="$2"
local label="$3"
if plist_has_key "${plist}" "${key_path}"; then
echo "Invalid IPA: ${label} must not be present in App Store builds." >&2
exit 1
fi
}
assert_plist_array_contains() {
local plist="$1"
local key_path="$2"
local expected="$3"
local label="$4"
local raw
raw="$(plist_value "${plist}" "${key_path}")"
if ! printf '%s\n' "${raw}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | grep -Fxq "${expected}"; then
echo "Invalid IPA: ${label}; expected ${expected} in ${key_path}." >&2
exit 1
fi
}
assert_plist_empty_or_absent() {
local plist="$1"
local key_path="$2"
local label="$3"
local actual
actual="$(plist_value "${plist}" "${key_path}")"
if [[ -n "${actual}" ]]; then
echo "Invalid IPA: ${label} must be empty for App Store builds; got ${actual}." >&2
exit 1
fi
}
assert_plist_string "${info_plist}" "CFBundleIdentifier" "${EXPECTED_BUNDLE_ID}" "bundle identifier mismatch"
assert_plist_string "${info_plist}" "OpenClawPushMode" "${EXPECTED_PUSH_MODE}" "push mode mismatch"
assert_plist_empty_or_absent "${info_plist}" "OpenClawPushRelayBaseURL" "push relay URL override"
assert_plist_key_absent "${info_plist}" "OpenClawPushTransport" "legacy push transport"
assert_plist_key_absent "${info_plist}" "OpenClawPushDistribution" "legacy push distribution"
assert_plist_key_absent "${info_plist}" "OpenClawPushAPNsEnvironment" "legacy APNs environment"
assert_plist_key_absent "${info_plist}" "OpenClawPushRelayProfile" "legacy relay profile"
assert_plist_key_absent "${info_plist}" "OpenClawPushProofPolicy" "legacy proof policy"
if ! "${CODESIGN_BIN}" -d --entitlements :- "${app_path}" >"${entitlements_plist}" 2>"${tmp_dir}/codesign.err"; then
detail="$(<"${tmp_dir}/codesign.err")"
echo "Invalid IPA: failed to read signed entitlements${detail:+: ${detail}}" >&2
exit 1
fi
assert_plist_string "${entitlements_plist}" "application-identifier" "${EXPECTED_TEAM_ID}.${EXPECTED_BUNDLE_ID}" "signed application identifier mismatch"
assert_plist_string "${entitlements_plist}" "com.apple.developer.team-identifier" "${EXPECTED_TEAM_ID}" "signed team identifier mismatch"
assert_plist_string "${entitlements_plist}" "aps-environment" "production" "signed APNs entitlement mismatch"
assert_plist_string "${entitlements_plist}" "com.apple.developer.devicecheck.appattest-environment" "production" "signed App Attest entitlement mismatch"
assert_plist_array_contains "${entitlements_plist}" "com.apple.security.application-groups" "${EXPECTED_APP_GROUP}" "signed App Group entitlement mismatch"
if ! "${SECURITY_BIN}" cms -D -i "${embedded_profile}" >"${profile_plist}" 2>"${tmp_dir}/security.err"; then
detail="$(<"${tmp_dir}/security.err")"
echo "Invalid IPA: failed to decode embedded provisioning profile${detail:+: ${detail}}" >&2
exit 1
fi
assert_plist_string "${profile_plist}" "Name" "${EXPECTED_PROFILE_NAME}" "embedded profile name mismatch"
assert_plist_array_contains "${profile_plist}" "TeamIdentifier" "${EXPECTED_TEAM_ID}" "embedded profile team mismatch"
assert_plist_string "${profile_plist}" "Entitlements:application-identifier" "${EXPECTED_TEAM_ID}.${EXPECTED_BUNDLE_ID}" "embedded profile application identifier mismatch"
assert_plist_string "${profile_plist}" "Entitlements:aps-environment" "production" "embedded profile APNs entitlement mismatch"
assert_plist_array_contains "${profile_plist}" "Entitlements:com.apple.developer.devicecheck.appattest-environment" "production" "embedded profile App Attest entitlement mismatch"
assert_plist_array_contains "${profile_plist}" "Entitlements:com.apple.security.application-groups" "${EXPECTED_APP_GROUP}" "embedded profile App Group entitlement mismatch"
echo "Validated iOS App Store IPA: ${IPA_PATH}"

View File

@@ -163,8 +163,8 @@ let publicDeprecatedExportsByEntrypointBudget;
try {
budgets = {
publicEntrypoints: readBudgetEnv("OPENCLAW_PLUGIN_SDK_MAX_PUBLIC_ENTRYPOINTS", 321),
publicExports: readBudgetEnv("OPENCLAW_PLUGIN_SDK_MAX_PUBLIC_EXPORTS", 10349),
publicFunctionExports: readBudgetEnv("OPENCLAW_PLUGIN_SDK_MAX_PUBLIC_FUNCTION_EXPORTS", 5190),
publicExports: readBudgetEnv("OPENCLAW_PLUGIN_SDK_MAX_PUBLIC_EXPORTS", 10351),
publicFunctionExports: readBudgetEnv("OPENCLAW_PLUGIN_SDK_MAX_PUBLIC_FUNCTION_EXPORTS", 5192),
publicDeprecatedExports: readBudgetEnv(
"OPENCLAW_PLUGIN_SDK_MAX_PUBLIC_DEPRECATED_EXPORTS",
3247,

View File

@@ -85,8 +85,6 @@ type DerivedCoverageScores = QaMaturityCoverageScores & {
warnings: string[];
};
const MATURITY_DOC_OUTPUTS = ["maturity/scorecard.md", "maturity/taxonomy.md"] as const;
function parseArgs(argv: string[]): Args {
const args: Args = {
taxonomy: DEFAULT_TAXONOMY_PATH,
@@ -850,58 +848,14 @@ function writeOrCheck(outputPath: string, content: string, check: boolean): bool
return false;
}
function checkEvidenceIndependentInputs({
args,
scoresPath,
taxonomy,
taxonomyPath,
}: {
args: Args;
scoresPath: string;
taxonomy: QaMaturityTaxonomy;
taxonomyPath: string;
}): void {
const { warnings } = readValidatedQaMaturityScoreSources({
scoresPath,
taxonomy,
taxonomyPath,
});
writeInputWarnings(warnings);
if (args.strictInputs) {
enforceStrictInputs(warnings);
}
const missing = MATURITY_DOC_OUTPUTS.map((fileName) =>
path.join(args.outputDir, fileName),
).filter((outputPath) => !fs.existsSync(outputPath));
if (missing.length > 0) {
throw new Error(
`maturity docs check cannot skip evidence-backed freshness because generated docs are missing:\n${missing.map((file) => `- ${file}`).join("\n")}`,
);
}
}
function main(): void {
const args = parseArgs(process.argv.slice(2));
const taxonomyPath = path.normalize(args.taxonomy);
const scoresPath = path.normalize(args.scores);
const docsRoot = path.normalize(args.docsRoot);
const outputDir = path.normalize(args.outputDir);
const taxonomy = readQaMaturityTaxonomySource(taxonomyPath);
if (args.check && !args.evidenceDir?.trim()) {
checkEvidenceIndependentInputs({
args: { ...args, outputDir },
scoresPath,
taxonomy,
taxonomyPath,
});
process.stdout.write(
`maturity docs inputs are valid in ${outputDir}; evidence-backed freshness check skipped because --evidence-dir was not supplied\n`,
);
return;
}
const evidenceSummaries = readEvidenceSummaries(args.evidenceDir);
const taxonomy = readQaMaturityTaxonomySource(taxonomyPath);
const coverage = deriveCoverageScores(taxonomy, evidenceSummaries);
const { scores, warnings: scoreWarnings } = readValidatedQaMaturityScoreSources({
coverageScores: coverage,

View File

@@ -971,7 +971,10 @@ const TOOLING_SOURCE_TEST_TARGETS = new Map([
"test/scripts/security-sensitive-guard-workflow.test.ts",
],
],
["scripts/github/resolve-openclaw-ref.sh", ["test/scripts/resolve-openclaw-ref.test.ts"]],
[
"scripts/github/resolve-openclaw-ref.sh",
["test/scripts/resolve-openclaw-ref.test.ts"],
],
["scripts/ci-hydrate-testbox-env.sh", ["test/scripts/ci-hydrate-testbox-env.test.ts"]],
[
"scripts/github/run-openclaw-cross-os-release-checks.sh",
@@ -983,30 +986,37 @@ const TOOLING_SOURCE_TEST_TARGETS = new Map([
["scripts/ios-release-archive.sh", ["test/scripts/ios-release-wrapper-args.test.ts"]],
["scripts/ios-release-prepare.sh", ["test/scripts/ios-release-wrapper-args.test.ts"]],
["scripts/ios-release-signing.mjs", ["test/scripts/ios-release-signing.test.ts"]],
["apps/ios/fastlane/Fastfile", ["test/scripts/ios-release-fastlane-gates.test.ts"]],
[
"scripts/ios-release-upload.sh",
[
"test/scripts/ios-release-wrapper-args.test.ts",
"test/scripts/ios-release-fastlane-gates.test.ts",
],
],
["scripts/ios-validate-app-store-ipa.sh", ["test/scripts/ios-validate-app-store-ipa.test.ts"]],
["scripts/ios-release-upload.sh", ["test/scripts/ios-release-wrapper-args.test.ts"]],
["scripts/lib/restart-mac-gateway.sh", ["test/scripts/restart-mac.test.ts"]],
[
"scripts/openclaw-release-clawhub-runtime-state.ts",
["test/scripts/openclaw-release-clawhub-runtime-state.test.ts"],
],
["scripts/openclaw-release-clawhub-plan.ts", ["test/scripts/release-wrapper-scripts.test.ts"]],
[
"scripts/openclaw-release-clawhub-plan.ts",
["test/scripts/release-wrapper-scripts.test.ts"],
],
[
"scripts/plan-release-workflow-matrix.mjs",
["test/scripts/release-workflow-matrix-plan.test.ts"],
],
["scripts/release-fast-pretag-check.sh", ["test/scripts/package-acceptance-workflow.test.ts"]],
["scripts/plugin-clawhub-release-check.ts", ["test/scripts/release-wrapper-scripts.test.ts"]],
["scripts/plugin-clawhub-release-plan.ts", ["test/scripts/release-wrapper-scripts.test.ts"]],
["scripts/plugin-npm-release-check.ts", ["test/scripts/release-wrapper-scripts.test.ts"]],
["scripts/plugin-npm-release-plan.ts", ["test/scripts/release-wrapper-scripts.test.ts"]],
[
"scripts/plugin-clawhub-release-check.ts",
["test/scripts/release-wrapper-scripts.test.ts"],
],
[
"scripts/plugin-clawhub-release-plan.ts",
["test/scripts/release-wrapper-scripts.test.ts"],
],
[
"scripts/plugin-npm-release-check.ts",
["test/scripts/release-wrapper-scripts.test.ts"],
],
[
"scripts/plugin-npm-release-plan.ts",
["test/scripts/release-wrapper-scripts.test.ts"],
],
[
"scripts/plugin-release-pretag-pack-check.ts",
["test/scripts/plugin-release-pretag-pack-check.test.ts"],
@@ -1311,7 +1321,6 @@ const TOOLING_SOURCE_TEST_TARGETS = new Map([
["scripts/qa-lab-up.ts", ["test/scripts/qa-lab-up.test.ts"]],
["scripts/qa-coverage-report.ts", ["test/scripts/qa-report-cli.test.ts"]],
["scripts/qa-parity-report.ts", ["test/scripts/qa-report-cli.test.ts"]],
["scripts/qa/render-maturity-docs.ts", ["test/scripts/render-maturity-docs.test.ts"]],
[
"scripts/qa/ux-matrix-evidence-producer.ts",
["test/scripts/qa-ux-matrix-evidence-producer.test.ts"],

Some files were not shown because too many files have changed in this diff Show More