mirror of
https://github.com/openclaw/openclaw.git
synced 2026-06-06 22:11:38 +08:00
Compare commits
10 Commits
codex/exec
...
codex/open
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d8750cdab | ||
|
|
a18f9bc29c | ||
|
|
5d0dc24085 | ||
|
|
d4056692d6 | ||
|
|
deaab200f6 | ||
|
|
71cfa13192 | ||
|
|
d98f4f9df3 | ||
|
|
17affb4a61 | ||
|
|
cc32d032b5 | ||
|
|
fa20679dab |
@@ -16,36 +16,12 @@ Use this skill for Parallels guest workflows and smoke interpretation. Do not lo
|
||||
- Pass `--json` for machine-readable summaries.
|
||||
- Per-phase logs land under `/tmp/openclaw-parallels-*`.
|
||||
- Do not run local and gateway agent turns in parallel on the same fresh workspace or session.
|
||||
- For `prlctl exec`, pass the VM name before `--current-user` (`prlctl exec "$VM" --current-user ...`), not the other way around.
|
||||
- If the workflow installs OpenClaw from a repo checkout instead of the site installer/npm release, finish by installing a real guest CLI shim and verifying it in a fresh guest shell. `pnpm openclaw ...` inside the repo is not enough for handoff parity.
|
||||
- On macOS guests, prefer a user-global install plus a stable PATH-visible shim:
|
||||
- install with `NPM_CONFIG_PREFIX="$HOME/.npm-global" npm install -g .`
|
||||
- make sure `~/.local/bin/openclaw` exists or `~/.npm-global/bin` is on PATH
|
||||
- verify from a brand-new guest shell with `which openclaw` and `openclaw --version`
|
||||
|
||||
## npm install then update
|
||||
|
||||
- Preferred entrypoint: `pnpm test:parallels:npm-update`
|
||||
- Flow: fresh snapshot -> install npm package baseline -> smoke -> install current main tgz on the same guest -> smoke again.
|
||||
- Same-guest update verification should set the default model explicitly to `openai/gpt-5.4` before the agent turn and use a fresh explicit `--session-id` so old session model state does not leak into the check.
|
||||
- The aggregate npm-update wrapper must resolve the Linux VM with the same Ubuntu fallback policy as `parallels-linux-smoke.sh` before both fresh and update lanes. On Peter's current host, missing `Ubuntu 24.04.3 ARM64` should fall back to `Ubuntu 25.10`.
|
||||
- On Windows same-guest update checks, restart the gateway after the npm upgrade before `gateway status` / `agent`; in-place global npm updates can otherwise leave stale hashed `dist/*` module imports alive in the running service.
|
||||
- For Windows same-guest update checks, prefer the done-file/log-drain PowerShell runner pattern over one long-lived `prlctl exec ... powershell -EncodedCommand ...` transport. The guest can finish successfully while the outer `prlctl exec` still hangs.
|
||||
- Linux same-guest update verification should also export `HOME=/root`, pass `OPENAI_API_KEY` via `prlctl exec ... /usr/bin/env`, and use `openclaw agent --local`; the fresh Linux baseline does not rely on persisted gateway credentials.
|
||||
|
||||
## CLI invocation footgun
|
||||
|
||||
- The Parallels smoke shell scripts should tolerate a literal bare `--` arg so `pnpm test:parallels:* -- --json` and similar forwarded invocations work without needing to call `bash scripts/e2e/...` directly.
|
||||
|
||||
## macOS flow
|
||||
|
||||
- Preferred entrypoint: `pnpm test:parallels:macos`
|
||||
- Default to the snapshot closest to `macOS 26.3.1 latest`.
|
||||
- On Peter's Tahoe VM, `fresh-latest-march-2026` can hang in `prlctl snapshot-switch`; if restore times out there, rerun with `--snapshot-hint 'macOS 26.3.1 latest'` before blaming auth or the harness.
|
||||
- The macOS smoke should include a dashboard load phase after gateway health: resolve the tokenized URL with `openclaw dashboard --no-open`, verify the served HTML contains the Control UI title/root shell, then open Safari and require an established localhost TCP connection from Safari to the gateway port.
|
||||
- Target the snapshot closest to `macOS 26.3.1 fresh`.
|
||||
- `prlctl exec` is fine for deterministic repo commands, but use the guest Terminal or `prlctl enter` when installer parity or shell-sensitive behavior matters.
|
||||
- Multi-word `openclaw agent --message ...` checks should go through a guest shell wrapper (`guest_current_user_sh` / `guest_current_user_cli` or `/bin/sh -lc ...`), not raw `prlctl exec ... node openclaw.mjs ...`, or the message can be split into extra argv tokens and Commander reports `too many arguments for 'agent'`.
|
||||
- When ref-mode onboarding stores `OPENAI_API_KEY` as an env secret ref, the post-onboard agent verification should also export `OPENAI_API_KEY` for the guest command. The gateway can still reject with pairing-required and fall back to embedded execution, and that fallback needs the env-backed credential available in the shell.
|
||||
- On the fresh Tahoe snapshot, `brew` exists but `node` may be missing from PATH in noninteractive exec. Use `/opt/homebrew/bin/node` when needed.
|
||||
- Fresh host-served tgz installs should install as guest root with `HOME=/var/root`, then run onboarding as the desktop user via `prlctl exec --current-user`.
|
||||
- Root-installed tgz smoke can log plugin blocks for world-writable `extensions/*`; do not treat that as an onboarding or gateway failure unless plugin loading is the task.
|
||||
@@ -57,26 +33,17 @@ Use this skill for Parallels guest workflows and smoke interpretation. Do not lo
|
||||
- Always use `prlctl exec --current-user`; plain `prlctl exec` lands in `NT AUTHORITY\\SYSTEM`.
|
||||
- Prefer explicit `npm.cmd` and `openclaw.cmd`.
|
||||
- Use PowerShell only as the transport with `-ExecutionPolicy Bypass`, then call the `.cmd` shims from inside it.
|
||||
- Multi-word `openclaw agent --message ...` checks should call `& $openclaw ...` inside PowerShell, not `Start-Process ... -ArgumentList` against `openclaw.cmd`, or Commander can see split argv and throw `too many arguments for 'agent'`.
|
||||
- Windows installer/tgz phases now retry once after guest-ready recheck; keep new Windows smoke steps idempotent so a transport-flake retry is safe.
|
||||
- Windows global `npm install -g` phases can stay quiet for a minute or more even when healthy; inspect the phase log before calling it hung, and only treat it as a regression once the retry wrapper or timeout trips.
|
||||
- Fresh Windows ref-mode onboard should use the same background PowerShell runner plus done-file/log-drain pattern as the npm-update helper, including startup materialization checks, host-side timeouts on short poll `prlctl exec` calls, and retry-on-poll-failure behavior for transient transport flakes.
|
||||
- Fresh Windows ref-mode agent verification should set `OPENAI_API_KEY` in the PowerShell environment before invoking `openclaw.cmd agent`, for the same pairing-required fallback reason as macOS.
|
||||
- The Windows upgrade smoke lane should restart the managed gateway after `upgrade.install-main` and before `upgrade.onboard-ref`, or the old process can keep the previous gateway token and fail `gateway-health` with `unauthorized: gateway token mismatch`.
|
||||
- Keep onboarding and status output ASCII-clean in logs; fancy punctuation becomes mojibake in current capture paths.
|
||||
- If you hit an older run with `rc=255` plus an empty `fresh.install-main.log` or `upgrade.install-main.log`, treat it as a likely `prlctl exec` transport drop after guest start-up, not immediate proof of an npm/package failure.
|
||||
|
||||
## Linux flow
|
||||
|
||||
- Preferred entrypoint: `pnpm test:parallels:linux`
|
||||
- Use the snapshot closest to fresh `Ubuntu 24.04.3 ARM64`.
|
||||
- If that exact VM is missing on the host, fall back to the closest Ubuntu guest with a fresh poweroff snapshot. On Peter's host today, that is `Ubuntu 25.10`.
|
||||
- Use plain `prlctl exec`; `--current-user` is not the right transport on this snapshot.
|
||||
- Fresh snapshots may be missing `curl`, and `apt-get update` can fail on clock skew. Bootstrap with `apt-get -o Acquire::Check-Date=false update` and install `curl ca-certificates`.
|
||||
- Fresh `main` tgz smoke still needs the latest-release installer first because the snapshot has no Node or npm before bootstrap.
|
||||
- This snapshot does not have a usable `systemd --user` session; managed daemon install is unsupported.
|
||||
- `prlctl exec` reaps detached Linux child processes on this snapshot, so detached background gateway runs are not trustworthy smoke signals.
|
||||
- Treat `gateway=skipped-no-detached-linux-gateway` plus `daemon=systemd-user-unavailable` as baseline on that Linux lane, not a regression.
|
||||
|
||||
## Discord roundtrip
|
||||
|
||||
|
||||
@@ -11,13 +11,11 @@ Use this skill for release and publish-time workflow. Keep ordinary development
|
||||
|
||||
- Do not change version numbers without explicit operator approval.
|
||||
- Ask permission before any npm publish or release step.
|
||||
- This skill should be sufficient to drive the normal release flow end-to-end.
|
||||
- Use the private maintainer release docs for credentials, recovery steps, and mac signing/notary specifics, and use `docs/reference/RELEASING.md` for public policy.
|
||||
- Core `openclaw` publish is manual `workflow_dispatch`; creating or pushing a tag does not publish by itself.
|
||||
- Use the private maintainer release docs for the actual runbook and `docs/reference/RELEASING.md` for public policy.
|
||||
|
||||
## Keep release channel naming aligned
|
||||
|
||||
- `stable`: tagged releases only, published to npm `latest` and then mirrored onto npm `beta` unless `beta` already points at a newer prerelease
|
||||
- `stable`: tagged releases only, with npm dist-tag `latest`
|
||||
- `beta`: prerelease tags like `vYYYY.M.D-beta.N`, with npm dist-tag `beta`
|
||||
- Prefer `-beta.N`; do not mint new `-1` or `-2` beta suffixes
|
||||
- `dev`: moving head on `main`
|
||||
@@ -33,19 +31,8 @@ Use this skill for release and publish-time workflow. Keep ordinary development
|
||||
- `apps/macos/Sources/OpenClaw/Resources/Info.plist`
|
||||
- `docs/install/updating.md`
|
||||
- Peekaboo Xcode project and plist version fields
|
||||
- Before creating a release tag, make every version location above match the version encoded by that tag.
|
||||
- For fallback correction tags like `vYYYY.M.D-N`, the repo version locations still stay at `YYYY.M.D`.
|
||||
- “Bump version everywhere” means all version locations above except `appcast.xml`.
|
||||
- Release signing and notary credentials live outside the repo in the private maintainer docs.
|
||||
- Every OpenClaw release ships the npm package and macOS app together.
|
||||
- The production Sparkle feed lives at `https://raw.githubusercontent.com/openclaw/openclaw/main/appcast.xml`, and the canonical published file is `appcast.xml` on `main` in the `openclaw` repo.
|
||||
- That shared production Sparkle feed is stable-only. Beta mac releases may
|
||||
upload assets to the GitHub prerelease, but they must not replace the shared
|
||||
`appcast.xml` unless a separate beta feed exists.
|
||||
- For fallback correction tags like `vYYYY.M.D-N`, the repo version still stays
|
||||
at `YYYY.M.D`, but the mac release must use a strictly higher numeric
|
||||
`APP_BUILD` / Sparkle build than the original release so existing installs
|
||||
see it as newer.
|
||||
|
||||
## Build changelog-backed release notes
|
||||
|
||||
@@ -72,166 +59,16 @@ pnpm test:install:smoke
|
||||
For a non-root smoke path:
|
||||
|
||||
```bash
|
||||
OPENCLAW_INSTALL_SMOKE_SKIP_NONROOT=1 pnpm test:install:smoke
|
||||
OPENCLAW_INSTALL_SMOKE_SKIP_NONROOT=1 pnpm test:install:smoke
|
||||
```
|
||||
|
||||
After npm publish, run:
|
||||
|
||||
```bash
|
||||
node --import tsx scripts/openclaw-npm-postpublish-verify.ts <published-version>
|
||||
```
|
||||
|
||||
- This verifies the published registry install path in a fresh temp prefix.
|
||||
- For stable correction releases like `YYYY.M.D-N`, it also verifies the
|
||||
upgrade path from `YYYY.M.D` to `YYYY.M.D-N` so a correction publish cannot
|
||||
silently leave existing global installs on the old base stable payload.
|
||||
|
||||
## Check all relevant release builds
|
||||
|
||||
- Always validate the OpenClaw npm release path before creating the tag.
|
||||
- Default release checks:
|
||||
- `pnpm check`
|
||||
- `pnpm build`
|
||||
- `node --import tsx scripts/release-check.ts`
|
||||
- `pnpm release:check`
|
||||
- `OPENCLAW_INSTALL_SMOKE_SKIP_NONROOT=1 pnpm test:install:smoke`
|
||||
- Check all release-related build surfaces touched by the release, not only the npm package.
|
||||
- Include mac release readiness in preflight by running the public validation
|
||||
workflow in `openclaw/openclaw` and the real mac preflight in
|
||||
`openclaw/releases-private` for every release.
|
||||
- Treat the `appcast.xml` update on `main` as part of mac release readiness, not an optional follow-up.
|
||||
- The workflows remain tag-based. The agent is responsible for making sure
|
||||
preflight runs complete successfully before any publish run starts.
|
||||
- Any fix after preflight means a new commit. Delete and recreate the tag and
|
||||
matching GitHub release from the fixed commit, then rerun preflight from
|
||||
scratch before publishing.
|
||||
- For stable mac releases, generate the signed `appcast.xml` before uploading
|
||||
public release assets so the updater feed cannot lag the published binaries.
|
||||
- Serialize stable appcast-producing runs across tags so two releases do not
|
||||
generate replacement `appcast.xml` files from the same stale seed.
|
||||
- For stable releases, confirm the latest beta already passed the broader release workflows before cutting stable.
|
||||
- If any required build, packaging step, or release workflow is red, do not say the release is ready.
|
||||
|
||||
## Use the right auth flow
|
||||
|
||||
- OpenClaw publish uses GitHub trusted publishing.
|
||||
- The publish run must be started manually with `workflow_dispatch`.
|
||||
- The npm workflow and the private mac publish workflow accept
|
||||
`preflight_only=true` to run validation/build/package steps without uploading
|
||||
public release assets.
|
||||
- The private mac workflow also accepts `smoke_test_only=true` for branch-safe
|
||||
workflow smoke tests that use ad-hoc signing, skip notarization, skip shared
|
||||
appcast generation, and do not prove release readiness.
|
||||
- `preflight_only=true` on the npm workflow is also the right way to validate an
|
||||
existing tag after publish; it should keep running the build checks even when
|
||||
the npm version is already published.
|
||||
- Validation-only runs may be dispatched from a branch when you are testing a
|
||||
workflow change before merge.
|
||||
- `.github/workflows/macos-release.yml` in `openclaw/openclaw` is now a
|
||||
public validation-only handoff. It validates the tag/release state and points
|
||||
operators to the private repo; it does not build or publish macOS artifacts.
|
||||
- Real mac preflight and real mac publish both use
|
||||
`openclaw/releases-private/.github/workflows/openclaw-macos-publish.yml`.
|
||||
- The private mac workflow runs on GitHub's xlarge macOS runner and uses a
|
||||
SwiftPM cache because the Swift build/test/package path is CPU-heavy.
|
||||
- Private mac preflight uploads notarized build artifacts as workflow artifacts
|
||||
instead of uploading public GitHub release assets.
|
||||
- Private smoke-test runs upload ad-hoc, non-notarized build artifacts as
|
||||
workflow artifacts and intentionally skip stable `appcast.xml` generation.
|
||||
- npm preflight, public mac validation, and private mac preflight must all pass
|
||||
before any real publish run starts.
|
||||
- Real publish runs must be dispatched from `main`; branch-dispatched publish
|
||||
attempts should fail before the protected environment is reached.
|
||||
- The release workflows stay tag-based; rely on the documented release sequence
|
||||
rather than workflow-level SHA pinning.
|
||||
- The `npm-release` environment must be approved by `@openclaw/openclaw-release-managers` before publish continues.
|
||||
- Mac publish uses
|
||||
`openclaw/releases-private/.github/workflows/openclaw-macos-publish.yml` for
|
||||
build, signing, notarization, packaged mac artifact generation, and
|
||||
stable-feed `appcast.xml` artifact generation.
|
||||
- Real private mac publish uploads the packaged `.zip`, `.dmg`, and
|
||||
`.dSYM.zip` assets to the existing GitHub release in `openclaw/openclaw`
|
||||
automatically when `OPENCLAW_PUBLIC_REPO_RELEASE_TOKEN` is present in the
|
||||
private repo `mac-release` environment.
|
||||
- For stable releases, the agent must also download the signed
|
||||
`macos-appcast-<tag>` artifact from the successful private mac workflow and
|
||||
then update `appcast.xml` on `main`.
|
||||
- For beta mac releases, do not update the shared production `appcast.xml`
|
||||
unless a separate beta Sparkle feed exists.
|
||||
- The private repo targets a dedicated `mac-release` environment. If the GitHub
|
||||
plan does not yet support required reviewers there, do not assume the
|
||||
environment alone is the approval boundary; rely on private repo access and
|
||||
CODEOWNERS until those settings can be enabled.
|
||||
- Do not use `NPM_TOKEN` or the plugin OTP flow for OpenClaw releases.
|
||||
- Core `openclaw` publish uses GitHub trusted publishing.
|
||||
- Do not use `NPM_TOKEN` or the plugin OTP flow for core releases.
|
||||
- `@openclaw/*` plugin publishes use a separate maintainer-only flow.
|
||||
- Only publish plugins that already exist on npm; bundled disk-tree-only plugins stay unpublished.
|
||||
|
||||
## Fallback local mac publish
|
||||
|
||||
- Keep the original local macOS publish workflow available as a fallback in case
|
||||
CI/CD mac publishing is unavailable or broken.
|
||||
- Preserve the existing maintainer workflow Peter uses: run it on a real Mac
|
||||
with local signing, notary, and Sparkle credentials already configured.
|
||||
- Follow the private maintainer macOS runbook for the local steps:
|
||||
`scripts/package-mac-dist.sh` to build, sign, notarize, and package the app;
|
||||
manual GitHub release asset upload; then `scripts/make_appcast.sh` plus the
|
||||
`appcast.xml` commit to `main`.
|
||||
- `scripts/package-mac-dist.sh` now fails closed for release builds if the
|
||||
bundled app comes out with a debug bundle id, an empty Sparkle feed URL, or a
|
||||
`CFBundleVersion` below the canonical Sparkle build floor for that short
|
||||
version. For correction tags, set a higher explicit `APP_BUILD`.
|
||||
- `scripts/make_appcast.sh` first uses `generate_appcast` from `PATH`, then
|
||||
falls back to the SwiftPM Sparkle tool output under `apps/macos/.build`.
|
||||
- For stable tags, the local fallback may update the shared production
|
||||
`appcast.xml`.
|
||||
- For beta tags, the local fallback still publishes the mac assets but must not
|
||||
update the shared production `appcast.xml` unless a separate beta feed exists.
|
||||
- Treat the local workflow as fallback only. Prefer the CI/CD publish workflow
|
||||
when it is working.
|
||||
- After any stable mac publish, verify all of the following before you call the
|
||||
release finished:
|
||||
- the GitHub release has `.zip`, `.dmg`, and `.dSYM.zip` assets
|
||||
- `appcast.xml` on `main` points at the new stable zip
|
||||
- the packaged app reports the expected short version and a numeric
|
||||
`CFBundleVersion` at or above the canonical Sparkle build floor
|
||||
|
||||
## Run the release sequence
|
||||
|
||||
1. Confirm the operator explicitly wants to cut a release.
|
||||
2. Choose the exact target version and git tag.
|
||||
3. Make every repo version location match that tag before creating it.
|
||||
4. Update `CHANGELOG.md` and assemble the matching GitHub release notes.
|
||||
5. Run the full preflight for all relevant release builds, including mac readiness.
|
||||
6. Confirm the target npm version is not already published.
|
||||
7. Create and push the git tag.
|
||||
8. Create or refresh the matching GitHub release.
|
||||
9. Start `.github/workflows/openclaw-npm-release.yml` with `preflight_only=true`
|
||||
and wait for it to pass.
|
||||
10. Start `.github/workflows/macos-release.yml` in `openclaw/openclaw` and wait
|
||||
for the public validation-only run to pass.
|
||||
11. Start
|
||||
`openclaw/releases-private/.github/workflows/openclaw-macos-publish.yml`
|
||||
with `preflight_only=true` and wait for it to pass.
|
||||
12. If any preflight or validation run fails, fix the issue on a new commit,
|
||||
delete the tag and matching GitHub release, recreate them from the fixed
|
||||
commit, and rerun all relevant preflights from scratch before continuing.
|
||||
Never reuse old preflight results after the commit changes.
|
||||
13. Start `.github/workflows/openclaw-npm-release.yml` with the same tag for
|
||||
the real publish.
|
||||
14. Wait for `npm-release` approval from `@openclaw/openclaw-release-managers`.
|
||||
15. Start
|
||||
`openclaw/releases-private/.github/workflows/openclaw-macos-publish.yml`
|
||||
for the real publish and wait for success.
|
||||
16. Verify the successful real private mac run uploaded the `.zip`, `.dmg`,
|
||||
and `.dSYM.zip` artifacts to the existing GitHub release in
|
||||
`openclaw/openclaw`.
|
||||
17. For stable releases, download `macos-appcast-<tag>` from the successful
|
||||
private mac run, update `appcast.xml` on `main`, and verify the feed.
|
||||
18. For beta releases, publish the mac assets but expect no shared production
|
||||
`appcast.xml` artifact and do not update the shared production feed unless a
|
||||
separate beta feed exists.
|
||||
19. After publish, verify npm and the attached release artifacts.
|
||||
|
||||
## GHSA advisory work
|
||||
|
||||
- Use `openclaw-ghsa-maintainer` for GHSA advisory inspection, patch/publish flow, private-fork validation, and GHSA API-specific publish checks.
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
---
|
||||
name: security-triage
|
||||
description: Triage GitHub security advisories for OpenClaw with high-confidence close/keep decisions, exact tag and commit verification, trust-model checks, optional hardening notes, and a final reply ready to post and copy to clipboard.
|
||||
---
|
||||
|
||||
# Security Triage
|
||||
|
||||
Use when reviewing OpenClaw security advisories, drafts, or GHSA reports.
|
||||
|
||||
Goal: high-confidence maintainers' triage without over-closing real issues or shipping unnecessary regressions.
|
||||
|
||||
## Close Bar
|
||||
|
||||
Close only if one of these is true:
|
||||
|
||||
- duplicate of an existing advisory or fixed issue
|
||||
- invalid against shipped behavior
|
||||
- out of scope under `SECURITY.md`
|
||||
- fixed before any affected release/tag
|
||||
|
||||
Do not close only because `main` is fixed. If latest shipped tag or npm release is affected, keep it open until released or published with the right status.
|
||||
|
||||
## Required Reads
|
||||
|
||||
Before answering:
|
||||
|
||||
1. Read `SECURITY.md`.
|
||||
2. Read the GHSA body with `gh api /repos/openclaw/openclaw/security-advisories/<GHSA>`.
|
||||
3. Inspect the exact implicated code paths.
|
||||
4. Verify shipped state:
|
||||
- `git tag --sort=-creatordate | head`
|
||||
- `npm view openclaw version --userconfig "$(mktemp)"`
|
||||
- `git tag --contains <fix-commit>`
|
||||
- if needed: `git show <tag>:path/to/file`
|
||||
5. Search for canonical overlap:
|
||||
- existing published GHSAs
|
||||
- older fixed bugs
|
||||
- same trust-model class already covered in `SECURITY.md`
|
||||
|
||||
## Review Method
|
||||
|
||||
For each advisory, decide:
|
||||
|
||||
- `close`
|
||||
- `keep open`
|
||||
- `keep open but narrow`
|
||||
|
||||
Check in this order:
|
||||
|
||||
1. Trust model
|
||||
- Is the prerequisite already inside trusted host/local/plugin/operator state?
|
||||
- Does `SECURITY.md` explicitly call this class out as out of scope or hardening-only?
|
||||
2. Shipped behavior
|
||||
- Is the bug present in the latest shipped tag or npm release?
|
||||
- Was it fixed before release?
|
||||
3. Exploit path
|
||||
- Does the report show a real boundary bypass, not just prompt injection, local same-user control, or helper-level semantics?
|
||||
4. Functional tradeoff
|
||||
- If a hardening change would reduce intended user functionality, call that out before proposing it.
|
||||
- Prefer fixes that preserve user workflows over deny-by-default regressions unless the boundary demands it.
|
||||
|
||||
## Response Format
|
||||
|
||||
When preparing a maintainer-ready close reply:
|
||||
|
||||
1. Print the GHSA URL first.
|
||||
2. Then draft a detailed response the maintainer can post.
|
||||
3. Include:
|
||||
- exact reason for close
|
||||
- exact code refs
|
||||
- exact shipped tag / release facts
|
||||
- exact fix commit or canonical duplicate GHSA when applicable
|
||||
- optional hardening note only if worthwhile and functionality-preserving
|
||||
|
||||
Keep tone firm, specific, non-defensive.
|
||||
|
||||
## Clipboard Step
|
||||
|
||||
After drafting the final post body, copy it:
|
||||
|
||||
```bash
|
||||
pbcopy <<'EOF'
|
||||
<final response>
|
||||
EOF
|
||||
```
|
||||
|
||||
Tell the user that the clipboard now contains the proposed response.
|
||||
|
||||
## Useful Commands
|
||||
|
||||
```bash
|
||||
gh api /repos/openclaw/openclaw/security-advisories/<GHSA>
|
||||
gh api /repos/openclaw/openclaw/security-advisories --paginate
|
||||
git tag --sort=-creatordate | head -n 20
|
||||
npm view openclaw version --userconfig "$(mktemp)"
|
||||
git tag --contains <commit>
|
||||
git show <tag>:<path>
|
||||
gh search issues --repo openclaw/openclaw --match title,body,comments -- "<terms>"
|
||||
gh search prs --repo openclaw/openclaw --match title,body,comments -- "<terms>"
|
||||
```
|
||||
|
||||
## Decision Notes
|
||||
|
||||
- “fixed on main, unreleased” is usually not a close.
|
||||
- “needs attacker-controlled trusted local state first” is usually out of scope.
|
||||
- “same-host same-user process can already read/write local state” is usually out of scope.
|
||||
- “helper function behaves differently than documented config semantics” is usually invalid.
|
||||
- If only the severity is wrong but the bug is real, keep it open and narrow the impact in the reply.
|
||||
15
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
15
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -9,8 +9,6 @@ body:
|
||||
value: |
|
||||
Thanks for filing this report. Keep every answer concise, reproducible, and grounded in observed evidence.
|
||||
Do not speculate or infer beyond the evidence. If a narrative section cannot be answered from the available evidence, respond with exactly `NOT_ENOUGH_INFO`.
|
||||
|
||||
If this is a plugin beta-release blocker, rename the issue title to `Beta blocker: <plugin-name> - <summary>` and apply the `beta-blocker` label after filing.
|
||||
- type: dropdown
|
||||
id: bug_type
|
||||
attributes:
|
||||
@@ -22,19 +20,6 @@ body:
|
||||
- Behavior bug (incorrect output/state without crash)
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: beta_blocker
|
||||
attributes:
|
||||
label: Beta release blocker
|
||||
description: >
|
||||
Choose `Yes` only if this blocks plugin compatibility during the current beta release window.
|
||||
Selecting `Yes` does not apply the label automatically. You must also rename the issue title
|
||||
to `Beta blocker: <plugin-name> - <summary>` for the automation to apply the `beta-blocker` label.
|
||||
options:
|
||||
- "No"
|
||||
- "Yes"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: summary
|
||||
attributes:
|
||||
|
||||
18
.github/actions/ensure-base-commit/action.yml
vendored
18
.github/actions/ensure-base-commit/action.yml
vendored
@@ -23,16 +23,6 @@ runs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! [[ "$BASE_SHA" =~ ^[0-9a-fA-F]{7,40}$ ]]; then
|
||||
echo "::error title=ensure-base-commit invalid base sha::Refusing invalid base SHA: $BASE_SHA"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if ! git check-ref-format --branch "$FETCH_REF" >/dev/null 2>&1; then
|
||||
echo "::error title=ensure-base-commit invalid fetch ref::Refusing invalid fetch ref: $FETCH_REF"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if git rev-parse --verify "$BASE_SHA^{commit}" >/dev/null 2>&1; then
|
||||
echo "Base commit already present: $BASE_SHA"
|
||||
exit 0
|
||||
@@ -40,9 +30,7 @@ runs:
|
||||
|
||||
for deepen_by in 25 100 300; do
|
||||
echo "Base commit missing; deepening $FETCH_REF by $deepen_by."
|
||||
if ! git fetch --no-tags --deepen="$deepen_by" origin -- "$FETCH_REF"; then
|
||||
echo "::warning title=ensure-base-commit fetch failed::Failed to deepen $FETCH_REF by $deepen_by while looking for $BASE_SHA"
|
||||
fi
|
||||
git fetch --no-tags --deepen="$deepen_by" origin "$FETCH_REF" || true
|
||||
if git rev-parse --verify "$BASE_SHA^{commit}" >/dev/null 2>&1; then
|
||||
echo "Resolved base commit after deepening: $BASE_SHA"
|
||||
exit 0
|
||||
@@ -50,9 +38,7 @@ runs:
|
||||
done
|
||||
|
||||
echo "Base commit still missing; fetching full history for $FETCH_REF."
|
||||
if ! git fetch --no-tags origin -- "$FETCH_REF"; then
|
||||
echo "::warning title=ensure-base-commit fetch failed::Failed to fetch full history for $FETCH_REF while looking for $BASE_SHA"
|
||||
fi
|
||||
git fetch --no-tags origin "$FETCH_REF" || true
|
||||
if git rev-parse --verify "$BASE_SHA^{commit}" >/dev/null 2>&1; then
|
||||
echo "Resolved base commit after full ref fetch: $BASE_SHA"
|
||||
exit 0
|
||||
|
||||
20
.github/actions/setup-node-env/action.yml
vendored
20
.github/actions/setup-node-env/action.yml
vendored
@@ -1,7 +1,7 @@
|
||||
name: Setup Node environment
|
||||
description: >
|
||||
Install Node 24 by default, pnpm, optionally Bun, and optionally run pnpm
|
||||
install. Requires actions/checkout to run first.
|
||||
Initialize submodules with retry, install Node 24 by default, pnpm, optionally Bun,
|
||||
and optionally run pnpm install. Requires actions/checkout to run first.
|
||||
inputs:
|
||||
node-version:
|
||||
description: Node.js version to install.
|
||||
@@ -34,6 +34,20 @@ inputs:
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Checkout submodules (retry)
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git submodule sync --recursive
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if git -c protocol.version=2 submodule update --init --force --depth=1 --recursive; then
|
||||
exit 0
|
||||
fi
|
||||
echo "Submodule update failed (attempt $attempt/5). Retrying…"
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
exit 1
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
@@ -49,7 +63,7 @@ runs:
|
||||
|
||||
- name: Setup Bun
|
||||
if: inputs.install-bun == 'true'
|
||||
uses: oven-sh/setup-bun@v2.2.0
|
||||
uses: oven-sh/setup-bun@v2.1.3
|
||||
with:
|
||||
bun-version: "1.3.9"
|
||||
|
||||
|
||||
12
.github/labeler.yml
vendored
12
.github/labeler.yml
vendored
@@ -221,14 +221,14 @@
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "extensions/open-prose/**"
|
||||
"extensions: qwen-portal-auth":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "extensions/qwen-portal-auth/**"
|
||||
"extensions: device-pair":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "extensions/device-pair/**"
|
||||
"extensions: duckduckgo":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "extensions/duckduckgo/**"
|
||||
"extensions: acpx":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
@@ -237,10 +237,6 @@
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "extensions/byteplus/**"
|
||||
"extensions: deepseek":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "extensions/deepseek/**"
|
||||
"extensions: anthropic":
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
|
||||
46
.github/pull_request_template.md
vendored
46
.github/pull_request_template.md
vendored
@@ -2,8 +2,6 @@
|
||||
|
||||
Describe the problem and fix in 2–5 bullets:
|
||||
|
||||
If this PR fixes a plugin beta-release blocker, title it `fix(<plugin-id>): beta blocker - <summary>` and link the matching `Beta blocker: <plugin-name> - <summary>` issue labeled `beta-blocker`. Contributors cannot label PRs, so the title is the PR-side signal for maintainers and automation.
|
||||
|
||||
- Problem:
|
||||
- Why it matters:
|
||||
- What changed:
|
||||
@@ -33,50 +31,12 @@ If this PR fixes a plugin beta-release blocker, title it `fix(<plugin-id>): beta
|
||||
|
||||
- Closes #
|
||||
- Related #
|
||||
- [ ] This PR fixes a bug or regression
|
||||
|
||||
## Root Cause / Regression History (if applicable)
|
||||
|
||||
For bug fixes or regressions, explain why this happened, not just what changed. Otherwise write `N/A`. If the cause is unclear, write `Unknown`.
|
||||
|
||||
- Root cause:
|
||||
- Missing detection / guardrail:
|
||||
- Prior context (`git blame`, prior PR, issue, or refactor if known):
|
||||
- Why this regressed now:
|
||||
- If unknown, what was ruled out:
|
||||
|
||||
## Regression Test Plan (if applicable)
|
||||
|
||||
For bug fixes or regressions, name the smallest reliable test coverage that should have caught this. Otherwise write `N/A`.
|
||||
|
||||
- Coverage level that should have caught this:
|
||||
- [ ] Unit test
|
||||
- [ ] Seam / integration test
|
||||
- [ ] End-to-end test
|
||||
- [ ] Existing coverage already sufficient
|
||||
- Target test or file:
|
||||
- Scenario the test should lock in:
|
||||
- Why this is the smallest reliable guardrail:
|
||||
- Existing test that already covers this (if any):
|
||||
- If no new test is added, why not:
|
||||
|
||||
## User-visible / Behavior Changes
|
||||
|
||||
List user-visible changes (including defaults/config).
|
||||
If none, write `None`.
|
||||
|
||||
## Diagram (if applicable)
|
||||
|
||||
For UI changes or non-trivial logic flows, include a small ASCII diagram reviewers can scan quickly. Otherwise write `N/A`.
|
||||
|
||||
```text
|
||||
Before:
|
||||
[user action] -> [old state]
|
||||
|
||||
After:
|
||||
[user action] -> [new state] -> [result]
|
||||
```
|
||||
|
||||
## Security Impact (required)
|
||||
|
||||
- New permissions/capabilities? (`Yes/No`)
|
||||
@@ -141,6 +101,12 @@ If a bot review conversation is addressed by this PR, resolve that conversation
|
||||
- Migration needed? (`Yes/No`)
|
||||
- If yes, exact upgrade steps:
|
||||
|
||||
## Failure Recovery (if this breaks)
|
||||
|
||||
- How to disable/revert this change quickly:
|
||||
- Files/config to restore:
|
||||
- Known bad symptoms reviewers should watch for:
|
||||
|
||||
## Risks and Mitigations
|
||||
|
||||
List only real risks for this PR. Add/remove entries as needed. If none, write `None`.
|
||||
|
||||
8
.github/workflows/auto-response.yml
vendored
8
.github/workflows/auto-response.yml
vendored
@@ -11,10 +11,6 @@ on:
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request_target' }}
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
@@ -402,13 +398,11 @@ jobs:
|
||||
const invalidLabel = "invalid";
|
||||
const spamLabel = "r: spam";
|
||||
const dirtyLabel = "dirty";
|
||||
const badBarnacleLabel = "bad-barnacle";
|
||||
const noisyPrMessage =
|
||||
"Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch.";
|
||||
|
||||
if (pullRequest) {
|
||||
// `bad-barnacle` exempts PRs that Barnacle incorrectly marked dirty.
|
||||
if (labelSet.has(dirtyLabel) && !labelSet.has(badBarnacleLabel)) {
|
||||
if (labelSet.has(dirtyLabel)) {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
|
||||
110
.github/workflows/ci-bun.yml
vendored
110
.github/workflows/ci-bun.yml
vendored
@@ -1,110 +0,0 @@
|
||||
name: CI Bun
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
group: ci-bun-push-${{ github.run_id }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
|
||||
jobs:
|
||||
preflight:
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
timeout-minutes: 20
|
||||
outputs:
|
||||
run_bun_checks: ${{ steps.manifest.outputs.run_bun_checks }}
|
||||
bun_checks_matrix: ${{ steps.manifest.outputs.bun_checks_matrix }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
- name: Setup Node environment
|
||||
uses: ./.github/actions/setup-node-env
|
||||
with:
|
||||
install-bun: "false"
|
||||
install-deps: "false"
|
||||
use-sticky-disk: "false"
|
||||
|
||||
- name: Build Bun CI manifest
|
||||
id: manifest
|
||||
env:
|
||||
OPENCLAW_CI_DOCS_ONLY: "false"
|
||||
OPENCLAW_CI_DOCS_CHANGED: "false"
|
||||
OPENCLAW_CI_RUN_NODE: "true"
|
||||
OPENCLAW_CI_RUN_MACOS: "false"
|
||||
OPENCLAW_CI_RUN_ANDROID: "false"
|
||||
OPENCLAW_CI_RUN_WINDOWS: "false"
|
||||
OPENCLAW_CI_RUN_SKILLS_PYTHON: "false"
|
||||
OPENCLAW_CI_HAS_CHANGED_EXTENSIONS: "false"
|
||||
OPENCLAW_CI_CHANGED_EXTENSIONS_MATRIX: '{"include":[]}'
|
||||
run: node scripts/ci-write-manifest-outputs.mjs --workflow ci-bun
|
||||
|
||||
build-bun-artifacts:
|
||||
needs: [preflight]
|
||||
if: needs.preflight.outputs.run_bun_checks == 'true'
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
- name: Setup Node environment
|
||||
uses: ./.github/actions/setup-node-env
|
||||
with:
|
||||
install-bun: "false"
|
||||
use-sticky-disk: "false"
|
||||
|
||||
- name: Build A2UI bundle
|
||||
run: pnpm canvas:a2ui:bundle
|
||||
|
||||
- name: Upload A2UI bundle artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: canvas-a2ui-bundle
|
||||
path: src/canvas-host/a2ui/
|
||||
include-hidden-files: true
|
||||
retention-days: 1
|
||||
|
||||
bun-checks:
|
||||
name: ${{ matrix.check_name }}
|
||||
needs: [preflight, build-bun-artifacts]
|
||||
if: needs.preflight.outputs.run_bun_checks == 'true'
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJson(needs.preflight.outputs.bun_checks_matrix) }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
- name: Setup Node environment
|
||||
uses: ./.github/actions/setup-node-env
|
||||
with:
|
||||
install-bun: "true"
|
||||
use-sticky-disk: "false"
|
||||
|
||||
- name: Download A2UI bundle artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: canvas-a2ui-bundle
|
||||
path: src/canvas-host/a2ui/
|
||||
|
||||
- name: Run Bun test shard
|
||||
env:
|
||||
SHARD_COUNT: ${{ matrix.shard_count }}
|
||||
SHARD_INDEX: ${{ matrix.shard_index }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
OPENCLAW_TEST_ISOLATE=1 bunx vitest run --config vitest.unit.config.ts --shard "$SHARD_INDEX/$SHARD_COUNT"
|
||||
1377
.github/workflows/ci.yml
vendored
1377
.github/workflows/ci.yml
vendored
File diff suppressed because it is too large
Load Diff
14
.github/workflows/docker-release.yml
vendored
14
.github/workflows/docker-release.yml
vendored
@@ -2,6 +2,8 @@ name: Docker Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- "v*"
|
||||
paths-ignore:
|
||||
@@ -13,12 +15,12 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Existing release tag to backfill (for example v2026.3.22)
|
||||
description: Existing release tag to backfill (for example v2026.3.13)
|
||||
required: true
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.event_name == 'workflow_dispatch' && format('docker-release-manual-{0}', inputs.tag) || format('docker-release-push-{0}', github.run_id) }}
|
||||
group: docker-release-${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
@@ -157,8 +159,6 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64
|
||||
cache-from: type=gha,scope=docker-release-amd64
|
||||
cache-to: type=gha,mode=max,scope=docker-release-amd64
|
||||
tags: ${{ steps.tags.outputs.value }}
|
||||
labels: ${{ steps.labels.outputs.value }}
|
||||
provenance: false
|
||||
@@ -171,8 +171,6 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64
|
||||
cache-from: type=gha,scope=docker-release-amd64
|
||||
cache-to: type=gha,mode=max,scope=docker-release-amd64
|
||||
build-args: |
|
||||
OPENCLAW_VARIANT=slim
|
||||
tags: ${{ steps.tags.outputs.slim }}
|
||||
@@ -274,8 +272,6 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/arm64
|
||||
cache-from: type=gha,scope=docker-release-arm64
|
||||
cache-to: type=gha,mode=max,scope=docker-release-arm64
|
||||
tags: ${{ steps.tags.outputs.value }}
|
||||
labels: ${{ steps.labels.outputs.value }}
|
||||
provenance: false
|
||||
@@ -288,8 +284,6 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/arm64
|
||||
cache-from: type=gha,scope=docker-release-arm64
|
||||
cache-to: type=gha,mode=max,scope=docker-release-arm64
|
||||
build-args: |
|
||||
OPENCLAW_VARIANT=slim
|
||||
tags: ${{ steps.tags.outputs.slim }}
|
||||
|
||||
79
.github/workflows/install-smoke.yml
vendored
79
.github/workflows/install-smoke.yml
vendored
@@ -4,87 +4,41 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.event_name == 'pull_request' && format('{0}-{1}', github.workflow, github.event.pull_request.number) || format('{0}-{1}', github.workflow, github.run_id) }}
|
||||
group: install-smoke-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
|
||||
jobs:
|
||||
preflight:
|
||||
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
|
||||
docs-scope:
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
outputs:
|
||||
docs_only: ${{ steps.manifest.outputs.docs_only }}
|
||||
run_install_smoke: ${{ steps.manifest.outputs.run_install_smoke }}
|
||||
docs_only: ${{ steps.check.outputs.docs_only }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
fetch-tags: false
|
||||
persist-credentials: false
|
||||
submodules: false
|
||||
|
||||
- name: Ensure preflight base commit
|
||||
- name: Ensure docs-scope base commit
|
||||
uses: ./.github/actions/ensure-base-commit
|
||||
with:
|
||||
base-sha: ${{ github.event_name == 'push' && github.event.before || github.event.pull_request.base.sha }}
|
||||
fetch-ref: ${{ github.event_name == 'push' && github.ref_name || github.event.pull_request.base.ref }}
|
||||
|
||||
- name: Detect docs-only changes
|
||||
id: docs_scope
|
||||
id: check
|
||||
uses: ./.github/actions/detect-docs-changes
|
||||
|
||||
- name: Detect changed smoke scope
|
||||
id: changed_scope
|
||||
if: steps.docs_scope.outputs.docs_only != 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
BASE="${{ github.event.before }}"
|
||||
else
|
||||
BASE="${{ github.event.pull_request.base.sha }}"
|
||||
fi
|
||||
|
||||
node scripts/ci-changed-scope.mjs --base "$BASE" --head HEAD
|
||||
|
||||
- name: Setup Node environment
|
||||
if: steps.docs_scope.outputs.docs_only != 'true'
|
||||
uses: ./.github/actions/setup-node-env
|
||||
with:
|
||||
install-bun: "false"
|
||||
install-deps: "false"
|
||||
use-sticky-disk: "false"
|
||||
|
||||
- name: Build install-smoke CI manifest
|
||||
id: manifest
|
||||
env:
|
||||
OPENCLAW_CI_DOCS_ONLY: ${{ steps.docs_scope.outputs.docs_only }}
|
||||
OPENCLAW_CI_DOCS_CHANGED: "false"
|
||||
OPENCLAW_CI_RUN_NODE: "false"
|
||||
OPENCLAW_CI_RUN_MACOS: "false"
|
||||
OPENCLAW_CI_RUN_ANDROID: "false"
|
||||
OPENCLAW_CI_RUN_WINDOWS: "false"
|
||||
OPENCLAW_CI_RUN_SKILLS_PYTHON: "false"
|
||||
OPENCLAW_CI_HAS_CHANGED_EXTENSIONS: "false"
|
||||
OPENCLAW_CI_CHANGED_EXTENSIONS_MATRIX: '{"include":[]}'
|
||||
OPENCLAW_CI_RUN_CHANGED_SMOKE: ${{ steps.changed_scope.outputs.run_changed_smoke || 'false' }}
|
||||
run: node scripts/ci-write-manifest-outputs.mjs --workflow install-smoke
|
||||
|
||||
install-smoke:
|
||||
needs: [preflight]
|
||||
if: needs.preflight.outputs.run_install_smoke == 'true'
|
||||
needs: [docs-scope]
|
||||
if: needs.docs-scope.outputs.docs_only != 'true'
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
env:
|
||||
DOCKER_BUILD_SUMMARY: "false"
|
||||
DOCKER_BUILD_RECORD_UPLOAD: "false"
|
||||
steps:
|
||||
- name: Checkout CLI
|
||||
uses: actions/checkout@v6
|
||||
@@ -99,8 +53,6 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
build-args: |
|
||||
OPENCLAW_DOCKER_APT_UPGRADE=0
|
||||
tags: openclaw-dockerfile-smoke:local
|
||||
load: true
|
||||
push: false
|
||||
@@ -119,7 +71,6 @@ jobs:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
build-args: |
|
||||
OPENCLAW_DOCKER_APT_UPGRADE=0
|
||||
OPENCLAW_EXTENSIONS=matrix
|
||||
tags: openclaw-ext-smoke:local
|
||||
load: true
|
||||
@@ -194,12 +145,12 @@ jobs:
|
||||
|
||||
- name: Run installer docker tests
|
||||
env:
|
||||
OPENCLAW_INSTALL_URL: https://openclaw.ai/install.sh
|
||||
OPENCLAW_INSTALL_CLI_URL: https://openclaw.ai/install-cli.sh
|
||||
OPENCLAW_NO_ONBOARD: "1"
|
||||
OPENCLAW_INSTALL_SMOKE_SKIP_CLI: "1"
|
||||
OPENCLAW_INSTALL_SMOKE_SKIP_IMAGE_BUILD: "1"
|
||||
OPENCLAW_INSTALL_NONROOT_SKIP_IMAGE_BUILD: ${{ github.event_name == 'pull_request' && '0' || '1' }}
|
||||
OPENCLAW_INSTALL_SMOKE_SKIP_NONROOT: ${{ github.event_name == 'pull_request' && '1' || '0' }}
|
||||
OPENCLAW_INSTALL_SMOKE_SKIP_PREVIOUS: "1"
|
||||
CLAWDBOT_INSTALL_URL: https://openclaw.ai/install.sh
|
||||
CLAWDBOT_INSTALL_CLI_URL: https://openclaw.ai/install-cli.sh
|
||||
CLAWDBOT_NO_ONBOARD: "1"
|
||||
CLAWDBOT_INSTALL_SMOKE_SKIP_CLI: "1"
|
||||
CLAWDBOT_INSTALL_SMOKE_SKIP_IMAGE_BUILD: "1"
|
||||
CLAWDBOT_INSTALL_NONROOT_SKIP_IMAGE_BUILD: ${{ github.event_name == 'pull_request' && '0' || '1' }}
|
||||
CLAWDBOT_INSTALL_SMOKE_SKIP_NONROOT: ${{ github.event_name == 'pull_request' && '1' || '0' }}
|
||||
CLAWDBOT_INSTALL_SMOKE_SKIP_PREVIOUS: "1"
|
||||
run: bash scripts/test-install-sh-docker.sh
|
||||
|
||||
164
.github/workflows/labeler.yml
vendored
164
.github/workflows/labeler.yml
vendored
@@ -2,9 +2,9 @@ name: Labeler
|
||||
|
||||
on:
|
||||
pull_request_target: # zizmor: ignore[dangerous-triggers] maintainer-owned triage workflow; no untrusted checkout or PR code execution
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
types: [opened, synchronize, reopened]
|
||||
issues:
|
||||
types: [opened, edited]
|
||||
types: [opened]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
max_prs:
|
||||
@@ -19,10 +19,6 @@ on:
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request_target' }}
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
@@ -209,59 +205,6 @@ jobs:
|
||||
// labels: [trustedLabel],
|
||||
// });
|
||||
// }
|
||||
- name: Apply beta-blocker title label
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
github-token: ${{ steps.app-token.outputs.token || steps.app-token-fallback.outputs.token }}
|
||||
script: |
|
||||
const pullRequest = context.payload.pull_request;
|
||||
if (!pullRequest) {
|
||||
return;
|
||||
}
|
||||
|
||||
const labelName = "beta-blocker";
|
||||
const matchesBetaBlocker = /\bbeta blocker\b/i.test(pullRequest.title ?? "");
|
||||
|
||||
try {
|
||||
await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: labelName,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error?.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
core.info(`Skipping ${labelName} labeling because the label does not exist in the repository.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentLabels = await github.paginate(github.rest.issues.listLabelsOnIssue, {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pullRequest.number,
|
||||
per_page: 100,
|
||||
});
|
||||
const hasLabel = currentLabels.some((label) => label.name === labelName);
|
||||
|
||||
if (matchesBetaBlocker && !hasLabel) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pullRequest.number,
|
||||
labels: [labelName],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!matchesBetaBlocker && hasLabel) {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pullRequest.number,
|
||||
name: labelName,
|
||||
});
|
||||
}
|
||||
- name: Apply too-many-prs label
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
@@ -472,7 +415,6 @@ jobs:
|
||||
const maxCount = processAll ? Number.POSITIVE_INFINITY : Math.max(1, maxPrs);
|
||||
|
||||
const sizeLabels = ["size: XS", "size: S", "size: M", "size: L", "size: XL"];
|
||||
const betaBlockerLabel = "beta-blocker";
|
||||
const labelColor = "b76e79";
|
||||
// const trustedLabel = "trusted-contributor";
|
||||
// const experiencedLabel = "experienced-contributor";
|
||||
@@ -503,22 +445,6 @@ jobs:
|
||||
}
|
||||
}
|
||||
|
||||
async function hasBetaBlockerLabel() {
|
||||
try {
|
||||
await github.rest.issues.getLabel({
|
||||
owner,
|
||||
repo,
|
||||
name: betaBlockerLabel,
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error?.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveContributorLabel(login) {
|
||||
if (contributorCache.has(login)) {
|
||||
return contributorCache.get(login);
|
||||
@@ -650,37 +576,7 @@ jobs:
|
||||
labelNames.add(label);
|
||||
}
|
||||
|
||||
async function applyBetaBlockerTitleLabel(pullRequest, labelNames) {
|
||||
const matchesBetaBlocker = /\bbeta blocker\b/i.test(pullRequest.title ?? "");
|
||||
|
||||
if (matchesBetaBlocker) {
|
||||
if (!labelNames.has(betaBlockerLabel)) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: pullRequest.number,
|
||||
labels: [betaBlockerLabel],
|
||||
});
|
||||
labelNames.add(betaBlockerLabel);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!labelNames.has(betaBlockerLabel)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await github.rest.issues.removeLabel({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: pullRequest.number,
|
||||
name: betaBlockerLabel,
|
||||
});
|
||||
labelNames.delete(betaBlockerLabel);
|
||||
}
|
||||
|
||||
await ensureSizeLabels();
|
||||
const betaBlockerLabelExists = await hasBetaBlockerLabel();
|
||||
|
||||
let page = 1;
|
||||
let processed = 0;
|
||||
@@ -718,9 +614,6 @@ jobs:
|
||||
|
||||
await applySizeLabel(pullRequest, currentLabels, labelNames);
|
||||
await applyContributorLabel(pullRequest, labelNames);
|
||||
if (betaBlockerLabelExists) {
|
||||
await applyBetaBlockerTitleLabel(pullRequest, labelNames);
|
||||
}
|
||||
|
||||
processed += 1;
|
||||
}
|
||||
@@ -822,56 +715,3 @@ jobs:
|
||||
// labels: [trustedLabel],
|
||||
// });
|
||||
// }
|
||||
- name: Apply beta-blocker title label
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
github-token: ${{ steps.app-token.outputs.token || steps.app-token-fallback.outputs.token }}
|
||||
script: |
|
||||
const issue = context.payload.issue;
|
||||
if (!issue || issue.pull_request) {
|
||||
return;
|
||||
}
|
||||
|
||||
const labelName = "beta-blocker";
|
||||
const matchesBetaBlocker = /^beta blocker:/i.test(issue.title ?? "");
|
||||
|
||||
try {
|
||||
await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: labelName,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error?.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
core.info(`Skipping ${labelName} labeling because the label does not exist in the repository.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentLabels = await github.paginate(github.rest.issues.listLabelsOnIssue, {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
per_page: 100,
|
||||
});
|
||||
const hasLabel = currentLabels.some((label) => label.name === labelName);
|
||||
|
||||
if (matchesBetaBlocker && !hasLabel) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
labels: [labelName],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!matchesBetaBlocker && hasLabel) {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
name: labelName,
|
||||
});
|
||||
}
|
||||
|
||||
92
.github/workflows/macos-release.yml
vendored
92
.github/workflows/macos-release.yml
vendored
@@ -1,92 +0,0 @@
|
||||
name: macOS Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Existing release tag to validate for macOS release handoff (for example v2026.3.22 or v2026.3.22-beta.1)
|
||||
required: true
|
||||
type: string
|
||||
preflight_only:
|
||||
description: Retained for operator compatibility; this public workflow is validation-only
|
||||
required: true
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
concurrency:
|
||||
group: macos-release-${{ inputs.tag }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
NODE_VERSION: "24.x"
|
||||
PNPM_VERSION: "10.23.0"
|
||||
|
||||
jobs:
|
||||
validate_macos_release_request:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Validate tag input format
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "${RELEASE_TAG}" =~ ^v[0-9]{4}\.[1-9][0-9]*\.[1-9][0-9]*((-beta\.[1-9][0-9]*)|(-[1-9][0-9]*))?$ ]]; then
|
||||
echo "Invalid release tag format: ${RELEASE_TAG}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Checkout selected tag
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: refs/tags/${{ inputs.tag }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node environment
|
||||
uses: ./.github/actions/setup-node-env
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
pnpm-version: ${{ env.PNPM_VERSION }}
|
||||
install-bun: "false"
|
||||
use-sticky-disk: "false"
|
||||
|
||||
- name: Ensure matching GitHub release exists
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
run: gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" >/dev/null
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: Build Control UI
|
||||
run: pnpm ui:build
|
||||
|
||||
- name: Validate release tag and package metadata
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
RELEASE_MAIN_REF: origin/main
|
||||
run: |
|
||||
set -euo pipefail
|
||||
RELEASE_SHA=$(git rev-parse HEAD)
|
||||
export RELEASE_SHA RELEASE_TAG RELEASE_MAIN_REF
|
||||
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
|
||||
pnpm release:openclaw:npm:check
|
||||
|
||||
- name: Summarize next step
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
{
|
||||
echo "## Public macOS validation only"
|
||||
echo
|
||||
echo "This workflow no longer builds, signs, notarizes, or uploads macOS assets."
|
||||
echo
|
||||
echo "Next step:"
|
||||
echo "- Run \`openclaw/releases-private/.github/workflows/openclaw-macos-publish.yml\` with tag \`${RELEASE_TAG}\`."
|
||||
echo "- Use \`preflight_only=true\` there for the full private mac preflight."
|
||||
echo "- For the real publish path, the private run uploads the packaged \`.zip\`, \`.dmg\`, and \`.dSYM.zip\` files to the existing GitHub release in \`openclaw/openclaw\` automatically."
|
||||
echo "- For stable releases, also download \`macos-appcast-${RELEASE_TAG}\` from the successful private run and commit \`appcast.xml\` back to \`main\` in \`openclaw/openclaw\`."
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
165
.github/workflows/openclaw-npm-release.yml
vendored
165
.github/workflows/openclaw-npm-release.yml
vendored
@@ -1,17 +1,15 @@
|
||||
name: OpenClaw NPM Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Release tag to publish (for example v2026.3.22, v2026.3.22-beta.1, or fallback v2026.3.22-1)
|
||||
description: Release tag to publish (for example v2026.3.14, v2026.3.14-beta.1, or fallback v2026.3.14-1)
|
||||
required: true
|
||||
type: string
|
||||
preflight_only:
|
||||
description: Run validation/build only and skip the gated publish job
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
|
||||
concurrency:
|
||||
group: openclaw-npm-release-${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref }}
|
||||
@@ -23,25 +21,15 @@ env:
|
||||
PNPM_VERSION: "10.23.0"
|
||||
|
||||
jobs:
|
||||
preflight_openclaw_npm:
|
||||
preview_openclaw_npm:
|
||||
if: github.event_name == 'push'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Validate tag input format
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "${RELEASE_TAG}" =~ ^v[0-9]{4}\.[1-9][0-9]*\.[1-9][0-9]*((-beta\.[1-9][0-9]*)|(-[1-9][0-9]*))?$ ]]; then
|
||||
echo "Invalid release tag format: ${RELEASE_TAG}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: refs/tags/${{ inputs.tag }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node environment
|
||||
@@ -52,39 +40,38 @@ jobs:
|
||||
install-bun: "false"
|
||||
use-sticky-disk: "false"
|
||||
|
||||
- name: Ensure version is not already published
|
||||
- name: Print release plan
|
||||
env:
|
||||
PREFLIGHT_ONLY: ${{ inputs.preflight_only }}
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
RELEASE_SHA=$(git rev-parse HEAD)
|
||||
PACKAGE_VERSION=$(node -p "require('./package.json').version")
|
||||
|
||||
if npm view "openclaw@${PACKAGE_VERSION}" version >/dev/null 2>&1; then
|
||||
if [[ "${PREFLIGHT_ONLY}" == "true" ]]; then
|
||||
echo "openclaw@${PACKAGE_VERSION} is already published on npm; continuing because preflight_only=true."
|
||||
exit 0
|
||||
fi
|
||||
echo "openclaw@${PACKAGE_VERSION} is already published on npm."
|
||||
exit 1
|
||||
if [[ "${RELEASE_TAG}" =~ ^v[0-9]{4}\.[1-9][0-9]*\.[1-9][0-9]*-[1-9][0-9]*$ ]]; then
|
||||
TAG_KIND="fallback correction"
|
||||
else
|
||||
TAG_KIND="standard"
|
||||
fi
|
||||
|
||||
echo "Publishing openclaw@${PACKAGE_VERSION}"
|
||||
|
||||
- name: Check
|
||||
run: pnpm check
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: Build Control UI
|
||||
run: pnpm ui:build
|
||||
echo "Release plan for ${RELEASE_TAG}:"
|
||||
echo "Resolved release SHA: ${RELEASE_SHA}"
|
||||
echo "Resolved package version: ${PACKAGE_VERSION}"
|
||||
echo "Resolved tag kind: ${TAG_KIND}"
|
||||
if [[ "${TAG_KIND}" == "fallback correction" ]]; then
|
||||
echo "Correction tag note: npm version remains ${PACKAGE_VERSION}"
|
||||
fi
|
||||
echo "Would run: git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main"
|
||||
echo "Would run with env: RELEASE_SHA=${RELEASE_SHA} RELEASE_TAG=${RELEASE_TAG} RELEASE_MAIN_REF=origin/main pnpm release:openclaw:npm:check"
|
||||
echo "Would run: npm view openclaw@${PACKAGE_VERSION} version"
|
||||
echo "Would run: pnpm check"
|
||||
echo "Would run: pnpm build"
|
||||
echo "Would run: pnpm release:check"
|
||||
|
||||
- name: Validate release tag and package metadata
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
RELEASE_MAIN_REF: origin/main
|
||||
run: |
|
||||
set -euo pipefail
|
||||
set -euxo pipefail
|
||||
RELEASE_SHA=$(git rev-parse HEAD)
|
||||
export RELEASE_SHA RELEASE_TAG RELEASE_MAIN_REF
|
||||
# Fetch the full main ref so merge-base ancestry checks keep working
|
||||
@@ -92,29 +79,54 @@ jobs:
|
||||
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
|
||||
pnpm release:openclaw:npm:check
|
||||
|
||||
- name: Verify release contents
|
||||
run: pnpm release:check
|
||||
|
||||
validate_publish_dispatch_ref:
|
||||
if: ${{ !inputs.preflight_only }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Require main workflow ref for publish
|
||||
- name: Ensure version is not already published
|
||||
env:
|
||||
WORKFLOW_REF: ${{ github.ref }}
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ "${WORKFLOW_REF}" != "refs/heads/main" ]]; then
|
||||
echo "Real publish runs must be dispatched from main. Use preflight_only=true for branch validation."
|
||||
set -euxo pipefail
|
||||
PACKAGE_VERSION=$(node -p "require('./package.json').version")
|
||||
IS_CORRECTION_TAG=0
|
||||
if [[ "${RELEASE_TAG}" =~ ^v[0-9]{4}\.[1-9][0-9]*\.[1-9][0-9]*-[1-9][0-9]*$ ]]; then
|
||||
IS_CORRECTION_TAG=1
|
||||
fi
|
||||
|
||||
if npm view "openclaw@${PACKAGE_VERSION}" version >/dev/null 2>&1; then
|
||||
if [[ "${IS_CORRECTION_TAG}" == "1" ]]; then
|
||||
echo "openclaw@${PACKAGE_VERSION} is already published on npm."
|
||||
echo "Correction tag ${RELEASE_TAG} is allowed as a fallback release tag, so preview will continue without treating this as an error."
|
||||
exit 0
|
||||
fi
|
||||
echo "openclaw@${PACKAGE_VERSION} is already published on npm."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "${IS_CORRECTION_TAG}" == "1" ]]; then
|
||||
echo "Previewing fallback correction tag ${RELEASE_TAG} for npm version openclaw@${PACKAGE_VERSION}"
|
||||
else
|
||||
echo "Previewing openclaw@${PACKAGE_VERSION}"
|
||||
fi
|
||||
|
||||
- name: Check
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
pnpm check
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
pnpm build
|
||||
|
||||
- name: Verify release contents
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
pnpm release:check
|
||||
|
||||
- name: Preview publish command
|
||||
run: bash scripts/openclaw-npm-publish.sh --dry-run
|
||||
|
||||
publish_openclaw_npm:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
# npm trusted publishing + provenance requires a GitHub-hosted runner.
|
||||
needs: [preflight_openclaw_npm, validate_publish_dispatch_ref]
|
||||
if: ${{ !inputs.preflight_only }}
|
||||
runs-on: ubuntu-latest
|
||||
environment: npm-release
|
||||
permissions:
|
||||
@@ -145,24 +157,6 @@ jobs:
|
||||
install-bun: "false"
|
||||
use-sticky-disk: "false"
|
||||
|
||||
- name: Ensure version is not already published
|
||||
run: |
|
||||
set -euo pipefail
|
||||
PACKAGE_VERSION=$(node -p "require('./package.json').version")
|
||||
|
||||
if npm view "openclaw@${PACKAGE_VERSION}" version >/dev/null 2>&1; then
|
||||
echo "openclaw@${PACKAGE_VERSION} is already published on npm."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Publishing openclaw@${PACKAGE_VERSION}"
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: Build Control UI
|
||||
run: pnpm ui:build
|
||||
|
||||
- name: Validate release tag and package metadata
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
@@ -176,5 +170,26 @@ jobs:
|
||||
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
|
||||
pnpm release:openclaw:npm:check
|
||||
|
||||
- name: Ensure version is not already published
|
||||
run: |
|
||||
set -euo pipefail
|
||||
PACKAGE_VERSION=$(node -p "require('./package.json').version")
|
||||
|
||||
if npm view "openclaw@${PACKAGE_VERSION}" version >/dev/null 2>&1; then
|
||||
echo "openclaw@${PACKAGE_VERSION} is already published on npm."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Publishing openclaw@${PACKAGE_VERSION}"
|
||||
|
||||
- name: Check
|
||||
run: pnpm check
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: Verify release contents
|
||||
run: pnpm release:check
|
||||
|
||||
- name: Publish
|
||||
run: bash scripts/openclaw-npm-publish.sh --publish
|
||||
|
||||
4
.github/workflows/sandbox-common-smoke.yml
vendored
4
.github/workflows/sandbox-common-smoke.yml
vendored
@@ -8,14 +8,13 @@ on:
|
||||
- Dockerfile.sandbox-common
|
||||
- scripts/sandbox-common-setup.sh
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
|
||||
paths:
|
||||
- Dockerfile.sandbox
|
||||
- Dockerfile.sandbox-common
|
||||
- scripts/sandbox-common-setup.sh
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
group: sandbox-common-smoke-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
@@ -23,7 +22,6 @@ env:
|
||||
|
||||
jobs:
|
||||
sandbox-common-smoke:
|
||||
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout
|
||||
|
||||
4
.github/workflows/stale.yml
vendored
4
.github/workflows/stale.yml
vendored
@@ -42,7 +42,7 @@ jobs:
|
||||
stale-issue-label: stale
|
||||
stale-pr-label: stale
|
||||
exempt-issue-labels: enhancement,maintainer,pinned,security,no-stale
|
||||
exempt-pr-labels: maintainer,no-stale,bad-barnacle
|
||||
exempt-pr-labels: maintainer,no-stale
|
||||
operations-per-run: 2000
|
||||
ascending: true
|
||||
exempt-all-assignees: true
|
||||
@@ -98,7 +98,7 @@ jobs:
|
||||
stale-issue-label: stale
|
||||
stale-pr-label: stale
|
||||
exempt-issue-labels: enhancement,maintainer,pinned,security,no-stale
|
||||
exempt-pr-labels: maintainer,no-stale,bad-barnacle
|
||||
exempt-pr-labels: maintainer,no-stale
|
||||
operations-per-run: 2000
|
||||
ascending: true
|
||||
exempt-all-assignees: true
|
||||
|
||||
17
.github/workflows/workflow-sanity.yml
vendored
17
.github/workflows/workflow-sanity.yml
vendored
@@ -7,7 +7,7 @@ on:
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
group: workflow-sanity-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
@@ -60,11 +60,8 @@ jobs:
|
||||
ACTIONLINT_VERSION="1.7.11"
|
||||
archive="actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz"
|
||||
base_url="https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}"
|
||||
# GitHub release downloads occasionally return transient 5xx responses.
|
||||
# Retry all curl errors here so workflow-sanity does not fail closed on
|
||||
# a one-off release edge outage.
|
||||
curl --retry 5 --retry-delay 2 --retry-all-errors -sSfL -o "${archive}" "${base_url}/${archive}"
|
||||
curl --retry 5 --retry-delay 2 --retry-all-errors -sSfL -o checksums.txt "${base_url}/actionlint_${ACTIONLINT_VERSION}_checksums.txt"
|
||||
curl -sSfL -o "${archive}" "${base_url}/${archive}"
|
||||
curl -sSfL -o checksums.txt "${base_url}/actionlint_${ACTIONLINT_VERSION}_checksums.txt"
|
||||
grep " ${archive}\$" checksums.txt | sha256sum -c -
|
||||
tar -xzf "${archive}" actionlint
|
||||
sudo install -m 0755 actionlint /usr/local/bin/actionlint
|
||||
@@ -75,10 +72,7 @@ jobs:
|
||||
- name: Disallow direct inputs interpolation in composite run blocks
|
||||
run: python3 scripts/check-composite-action-input-interpolation.py
|
||||
|
||||
- name: Disallow tracked merge conflict markers
|
||||
run: node scripts/check-no-conflict-markers.mjs
|
||||
|
||||
generated-doc-baselines:
|
||||
config-docs-drift:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
steps:
|
||||
@@ -93,6 +87,3 @@ jobs:
|
||||
|
||||
- name: Check config docs drift statefile
|
||||
run: pnpm config:docs:check
|
||||
|
||||
- name: Check plugin SDK API baseline drift
|
||||
run: pnpm plugin-sdk:api:check
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -85,7 +85,6 @@ apps/ios/*.mobileprovision
|
||||
# Local untracked files
|
||||
.local/
|
||||
docs/.local/
|
||||
docs/internal/
|
||||
tmp/
|
||||
IDENTITY.md
|
||||
USER.md
|
||||
@@ -138,6 +137,3 @@ docs/superpowers
|
||||
|
||||
# Deprecated changelog fragment workflow
|
||||
changelog/fragments/
|
||||
|
||||
# Local scratch workspace
|
||||
.tmp/
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
{
|
||||
"globs": ["docs/**/*.md", "docs/**/*.mdx", "README.md"],
|
||||
"ignores": [
|
||||
"docs/zh-CN/**",
|
||||
"docs/.i18n/**",
|
||||
"docs/reference/templates/**",
|
||||
"**/.local/**"
|
||||
],
|
||||
"ignores": ["docs/zh-CN/**", "docs/.i18n/**", "docs/reference/templates/**", "**/.local/**"],
|
||||
"config": {
|
||||
"default": true,
|
||||
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
**/node_modules/
|
||||
**/.runtime-deps-*/
|
||||
docs/.generated/
|
||||
|
||||
100
AGENTS.md
100
AGENTS.md
@@ -1,7 +1,7 @@
|
||||
# Repository Guidelines
|
||||
|
||||
- Repo: https://github.com/openclaw/openclaw
|
||||
- In chat replies, file references must be repo-root relative only (example: `src/telegram/index.ts:80`); never absolute paths or `~/...`.
|
||||
- In chat replies, file references must be repo-root relative only (example: `extensions/bluebubbles/src/channel.ts:80`); never absolute paths or `~/...`.
|
||||
- Do not edit files covered by security-focused `CODEOWNERS` rules unless a listed owner explicitly asked for the change or is already reviewing it with you. Treat those paths as restricted surfaces, not drive-by cleanup.
|
||||
|
||||
## Project Structure & Module Organization
|
||||
@@ -9,59 +9,16 @@
|
||||
- Source code: `src/` (CLI wiring in `src/cli`, commands in `src/commands`, web provider in `src/provider-web.ts`, infra in `src/infra`, media pipeline in `src/media`).
|
||||
- Tests: colocated `*.test.ts`.
|
||||
- Docs: `docs/` (images, queue, Pi config). Built output lives in `dist/`.
|
||||
- Nomenclature: use "plugin" / "plugins" in docs, UI, changelogs, and contributor guidance. The bundled workspace plugin tree remains the internal package layout to avoid repo-wide churn from a rename.
|
||||
- Bundled plugin naming: for repo-owned workspace plugins, keep the canonical plugin id aligned across `openclaw.plugin.json:id`, the default workspace folder name, and package names anchored to the same id (`@openclaw/<id>` or approved suffix forms like `-provider`, `-plugin`, `-speech`, `-sandbox`, `-media-understanding`). Keep `openclaw.install.npmSpec` equal to the package name and `openclaw.channel.id` equal to the plugin id when present. Exceptions must be explicit and covered by the repo invariant test.
|
||||
- Plugins: live in the bundled workspace plugin tree (workspace packages). Keep plugin-only deps in the extension `package.json`; do not add them to the root `package.json` unless core uses them.
|
||||
- Nomenclature: use "plugin" / "plugins" in docs, UI, changelogs, and contributor guidance. `extensions/*` remains the internal directory/package path to avoid repo-wide churn from a rename.
|
||||
- Plugins: live under `extensions/*` (workspace packages). Keep plugin-only deps in the extension `package.json`; do not add them to the root `package.json` unless core uses them.
|
||||
- Plugins: install runs `npm install --omit=dev` in plugin dir; runtime deps must live in `dependencies`. Avoid `workspace:*` in `dependencies` (npm install breaks); put `openclaw` in `devDependencies` or `peerDependencies` instead (runtime resolves `openclaw/plugin-sdk` via jiti alias).
|
||||
- Import boundaries: extension production code should treat `openclaw/plugin-sdk/*` plus local `api.ts` / `runtime-api.ts` barrels as the public surface. Do not import core `src/**`, `src/plugin-sdk-internal/**`, or another extension's `src/**` directly.
|
||||
- Installers served from `https://openclaw.ai/*`: live in the sibling repo `../openclaw.ai` (`public/install.sh`, `public/install-cli.sh`, `public/install.ps1`).
|
||||
- Messaging channels: always consider **all** built-in + extension channels when refactoring shared logic (routing, allowlists, pairing, command gating, onboarding, docs).
|
||||
- Core channel docs: `docs/channels/`
|
||||
- Core channel code: `src/telegram`, `src/discord`, `src/slack`, `src/signal`, `src/imessage`, `src/web` (WhatsApp web), `src/channels`, `src/routing`
|
||||
- Bundled plugin channels: the workspace plugin tree (for example Matrix, Zalo, ZaloUser, Voice Call)
|
||||
- When adding channels/plugins/apps/docs, update `.github/labeler.yml` and create matching GitHub labels (use existing channel/plugin label colors).
|
||||
|
||||
## Architecture Boundaries
|
||||
|
||||
- Start here for the repo map:
|
||||
- bundled workspace plugin tree = bundled plugins and the closest example surface for third-party plugins
|
||||
- `src/plugin-sdk/*` = the public plugin contract that extensions are allowed to import
|
||||
- `src/channels/*` = core channel implementation details behind the plugin/channel boundary
|
||||
- `src/plugins/*` = plugin discovery, manifest validation, loader, registry, and contract enforcement
|
||||
- `src/gateway/protocol/*` = typed Gateway control-plane and node wire protocol
|
||||
- Progressive disclosure lives in local boundary guides:
|
||||
- bundled-plugin-tree `AGENTS.md`
|
||||
- `src/plugin-sdk/AGENTS.md`
|
||||
- `src/channels/AGENTS.md`
|
||||
- `src/plugins/AGENTS.md`
|
||||
- `src/gateway/protocol/AGENTS.md`
|
||||
- Plugin and extension boundary:
|
||||
- Public docs: `docs/plugins/building-plugins.md`, `docs/plugins/architecture.md`, `docs/plugins/sdk-overview.md`, `docs/plugins/sdk-entrypoints.md`, `docs/plugins/sdk-runtime.md`, `docs/plugins/manifest.md`, `docs/plugins/sdk-channel-plugins.md`, `docs/plugins/sdk-provider-plugins.md`
|
||||
- Definition files: `src/plugin-sdk/plugin-entry.ts`, `src/plugin-sdk/core.ts`, `src/plugin-sdk/provider-entry.ts`, `src/plugin-sdk/channel-contract.ts`, `scripts/lib/plugin-sdk-entrypoints.json`, `package.json`
|
||||
- Rule: extensions must cross into core only through `openclaw/plugin-sdk/*`, manifest metadata, and documented runtime helpers. Do not import `src/**` from extension production code.
|
||||
- Rule: core code and tests must not deep-import bundled plugin internals such as a plugin's `src/**` files or `onboard.js`. If core needs a bundled plugin helper, expose it through that plugin's `api.ts` and, when it is a real cross-package contract, through `src/plugin-sdk/<id>.ts`.
|
||||
- Compatibility: new plugin seams are allowed, but they must be added as documented, backwards-compatible, versioned contracts. We have third-party plugins in the wild and do not break them casually.
|
||||
- Channel boundary:
|
||||
- Public docs: `docs/plugins/sdk-channel-plugins.md`, `docs/plugins/architecture.md`
|
||||
- Definition files: `src/channels/plugins/types.plugin.ts`, `src/channels/plugins/types.core.ts`, `src/channels/plugins/types.adapters.ts`, `src/plugin-sdk/core.ts`, `src/plugin-sdk/channel-contract.ts`
|
||||
- Rule: `src/channels/**` is core implementation. If plugin authors need a new seam, add it to the Plugin SDK instead of telling them to import channel internals.
|
||||
- Provider/model boundary:
|
||||
- Public docs: `docs/plugins/sdk-provider-plugins.md`, `docs/concepts/model-providers.md`, `docs/plugins/architecture.md`
|
||||
- Definition files: `src/plugins/types.ts`, `src/plugin-sdk/provider-entry.ts`, `src/plugin-sdk/provider-auth.ts`, `src/plugin-sdk/provider-catalog-shared.ts`, `src/plugin-sdk/provider-model-shared.ts`
|
||||
- Rule: core owns the generic inference loop; provider plugins own provider-specific behavior through registration and typed hooks. Do not solve provider needs by reaching into unrelated core internals.
|
||||
- Rule: avoid ad hoc reads of `plugins.entries.<id>.config` from unrelated core code. If core needs plugin-owned auth/config behavior, add or use a generic seam (`resolveSyntheticAuth`, public SDK/helper facades, manifest metadata, plugin auto-enable hooks) and honor plugin disablement plus SecretRef semantics.
|
||||
- Rule: vendor-owned tools and settings belong in the owning plugin. Do not add provider-specific tool config, secret collection, or runtime enablement to core `tools.*` surfaces unless the tool is intentionally core-owned.
|
||||
- Gateway protocol boundary:
|
||||
- Public docs: `docs/gateway/protocol.md`, `docs/gateway/bridge-protocol.md`, `docs/concepts/architecture.md`
|
||||
- Definition files: `src/gateway/protocol/schema.ts`, `src/gateway/protocol/schema/*.ts`, `src/gateway/protocol/index.ts`
|
||||
- Rule: protocol changes are contract changes. Prefer additive evolution; incompatible changes require explicit versioning, docs, and client/codegen follow-through.
|
||||
- Bundled plugin contract boundary:
|
||||
- Public docs: `docs/plugins/architecture.md`, `docs/plugins/manifest.md`, `docs/plugins/sdk-overview.md`
|
||||
- Definition files: `src/plugins/contracts/registry.ts`, `src/plugins/types.ts`, `src/plugins/public-artifacts.ts`
|
||||
- Rule: keep manifest metadata, runtime registration, public SDK exports, and contract tests aligned. Do not create a hidden path around the declared plugin interfaces.
|
||||
- Extension test boundary:
|
||||
- Keep extension-owned onboarding/config/provider coverage under the owning bundled plugin package when feasible.
|
||||
- If core tests need bundled plugin behavior, consume it through public `src/plugin-sdk/<id>.ts` facades or the plugin's `api.ts`, not private extension modules.
|
||||
- Extensions (channel plugins): `extensions/*` (e.g. `extensions/msteams`, `extensions/matrix`, `extensions/zalo`, `extensions/zalouser`, `extensions/voice-call`)
|
||||
- When adding channels/extensions/apps/docs, update `.github/labeler.yml` and create matching GitHub labels (use existing channel/extension label colors).
|
||||
|
||||
## Docs Linking (Mintlify)
|
||||
|
||||
@@ -71,7 +28,7 @@
|
||||
- For docs, UI copy, and picker lists, order services/providers alphabetically unless the section is explicitly describing runtime behavior (for example auto-detection or execution order).
|
||||
- Section cross-references: use anchors on root-relative paths (example: `[Hooks](/configuration#hooks)`).
|
||||
- Doc headings and anchors: avoid em dashes and apostrophes in headings because they break Mintlify anchor links.
|
||||
- When the user asks for links, reply with full `https://docs.openclaw.ai/...` URLs (not root-relative).
|
||||
- When Peter asks for links, reply with full `https://docs.openclaw.ai/...` URLs (not root-relative).
|
||||
- When you touch docs, end the reply with the `https://docs.openclaw.ai/...` URLs you referenced.
|
||||
- README (GitHub): keep absolute docs URLs (`https://docs.openclaw.ai/...`) so links work on GitHub.
|
||||
- Docs content must be generic: no personal device names/hostnames/paths; use placeholders like `user@gateway-host` and “gateway host”.
|
||||
@@ -102,8 +59,7 @@
|
||||
- Runtime baseline: Node **22+** (keep Node + Bun paths working).
|
||||
- Install deps: `pnpm install`
|
||||
- If deps are missing (for example `node_modules` missing, `vitest not found`, or `command not found`), run the repo’s package-manager install command (prefer lockfile/README-defined PM), then rerun the exact requested command once. Apply this to test/build/lint/typecheck/dev commands; if retry still fails, report the command and first actionable error.
|
||||
- Pre-commit hooks: `prek install`. The hook runs the repo verification flow, including `pnpm check`.
|
||||
- `FAST_COMMIT=1` skips the repo-wide `pnpm format` and `pnpm check` inside the pre-commit hook only. Use it when you intentionally want a faster commit path and are running equivalent targeted verification manually. It does not change CI and does not change what `pnpm check` itself does.
|
||||
- Pre-commit hooks: `prek install` (runs same checks as CI)
|
||||
- Also supported: `bun install` (keep `pnpm-lock.yaml` + Bun patching in sync when touching deps/patches).
|
||||
- Prefer Bun for TypeScript execution (scripts, dev, tests): `bun <file.ts>` / `bunx <tool>`.
|
||||
- Run CLI in dev: `pnpm openclaw ...` (bun) or `pnpm dev`.
|
||||
@@ -114,28 +70,12 @@
|
||||
- Lint/format: `pnpm check`
|
||||
- Format check: `pnpm format` (oxfmt --check)
|
||||
- Format fix: `pnpm format:fix` (oxfmt --write)
|
||||
- Terminology:
|
||||
- "gate" means a verification command or command set that must be green for the decision you are making.
|
||||
- A local dev gate is the fast default loop, usually `pnpm check` plus any scoped test you actually need.
|
||||
- A landing gate is the broader bar before pushing `main`, usually `pnpm check`, `pnpm test`, and `pnpm build` when the touched surface can affect build output, packaging, lazy-loading/module boundaries, or published surfaces.
|
||||
- A CI gate is whatever the relevant workflow enforces for that lane (for example `check`, `check-additional`, `build-smoke`, or release validation).
|
||||
- Local dev gate: prefer `pnpm check` for the normal edit loop. It keeps the repo-architecture policy guards out of the default local loop.
|
||||
- CI architecture gate: `check-additional` enforces architecture and boundary policy guards that are intentionally kept out of the default local loop.
|
||||
- Formatting gate: the pre-commit hook runs `pnpm format` before `pnpm check`. If you want a formatting-only preflight locally, run `pnpm format` explicitly.
|
||||
- If you need a fast commit loop, `FAST_COMMIT=1 git commit ...` skips the hook’s repo-wide `pnpm format` and `pnpm check`; use that only when you are deliberately covering the touched surface some other way.
|
||||
- Tests: `pnpm test` (vitest); coverage: `pnpm test:coverage`
|
||||
- Generated baseline artifacts live together under `docs/.generated/`.
|
||||
- Config schema drift uses `pnpm config:docs:gen` / `pnpm config:docs:check`.
|
||||
- Plugin SDK API drift uses `pnpm plugin-sdk:api:gen` / `pnpm plugin-sdk:api:check`.
|
||||
- If you change config schema/help or the public Plugin SDK surface, update the matching baseline artifact and keep the two drift-check flows adjacent in scripts/workflows/docs guidance rather than inventing a third pattern.
|
||||
- For narrowly scoped changes, prefer narrowly scoped tests that directly validate the touched behavior. If no meaningful scoped test exists, say so explicitly and use the next most direct validation available.
|
||||
- Verification modes for work on `main`:
|
||||
- Default mode: `main` is relatively stable. Count pre-commit hook coverage when it already verified the current tree, avoid rerunning the exact same checks just for ceremony, and prefer keeping CI/main green before landing.
|
||||
- Fast-commit mode: `main` is moving fast and you intentionally optimize for shorter commit loops. Prefer explicit local verification close to the final landing point, and it is acceptable to use `--no-verify` for intermediate or catch-up commits after equivalent checks have already run locally.
|
||||
- Preferred landing bar for pushes to `main`: in Default mode, favor `pnpm check` and `pnpm test` near the final rebase/push point when feasible. In fast-commit mode, verify the touched surface locally near landing without insisting every intermediate commit replay the full hook.
|
||||
- Preferred landing bar for pushes to `main`: `pnpm check` and `pnpm test`, with a green result when feasible.
|
||||
- Scoped tests prove the change itself. `pnpm test` remains the default `main` landing bar; scoped tests do not replace full-suite gates by default.
|
||||
- Hard gate: if the change can affect build output, packaging, lazy-loading/module boundaries, or published surfaces, `pnpm build` MUST be run and MUST pass before pushing `main`.
|
||||
- Default rule: do not land changes with failing format, lint, type, build, or required test checks when those failures are caused by the change or plausibly related to the touched surface. Fast-commit mode changes how verification is sequenced; it does not lower the requirement to validate and clean up the touched surface before final landing.
|
||||
- Default rule: do not commit or push with failing format, lint, type, build, or required test checks when those failures are caused by the change or plausibly related to the touched surface.
|
||||
- For narrowly scoped changes, if unrelated failures already exist on latest `origin/main`, state that clearly, report the scoped tests you ran, and ask before broadening scope into unrelated fixes or landing despite those failures.
|
||||
- Do not use scoped tests as permission to ignore plausibly related failures.
|
||||
|
||||
@@ -143,19 +83,11 @@
|
||||
|
||||
- Language: TypeScript (ESM). Prefer strict typing; avoid `any`.
|
||||
- Formatting/linting via Oxlint and Oxfmt.
|
||||
- Never add `@ts-nocheck` and do not add inline lint suppressions by default. Fix root causes first; only keep a suppression when the code is intentionally correct, the rule cannot express that safely, and the comment explains why.
|
||||
- Do not disable `no-explicit-any`; prefer real types, `unknown`, or a narrow adapter/helper instead. Update Oxlint/Oxfmt config only when required.
|
||||
- Prefer `zod` or existing schema helpers at external boundaries such as config, webhook payloads, CLI/JSON output, persisted JSON, and third-party API responses.
|
||||
- Prefer discriminated unions when parameter shape changes runtime behavior.
|
||||
- Prefer `Result<T, E>`-style outcomes and closed error-code unions for recoverable runtime decisions.
|
||||
- Keep human-readable strings for logs, CLI output, and UI; do not use freeform strings as the source of truth for internal branching.
|
||||
- Avoid `?? 0`, empty-string, empty-object, or magic-string sentinels when they can change runtime meaning silently.
|
||||
- If introducing a new optional field or nullable semantic in core logic, prefer an explicit union or dedicated type when the value changes behavior.
|
||||
- New runtime control-flow code should not branch on `error: string` or `reason: string` when a closed code union would be reasonable.
|
||||
- Never add `@ts-nocheck` and do not disable `no-explicit-any`; fix root causes and update Oxlint/Oxfmt config only when required.
|
||||
- Dynamic import guardrail: do not mix `await import("x")` and static `import ... from "x"` for the same module in production code paths. If you need lazy loading, create a dedicated `*.runtime.ts` boundary (that re-exports from `x`) and dynamically import that boundary from lazy callers only.
|
||||
- Dynamic import verification: after refactors that touch lazy-loading/module boundaries, run `pnpm build` and check for `[INEFFECTIVE_DYNAMIC_IMPORT]` warnings before submitting.
|
||||
- Extension SDK self-import guardrail: inside an extension package, do not import that same extension via `openclaw/plugin-sdk/<extension>` from production files. Route internal imports through a local barrel such as `./api.ts` or `./runtime-api.ts`, and keep the `plugin-sdk/<extension>` path as the external contract only.
|
||||
- Extension package boundary guardrail: inside a bundled plugin package, do not use relative imports/exports that resolve outside that same package root. If shared code belongs in the plugin SDK, import `openclaw/plugin-sdk/<subpath>` instead of reaching into `src/plugin-sdk/**` or other repo paths via `../`.
|
||||
- Extension package boundary guardrail: inside `extensions/<id>/**`, do not use relative imports/exports that resolve outside that same `extensions/<id>` package root. If shared code belongs in the plugin SDK, import `openclaw/plugin-sdk/<subpath>` instead of reaching into `src/plugin-sdk/**` or other repo paths via `../`.
|
||||
- Extension API surface rule: `openclaw/plugin-sdk/<subpath>` is the only public cross-package contract for extension-facing SDK code. If an extension needs a new seam, add a public subpath first; do not reach into `src/plugin-sdk/**` by relative path.
|
||||
- Never share class behavior via prototype mutation (`applyPrototypeMixins`, `Object.defineProperty` on `.prototype`, or exporting `Class.prototype` for merges). Use explicit inheritance/composition (`A extends B extends C`) or helper composition so TypeScript can typecheck.
|
||||
- If this pattern is needed, stop and get explicit approval before shipping; default behavior is to split/refactor into an explicit class hierarchy and keep members strongly typed.
|
||||
@@ -176,16 +108,13 @@
|
||||
|
||||
- Framework: Vitest with V8 coverage thresholds (70% lines/branches/functions/statements).
|
||||
- Naming: match source names with `*.test.ts`; e2e in `*.e2e.test.ts`.
|
||||
- When tests need example Anthropic/OpenAI model constants, prefer `sonnet-4.6` and `gpt-5.4`; update older Anthropic/GPT examples when you touch those tests.
|
||||
- Run `pnpm test` (or `pnpm test:coverage`) before pushing when you touch logic.
|
||||
- Write tests to clean up timers, env, globals, mocks, sockets, temp dirs, and module state so `--isolate=false` stays green.
|
||||
- Agents MUST NOT modify baseline, inventory, ignore, snapshot, or expected-failure files to silence failing checks without explicit approval in this chat.
|
||||
- For targeted/local debugging, keep using the wrapper: `pnpm test -- <path-or-filter> [vitest args...]` (for example `pnpm test -- src/commands/onboard-search.test.ts -t "shows registered plugin providers"`); do not default to raw `pnpm vitest run ...` because it bypasses wrapper config/profile/pool routing.
|
||||
- Do not set test workers above 16; tried already.
|
||||
- Keep Vitest on `forks` only. Do not introduce or reintroduce any non-`forks` Vitest pool or alternate execution mode in configs, wrapper scripts, or default test commands without explicit approval in this chat. This includes `threads`, `vmThreads`, `vmForks`, and any future/nonstandard pool variant.
|
||||
- If local Vitest runs cause memory pressure, the wrapper now derives budgets from host capabilities (CPU, memory band, current load). For a conservative explicit override during land/gate runs, use `OPENCLAW_TEST_PROFILE=serial OPENCLAW_TEST_SERIAL_GATEWAY=1 pnpm test`.
|
||||
- Live tests (real keys): `OPENCLAW_LIVE_TEST=1 pnpm test:live` (OpenClaw-only) or `LIVE=1 pnpm test:live` (includes provider live tests). Docker: `pnpm test:docker:live-models`, `pnpm test:docker:live-gateway`. Onboarding Docker E2E: `pnpm test:docker:onboard`.
|
||||
- `pnpm test:live` defaults quiet now. Keep `[live]` progress; suppress profile/gateway chatter. Full logs: `OPENCLAW_LIVE_TEST_QUIET=0 pnpm test:live`.
|
||||
- Do not switch CI `pnpm test` lanes back to Vitest `vmForks` by default without fresh green evidence on current `main`; keep CI on `forks` unless explicitly re-validated.
|
||||
- If local Vitest runs cause memory pressure (common on non-Mac-Studio hosts), use `OPENCLAW_TEST_PROFILE=low OPENCLAW_TEST_SERIAL_GATEWAY=1 pnpm test` for land/gate runs.
|
||||
- Live tests (real keys): `CLAWDBOT_LIVE_TEST=1 pnpm test:live` (OpenClaw-only) or `LIVE=1 pnpm test:live` (includes provider live tests). Docker: `pnpm test:docker:live-models`, `pnpm test:docker:live-gateway`. Onboarding Docker E2E: `pnpm test:docker:onboard`.
|
||||
- Full kit + what’s covered: `docs/help/testing.md`.
|
||||
- Changelog: user-facing changes only; no internal/meta notes (version alignment, appcast reminders, release process).
|
||||
- Changelog placement: in the active version block, append new entries to the end of the target section (`### Changes` or `### Fixes`); do not insert new entries at the top of a section.
|
||||
@@ -260,7 +189,6 @@
|
||||
- Patching dependencies (pnpm patches, overrides, or vendored changes) requires explicit approval; do not do this by default.
|
||||
- **Multi-agent safety:** do **not** create/apply/drop `git stash` entries unless explicitly requested (this includes `git pull --rebase --autostash`). Assume other agents may be working; keep unrelated WIP untouched and avoid cross-cutting state changes.
|
||||
- **Multi-agent safety:** when the user says "push", you may `git pull --rebase` to integrate latest changes (never discard other agents' work). When the user says "commit", scope to your changes only. When the user says "commit all", commit everything in grouped chunks.
|
||||
- **Multi-agent safety:** prefer grouped `commit` / `pull --rebase` / `push` cycles for related work instead of many tiny syncs.
|
||||
- **Multi-agent safety:** do **not** create/remove/modify `git worktree` checkouts (or edit `.worktrees/*`) unless explicitly requested.
|
||||
- **Multi-agent safety:** do **not** switch branches / check out a different branch unless explicitly requested.
|
||||
- **Multi-agent safety:** running multiple agents is OK as long as each agent has its own session.
|
||||
|
||||
1295
CHANGELOG.md
1295
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
@@ -24,7 +24,7 @@ Welcome to the lobster tank! 🦞
|
||||
- GitHub: [@joshp123](https://github.com/joshp123) · X: [@jjpcodes](https://x.com/jjpcodes)
|
||||
|
||||
- **Ayaan Zaidi** - Telegram subsystem, Android app
|
||||
- GitHub: [@obviyus](https://github.com/obviyus) · X: [@obviyus](https://x.com/obviyus)
|
||||
- GitHub: [@obviyus](https://github.com/obviyus) · X: [@0bviyus](https://x.com/0bviyus)
|
||||
|
||||
- **Tyler Yust** - Agents/subagents, cron, BlueBubbles, macOS app
|
||||
- GitHub: [@tyler6204](https://github.com/tyler6204) · X: [@tyleryust](https://x.com/tyleryust)
|
||||
@@ -58,7 +58,6 @@ Welcome to the lobster tank! 🦞
|
||||
|
||||
- **Jonathan Taylor** - ACP subsystem, Gateway features/bugs, Gog/Mog/Sog CLI's, SEDMAT
|
||||
- GitHub [@visionik](https://github.com/visionik) · X: [@visionik](https://x.com/visionik)
|
||||
|
||||
- **Josh Lehman** - Compaction, Tlon/Urbit subsystem
|
||||
- GitHub [@jalehman](https://github.com/jalehman) · X: [@jlehman\_](https://x.com/jlehman_)
|
||||
|
||||
@@ -77,6 +76,9 @@ Welcome to the lobster tank! 🦞
|
||||
- **Tengji (George) Zhang** - Chinese model APIs, cloud, pi
|
||||
- GitHub: [@odysseus0](https://github.com/odysseus0) · X: [@odysseus0z](https://x.com/odysseus0z)
|
||||
|
||||
- **Andrew (Bubbles) Demczuk** - Agents/Gateway/TTS/VTT
|
||||
- GitHub: [@ademczuk](https://github.com/ademczuk) · X: [@ademczuk](https://x.com/ademczuk)
|
||||
|
||||
## How to Contribute
|
||||
|
||||
1. **Bugs & small fixes** → Open a PR!
|
||||
@@ -94,7 +96,6 @@ Welcome to the lobster tank! 🦞
|
||||
- `pnpm test:extension --list` to see valid extension ids
|
||||
- If you changed shared plugin or channel surfaces, run `pnpm test:contracts`
|
||||
- For targeted shared-surface work, use `pnpm test:contracts:channels` or `pnpm test:contracts:plugins`
|
||||
- These commands also cover the shared seam/smoke files that the default unit lane skips
|
||||
- If you changed broader runtime behavior, still run the relevant wider lanes (`pnpm test:extensions`, `pnpm test:channels`, or `pnpm test`) before asking for review
|
||||
- If you have access to Codex, run `codex review --base origin/main` locally before opening or updating your PR. Treat this as the current highest standard of AI review, even if GitHub Codex review also runs.
|
||||
- Do not submit refactor-only PRs unless a maintainer explicitly requested that refactor for an active fix or deliverable.
|
||||
|
||||
33
Dockerfile
33
Dockerfile
@@ -5,17 +5,15 @@
|
||||
#
|
||||
# Multi-stage build produces a minimal runtime image without build tools,
|
||||
# source code, or Bun. Works with Docker, Buildx, and Podman.
|
||||
# The ext-deps stage extracts only the package.json files we need from the
|
||||
# bundled plugin workspace tree, so the main build layer is not invalidated by
|
||||
# unrelated plugin source changes.
|
||||
# The ext-deps stage extracts only the package.json files we need from
|
||||
# extensions/, so the main build layer is not invalidated by unrelated
|
||||
# extension source changes.
|
||||
#
|
||||
# Two runtime variants:
|
||||
# Default (bookworm): docker build .
|
||||
# Slim (bookworm-slim): docker build --build-arg OPENCLAW_VARIANT=slim .
|
||||
ARG OPENCLAW_EXTENSIONS=""
|
||||
ARG OPENCLAW_VARIANT=default
|
||||
ARG OPENCLAW_BUNDLED_PLUGIN_DIR=extensions
|
||||
ARG OPENCLAW_DOCKER_APT_UPGRADE=1
|
||||
ARG OPENCLAW_NODE_BOOKWORM_IMAGE="node:24-bookworm@sha256:3a09aa6354567619221ef6c45a5051b671f953f0a1924d1f819ffb236e520e6b"
|
||||
ARG OPENCLAW_NODE_BOOKWORM_DIGEST="sha256:3a09aa6354567619221ef6c45a5051b671f953f0a1924d1f819ffb236e520e6b"
|
||||
ARG OPENCLAW_NODE_BOOKWORM_SLIM_IMAGE="node:24-bookworm-slim@sha256:e8e2e91b1378f83c5b2dd15f0247f34110e2fe895f6ca7719dbb780f929368eb"
|
||||
@@ -28,20 +26,18 @@ ARG OPENCLAW_NODE_BOOKWORM_SLIM_DIGEST="sha256:e8e2e91b1378f83c5b2dd15f0247f3411
|
||||
|
||||
FROM ${OPENCLAW_NODE_BOOKWORM_IMAGE} AS ext-deps
|
||||
ARG OPENCLAW_EXTENSIONS
|
||||
ARG OPENCLAW_BUNDLED_PLUGIN_DIR
|
||||
COPY ${OPENCLAW_BUNDLED_PLUGIN_DIR} /tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}
|
||||
COPY extensions /tmp/extensions
|
||||
# Copy package.json for opted-in extensions so pnpm resolves their deps.
|
||||
RUN mkdir -p /out && \
|
||||
for ext in $OPENCLAW_EXTENSIONS; do \
|
||||
if [ -f "/tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}/$ext/package.json" ]; then \
|
||||
if [ -f "/tmp/extensions/$ext/package.json" ]; then \
|
||||
mkdir -p "/out/$ext" && \
|
||||
cp "/tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}/$ext/package.json" "/out/$ext/package.json"; \
|
||||
cp "/tmp/extensions/$ext/package.json" "/out/$ext/package.json"; \
|
||||
fi; \
|
||||
done
|
||||
|
||||
# ── Stage 2: Build ──────────────────────────────────────────────
|
||||
FROM ${OPENCLAW_NODE_BOOKWORM_IMAGE} AS build
|
||||
ARG OPENCLAW_BUNDLED_PLUGIN_DIR
|
||||
|
||||
# Install Bun (required for build scripts). Retry the whole bootstrap flow to
|
||||
# tolerate transient 5xx failures from bun.sh/GitHub during CI image builds.
|
||||
@@ -64,9 +60,8 @@ WORKDIR /app
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
|
||||
COPY ui/package.json ./ui/package.json
|
||||
COPY patches ./patches
|
||||
COPY scripts/postinstall-bundled-plugins.mjs ./scripts/postinstall-bundled-plugins.mjs
|
||||
|
||||
COPY --from=ext-deps /out/ ./${OPENCLAW_BUNDLED_PLUGIN_DIR}/
|
||||
COPY --from=ext-deps /out/ ./extensions/
|
||||
|
||||
# Reduce OOM risk on low-memory hosts during dependency installation.
|
||||
# Docker builds on small VMs may otherwise fail with "Killed" (exit 137).
|
||||
@@ -77,7 +72,7 @@ COPY . .
|
||||
|
||||
# Normalize extension paths now so runtime COPY preserves safe modes
|
||||
# without adding a second full extensions layer.
|
||||
RUN for dir in /app/${OPENCLAW_BUNDLED_PLUGIN_DIR} /app/.agent /app/.agents; do \
|
||||
RUN for dir in /app/extensions /app/.agent /app/.agents; do \
|
||||
if [ -d "$dir" ]; then \
|
||||
find "$dir" -type d -exec chmod 755 {} +; \
|
||||
find "$dir" -type f -exec chmod 644 {} +; \
|
||||
@@ -118,8 +113,6 @@ LABEL org.opencontainers.image.base.name="docker.io/library/node:24-bookworm-sli
|
||||
# ── Stage 3: Runtime ────────────────────────────────────────────
|
||||
FROM base-${OPENCLAW_VARIANT}
|
||||
ARG OPENCLAW_VARIANT
|
||||
ARG OPENCLAW_BUNDLED_PLUGIN_DIR
|
||||
ARG OPENCLAW_DOCKER_APT_UPGRADE
|
||||
|
||||
# OCI base-image metadata for downstream image consumers.
|
||||
# If you change these annotations, also update:
|
||||
@@ -136,14 +129,10 @@ WORKDIR /app
|
||||
|
||||
# Install system utilities present in bookworm but missing in bookworm-slim.
|
||||
# On the full bookworm image these are already installed (apt-get is a no-op).
|
||||
# Smoke workflows can opt out of distro upgrades to cut repeated CI time while
|
||||
# keeping the default runtime image behavior unchanged.
|
||||
RUN --mount=type=cache,id=openclaw-bookworm-apt-cache,target=/var/cache/apt,sharing=locked \
|
||||
--mount=type=cache,id=openclaw-bookworm-apt-lists,target=/var/lib/apt,sharing=locked \
|
||||
apt-get update && \
|
||||
if [ "${OPENCLAW_DOCKER_APT_UPGRADE}" != "0" ]; then \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get upgrade -y --no-install-recommends; \
|
||||
fi && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get upgrade -y --no-install-recommends && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
procps hostname curl git lsof openssl
|
||||
|
||||
@@ -153,13 +142,13 @@ COPY --from=runtime-assets --chown=node:node /app/dist ./dist
|
||||
COPY --from=runtime-assets --chown=node:node /app/node_modules ./node_modules
|
||||
COPY --from=runtime-assets --chown=node:node /app/package.json .
|
||||
COPY --from=runtime-assets --chown=node:node /app/openclaw.mjs .
|
||||
COPY --from=runtime-assets --chown=node:node /app/${OPENCLAW_BUNDLED_PLUGIN_DIR} ./${OPENCLAW_BUNDLED_PLUGIN_DIR}
|
||||
COPY --from=runtime-assets --chown=node:node /app/extensions ./extensions
|
||||
COPY --from=runtime-assets --chown=node:node /app/skills ./skills
|
||||
COPY --from=runtime-assets --chown=node:node /app/docs ./docs
|
||||
|
||||
# In npm-installed Docker images, prefer the copied source extension tree for
|
||||
# bundled discovery so package metadata that points at source entries stays valid.
|
||||
ENV OPENCLAW_BUNDLED_PLUGINS_DIR=/app/${OPENCLAW_BUNDLED_PLUGIN_DIR}
|
||||
ENV OPENCLAW_BUNDLED_PLUGINS_DIR=/app/extensions
|
||||
|
||||
# Keep pnpm available in the runtime image for container-local workflows.
|
||||
# Use a shared Corepack home so the non-root `node` user does not need a
|
||||
|
||||
@@ -14,7 +14,6 @@ RUN --mount=type=cache,id=openclaw-sandbox-bookworm-apt-cache,target=/var/cache/
|
||||
chromium \
|
||||
curl \
|
||||
fonts-liberation \
|
||||
fonts-noto-cjk \
|
||||
fonts-noto-color-emoji \
|
||||
git \
|
||||
jq \
|
||||
|
||||
16
README.md
16
README.md
@@ -19,7 +19,7 @@
|
||||
</p>
|
||||
|
||||
**OpenClaw** is a _personal AI assistant_ you run on your own devices.
|
||||
It answers you on the channels you already use (WhatsApp, Telegram, Slack, Discord, Google Chat, Signal, iMessage, BlueBubbles, IRC, Microsoft Teams, Matrix, Feishu, LINE, Mattermost, Nextcloud Talk, Nostr, Synology Chat, Tlon, Twitch, Zalo, Zalo Personal, WeChat, WebChat). It can speak and listen on macOS/iOS/Android, and can render a live Canvas you control. The Gateway is just the control plane — the product is the assistant.
|
||||
It answers you on the channels you already use (WhatsApp, Telegram, Slack, Discord, Google Chat, Signal, iMessage, BlueBubbles, IRC, Microsoft Teams, Matrix, Feishu, LINE, Mattermost, Nextcloud Talk, Nostr, Synology Chat, Tlon, Twitch, Zalo, Zalo Personal, WebChat). It can speak and listen on macOS/iOS/Android, and can render a live Canvas you control. The Gateway is just the control plane — the product is the assistant.
|
||||
|
||||
If you want a personal, single-user assistant that feels local, fast, and always-on, this is it.
|
||||
|
||||
@@ -74,7 +74,7 @@ openclaw gateway --port 18789 --verbose
|
||||
# Send a message
|
||||
openclaw message send --to +1234567890 --message "Hello from OpenClaw"
|
||||
|
||||
# Talk to the assistant (optionally deliver back to any connected channel: WhatsApp/Telegram/Slack/Discord/Google Chat/Signal/iMessage/BlueBubbles/IRC/Microsoft Teams/Matrix/Feishu/LINE/Mattermost/Nextcloud Talk/Nostr/Synology Chat/Tlon/Twitch/Zalo/Zalo Personal/WeChat/WebChat)
|
||||
# Talk to the assistant (optionally deliver back to any connected channel: WhatsApp/Telegram/Slack/Discord/Google Chat/Signal/iMessage/BlueBubbles/IRC/Microsoft Teams/Matrix/Feishu/LINE/Mattermost/Nextcloud Talk/Nostr/Synology Chat/Tlon/Twitch/Zalo/Zalo Personal/WebChat)
|
||||
openclaw agent --message "Ship checklist" --thinking high
|
||||
```
|
||||
|
||||
@@ -126,7 +126,7 @@ Run `openclaw doctor` to surface risky/misconfigured DM policies.
|
||||
## Highlights
|
||||
|
||||
- **[Local-first Gateway](https://docs.openclaw.ai/gateway)** — single control plane for sessions, channels, tools, and events.
|
||||
- **[Multi-channel inbox](https://docs.openclaw.ai/channels)** — WhatsApp, Telegram, Slack, Discord, Google Chat, Signal, BlueBubbles (iMessage), iMessage (legacy), IRC, Microsoft Teams, Matrix, Feishu, LINE, Mattermost, Nextcloud Talk, Nostr, Synology Chat, Tlon, Twitch, Zalo, Zalo Personal, WeChat, WebChat, macOS, iOS/Android.
|
||||
- **[Multi-channel inbox](https://docs.openclaw.ai/channels)** — WhatsApp, Telegram, Slack, Discord, Google Chat, Signal, BlueBubbles (iMessage), iMessage (legacy), IRC, Microsoft Teams, Matrix, Feishu, LINE, Mattermost, Nextcloud Talk, Nostr, Synology Chat, Tlon, Twitch, Zalo, Zalo Personal, WebChat, macOS, iOS/Android.
|
||||
- **[Multi-agent routing](https://docs.openclaw.ai/gateway/configuration)** — route inbound channels/accounts/peers to isolated agents (workspaces + per-agent sessions).
|
||||
- **[Voice Wake](https://docs.openclaw.ai/nodes/voicewake) + [Talk Mode](https://docs.openclaw.ai/nodes/talk)** — wake words on macOS/iOS and continuous voice on Android (ElevenLabs + system TTS fallback).
|
||||
- **[Live Canvas](https://docs.openclaw.ai/platforms/mac/canvas)** — agent-driven visual workspace with [A2UI](https://docs.openclaw.ai/platforms/mac/canvas#canvas-a2ui).
|
||||
@@ -150,7 +150,7 @@ Run `openclaw doctor` to surface risky/misconfigured DM policies.
|
||||
|
||||
### Channels
|
||||
|
||||
- [Channels](https://docs.openclaw.ai/channels): [WhatsApp](https://docs.openclaw.ai/channels/whatsapp) (Baileys), [Telegram](https://docs.openclaw.ai/channels/telegram) (grammY), [Slack](https://docs.openclaw.ai/channels/slack) (Bolt), [Discord](https://docs.openclaw.ai/channels/discord) (discord.js), [Google Chat](https://docs.openclaw.ai/channels/googlechat) (Chat API), [Signal](https://docs.openclaw.ai/channels/signal) (signal-cli), [BlueBubbles](https://docs.openclaw.ai/channels/bluebubbles) (iMessage, recommended), [iMessage](https://docs.openclaw.ai/channels/imessage) (legacy imsg), [IRC](https://docs.openclaw.ai/channels/irc), [Microsoft Teams](https://docs.openclaw.ai/channels/msteams), [Matrix](https://docs.openclaw.ai/channels/matrix), [Feishu](https://docs.openclaw.ai/channels/feishu), [LINE](https://docs.openclaw.ai/channels/line), [Mattermost](https://docs.openclaw.ai/channels/mattermost), [Nextcloud Talk](https://docs.openclaw.ai/channels/nextcloud-talk), [Nostr](https://docs.openclaw.ai/channels/nostr), [Synology Chat](https://docs.openclaw.ai/channels/synology-chat), [Tlon](https://docs.openclaw.ai/channels/tlon), [Twitch](https://docs.openclaw.ai/channels/twitch), [Zalo](https://docs.openclaw.ai/channels/zalo), [Zalo Personal](https://docs.openclaw.ai/channels/zalouser), WeChat (`@tencent-weixin/openclaw-weixin`), [WebChat](https://docs.openclaw.ai/web/webchat).
|
||||
- [Channels](https://docs.openclaw.ai/channels): [WhatsApp](https://docs.openclaw.ai/channels/whatsapp) (Baileys), [Telegram](https://docs.openclaw.ai/channels/telegram) (grammY), [Slack](https://docs.openclaw.ai/channels/slack) (Bolt), [Discord](https://docs.openclaw.ai/channels/discord) (discord.js), [Google Chat](https://docs.openclaw.ai/channels/googlechat) (Chat API), [Signal](https://docs.openclaw.ai/channels/signal) (signal-cli), [BlueBubbles](https://docs.openclaw.ai/channels/bluebubbles) (iMessage, recommended), [iMessage](https://docs.openclaw.ai/channels/imessage) (legacy imsg), [IRC](https://docs.openclaw.ai/channels/irc), [Microsoft Teams](https://docs.openclaw.ai/channels/msteams), [Matrix](https://docs.openclaw.ai/channels/matrix), [Feishu](https://docs.openclaw.ai/channels/feishu), [LINE](https://docs.openclaw.ai/channels/line), [Mattermost](https://docs.openclaw.ai/channels/mattermost), [Nextcloud Talk](https://docs.openclaw.ai/channels/nextcloud-talk), [Nostr](https://docs.openclaw.ai/channels/nostr), [Synology Chat](https://docs.openclaw.ai/channels/synology-chat), [Tlon](https://docs.openclaw.ai/channels/tlon), [Twitch](https://docs.openclaw.ai/channels/twitch), [Zalo](https://docs.openclaw.ai/channels/zalo), [Zalo Personal](https://docs.openclaw.ai/channels/zalouser), [WebChat](https://docs.openclaw.ai/web/webchat).
|
||||
- [Group routing](https://docs.openclaw.ai/channels/group-messages): mention gating, reply tags, per-channel chunking and routing. Channel rules: [Channels](https://docs.openclaw.ai/channels).
|
||||
|
||||
### Apps + nodes
|
||||
@@ -185,7 +185,7 @@ Run `openclaw doctor` to surface risky/misconfigured DM policies.
|
||||
## How it works (short)
|
||||
|
||||
```
|
||||
WhatsApp / Telegram / Slack / Discord / Google Chat / Signal / iMessage / BlueBubbles / IRC / Microsoft Teams / Matrix / Feishu / LINE / Mattermost / Nextcloud Talk / Nostr / Synology Chat / Tlon / Twitch / Zalo / Zalo Personal / WeChat / WebChat
|
||||
WhatsApp / Telegram / Slack / Discord / Google Chat / Signal / iMessage / BlueBubbles / IRC / Microsoft Teams / Matrix / Feishu / LINE / Mattermost / Nextcloud Talk / Nostr / Synology Chat / Tlon / Twitch / Zalo / Zalo Personal / WebChat
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────┐
|
||||
@@ -397,12 +397,6 @@ Details: [Security guide](https://docs.openclaw.ai/gateway/security) · [Docker
|
||||
- Configure a Teams app + Bot Framework, then add a `msteams` config section.
|
||||
- Allowlist who can talk via `msteams.allowFrom`; group access via `msteams.groupAllowFrom` or `msteams.groupPolicy: "open"`.
|
||||
|
||||
### WeChat
|
||||
|
||||
- Official Tencent plugin via [`@tencent-weixin/openclaw-weixin`](https://www.npmjs.com/package/@tencent-weixin/openclaw-weixin) (iLink Bot API). Private chats only; v2.x requires OpenClaw `>=2026.3.22`.
|
||||
- Install: `openclaw plugins install "@tencent-weixin/openclaw-weixin"`, then `openclaw channels login --channel openclaw-weixin` to scan the QR code.
|
||||
- Requires the WeChat ClawBot plugin (WeChat > Me > Settings > Plugins); gradual rollout by Tencent.
|
||||
|
||||
### [WebChat](https://docs.openclaw.ai/web/webchat)
|
||||
|
||||
- Uses the Gateway WebSocket; no separate WebChat port/config.
|
||||
|
||||
@@ -101,7 +101,7 @@ OpenClaw does **not** model one gateway as a multi-tenant, adversarial user boun
|
||||
- If multiple users need OpenClaw, use one VPS (or host/OS user boundary) per user.
|
||||
- For advanced setups, multiple gateways on one machine are possible, but only with strict isolation and are not the recommended default.
|
||||
- Exec behavior is host-first by default: `agents.defaults.sandbox.mode` defaults to `off`.
|
||||
- `tools.exec.host` defaults to `auto`: sandbox when sandbox runtime is active for the session, otherwise gateway.
|
||||
- `tools.exec.host` defaults to `sandbox` as a routing preference, but if sandbox runtime is not active for the session, exec runs on the gateway host.
|
||||
- Implicit exec calls (no explicit host in the tool call) follow the same behavior.
|
||||
- This is expected in OpenClaw's one-user trusted-operator model. If you need isolation, enable sandbox mode (`non-main`/`all`) and keep strict tool policy.
|
||||
|
||||
|
||||
410
appcast.xml
410
appcast.xml
@@ -3,238 +3,246 @@
|
||||
<channel>
|
||||
<title>OpenClaw</title>
|
||||
<item>
|
||||
<title>2026.3.28</title>
|
||||
<pubDate>Sun, 29 Mar 2026 02:10:40 +0000</pubDate>
|
||||
<title>2026.3.13</title>
|
||||
<pubDate>Sat, 14 Mar 2026 05:19:48 +0000</pubDate>
|
||||
<link>https://raw.githubusercontent.com/openclaw/openclaw/main/appcast.xml</link>
|
||||
<sparkle:version>2026032890</sparkle:version>
|
||||
<sparkle:shortVersionString>2026.3.28</sparkle:shortVersionString>
|
||||
<sparkle:version>2026031390</sparkle:version>
|
||||
<sparkle:shortVersionString>2026.3.13</sparkle:shortVersionString>
|
||||
<sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
|
||||
<description><![CDATA[<h2>OpenClaw 2026.3.28</h2>
|
||||
<h3>Breaking</h3>
|
||||
<ul>
|
||||
<li>Providers/Qwen: remove the deprecated <code>qwen-portal-auth</code> OAuth integration for <code>portal.qwen.ai</code>; migrate to Model Studio with <code>openclaw onboard --auth-choice modelstudio-api-key</code>. (#52709) Thanks @pomelo-nwu.</li>
|
||||
<li>Config/Doctor: drop automatic config migrations older than two months; very old legacy keys now fail validation instead of being rewritten on load or by <code>openclaw doctor</code>.</li>
|
||||
</ul>
|
||||
<description><![CDATA[<h2>OpenClaw 2026.3.13</h2>
|
||||
<h3>Changes</h3>
|
||||
<ul>
|
||||
<li>xAI/tools: move the bundled xAI provider to the Responses API, add first-class <code>x_search</code>, and auto-enable the xAI plugin from owned web-search and tool config so bundled Grok auth/configured search flows work without manual plugin toggles. (#56048) Thanks @huntharo.</li>
|
||||
<li>xAI/onboarding: let the bundled Grok web-search plugin offer optional <code>x_search</code> setup during <code>openclaw onboard</code> and <code>openclaw configure --section web</code>, including an x_search model picker with the shared xAI key.</li>
|
||||
<li>MiniMax: add image generation provider for <code>image-01</code> model, supporting generate and image-to-image editing with aspect ratio control. (#54487) Thanks @liyuan97.</li>
|
||||
<li>Plugins/hooks: add async <code>requireApproval</code> to <code>before_tool_call</code> hooks, letting plugins pause tool execution and prompt the user for approval via the exec approval overlay, Telegram buttons, Discord interactions, or the <code>/approve</code> command on any channel. The <code>/approve</code> command now handles both exec and plugin approvals with automatic fallback. (#55339) Thanks @vaclavbelak and @joshavant.</li>
|
||||
<li>ACP/channels: add current-conversation ACP binds for Discord, BlueBubbles, and iMessage so <code>/acp spawn codex --bind here</code> can turn the current chat into a Codex-backed workspace without creating a child thread, and document the distinction between chat surface, ACP session, and runtime workspace.</li>
|
||||
<li>OpenAI/apply_patch: enable <code>apply_patch</code> by default for OpenAI and OpenAI Codex models, and align its sandbox policy access with <code>write</code> permissions.</li>
|
||||
<li>Plugins/CLI backends: move bundled Claude CLI, Codex CLI, and Gemini CLI inference defaults onto the plugin surface, add bundled Gemini CLI backend support, and replace <code>gateway run --claude-cli-logs</code> with generic <code>--cli-backend-logs</code> while keeping the old flag as a compatibility alias.</li>
|
||||
<li>Plugins/startup: auto-load bundled provider and CLI-backend plugins from explicit config refs, so bundled Claude CLI, Codex CLI, and Gemini CLI message-provider setups no longer need manual <code>plugins.allow</code> entries.</li>
|
||||
<li>Podman: simplify the container setup around the current rootless user, install the launch helper under <code>~/.local/bin</code>, and document the host-CLI <code>openclaw --container <name> ...</code> workflow instead of a dedicated <code>openclaw</code> service user.</li>
|
||||
<li>Slack/tool actions: add an explicit <code>upload-file</code> Slack action that routes file uploads through the existing Slack upload transport, with optional filename/title/comment overrides for channels and DMs.</li>
|
||||
<li>Message actions/files: start unifying file-first sends on the canonical <code>upload-file</code> action by adding explicit support for Microsoft Teams and Google Chat, and by exposing BlueBubbles file sends through <code>upload-file</code> while keeping the legacy <code>sendAttachment</code> alias.</li>
|
||||
<li>Plugins/Matrix TTS: send auto-TTS replies as native Matrix voice bubbles instead of generic audio attachments. (#37080) thanks @Matthew19990919.</li>
|
||||
<li>CLI: add <code>openclaw config schema</code> to print the generated JSON schema for <code>openclaw.json</code>. (#54523) Thanks @kvokka.</li>
|
||||
<li>Config/TTS: auto-migrate legacy speech config on normal reads and secret resolution, keep legacy diagnostics for Doctor, and remove regular-mode runtime fallback for old bundled <code>tts.<provider></code> API-key shapes.</li>
|
||||
<li>Memory/plugins: move the pre-compaction memory flush plan behind the active memory plugin contract so <code>memory-core</code> owns flush prompts and target-path policy instead of hardcoded core logic.</li>
|
||||
<li>MiniMax: trim model catalog to M2.7 only, removing legacy M2, M2.1, M2.5, and VL-01 models. (#54487) Thanks @liyuan97.</li>
|
||||
<li>Plugins/runtime: expose <code>runHeartbeatOnce</code> in the plugin runtime <code>system</code> namespace so plugins can trigger a single heartbeat cycle with an explicit delivery target override (e.g. <code>heartbeat: { target: "last" }</code>). (#40299) Thanks @loveyana.</li>
|
||||
<li>Agents/compaction: preserve the post-compaction AGENTS refresh on stale-usage preflight compaction for both immediate replies and queued followups. (#49479) Thanks @jared596.</li>
|
||||
<li>Agents/compaction: surface safeguard-specific cancel reasons and relabel benign manual <code>/compact</code> no-op cases as skipped instead of failed. (#51072) Thanks @afurm.</li>
|
||||
<li>Docs: add <code>pnpm docs:check-links:anchors</code> for Mintlify anchor validation while keeping <code>scripts/docs-link-audit.mjs</code> as the stable link-audit entrypoint. (#55912) Thanks @velvet-shark.</li>
|
||||
<li>Tavily: mark outbound API requests with <code>X-Client-Source: openclaw</code> so Tavily can attribute OpenClaw-originated traffic. (#55335) Thanks @lakshyaag-tavily.</li>
|
||||
<li>Android/chat settings: redesign the chat settings sheet with grouped device and media sections, refresh the Connect and Voice tabs, and tighten the chat composer/session header for a denser mobile layout. (#44894) Thanks @obviyus.</li>
|
||||
<li>iOS/onboarding: add a first-run welcome pager before gateway setup, stop auto-opening the QR scanner, and show <code>/pair qr</code> instructions on the connect step. (#45054) Thanks @ngutman.</li>
|
||||
<li>Browser/existing-session: add an official Chrome DevTools MCP attach mode for signed-in live Chrome sessions, with docs for <code>chrome://inspect/#remote-debugging</code> enablement and direct backlinks to Chrome’s own setup guides.</li>
|
||||
<li>Browser/agents: add built-in <code>profile="user"</code> for the logged-in host browser and <code>profile="chrome-relay"</code> for the extension relay, so agent browser calls can prefer the real signed-in browser without the extra <code>browserSession</code> selector.</li>
|
||||
<li>Browser/act automation: add batched actions, selector targeting, and delayed clicks for browser act requests with normalized batch dispatch. Thanks @vincentkoc.</li>
|
||||
<li>Docker/timezone override: add <code>OPENCLAW_TZ</code> so <code>docker-setup.sh</code> can pin gateway and CLI containers to a chosen IANA timezone instead of inheriting the daemon default. (#34119) Thanks @Lanfei.</li>
|
||||
<li>Dependencies/pi: bump <code>@mariozechner/pi-agent-core</code>, <code>@mariozechner/pi-ai</code>, <code>@mariozechner/pi-coding-agent</code>, and <code>@mariozechner/pi-tui</code> to <code>0.58.0</code>.</li>
|
||||
</ul>
|
||||
<h3>Fixes</h3>
|
||||
<ul>
|
||||
<li>Agents/Anthropic: recover unhandled provider stop reasons (e.g. <code>sensitive</code>) as structured assistant errors instead of crashing the agent run. (#56639)</li>
|
||||
<li>Google/models: resolve Gemini 3.1 pro, flash, and flash-lite for all Google provider aliases by passing the actual runtime provider ID and adding a template-provider fallback; fix flash-lite prefix ordering. (#56567)</li>
|
||||
<li>OpenAI Codex/image tools: register Codex for media understanding and route image prompts through Codex instructions so image analysis no longer fails on missing provider registration or missing <code>instructions</code>. (#54829) Thanks @neeravmakwana.</li>
|
||||
<li>Agents/image tool: restore the generic image-runtime fallback when no provider-specific media-understanding provider is registered, so image analysis works again for providers like <code>openrouter</code> and <code>minimax-portal</code>. (#54858) Thanks @MonkeyLeeT.</li>
|
||||
<li>WhatsApp: fix infinite echo loop in self-chat DM mode where the bot's own outbound replies were re-processed as new inbound user messages. (#54570) Thanks @joelnishanth</li>
|
||||
<li>Telegram/splitting: replace proportional text estimate with verified HTML-length search so long messages split at word boundaries instead of mid-word; gracefully degrade when tag overhead exceeds the limit. (#56595)</li>
|
||||
<li>Telegram/delivery: skip whitespace-only and hook-blanked text replies in bot delivery to prevent GrammyError 400 empty-text crashes. (#56620)</li>
|
||||
<li>Telegram/send: validate <code>replyToMessageId</code> at all four API sinks with a shared normalizer that rejects non-numeric, NaN, and mixed-content strings. (#56587)</li>
|
||||
<li>Mistral: normalize OpenAI-compatible request flags so official Mistral API runs no longer fail with remaining <code>422 status code (no body)</code> chat errors.</li>
|
||||
<li>Control UI/config: keep sensitive raw config hidden by default, replace the blank blocked editor with an explicit reveal-to-edit state, and restore raw JSON editing without auto-exposing secrets. Fixes #55322.</li>
|
||||
<li>CLI/zsh: defer <code>compdef</code> registration until <code>compinit</code> is available so zsh completion loads cleanly with plugin managers and manual setups. (#56555)</li>
|
||||
<li>BlueBubbles/debounce: guard debounce flush against null message text by sanitizing at the enqueue boundary and adding an independent combiner guard. (#56573)</li>
|
||||
<li>Auto-reply: suppress JSON-wrapped <code>{"action":"NO_REPLY"}</code> control envelopes before channel delivery with a strict single-key detector; preserves media when text is only a silent envelope. (#56612)</li>
|
||||
<li>ACP/ACPX agent registry: align OpenClaw's ACPX built-in agent mirror with the latest <code>openclaw/acpx</code> command defaults and built-in aliases, pin versioned <code>npx</code> built-ins to exact versions, and stop unknown ACP agent ids from falling through to raw <code>--agent</code> command execution on the MCP-proxy path. (#28321) Thanks @m0nkmaster and @vincentkoc.</li>
|
||||
<li>Security/audit: extend web search key audit to recognize Gemini, Grok/xAI, Kimi, Moonshot, and OpenRouter credentials via a boundary-safe bundled-web-search registry shim. (#56540)</li>
|
||||
<li>Docs/FAQ: remove broken Xfinity SSL troubleshooting cross-links from English and zh-CN FAQ entries — both sections already contain the full workaround inline. (#56500)</li>
|
||||
<li>Telegram: deliver verbose tool summaries inside forum topic sessions again, so threaded topic chats now match DM verbose behavior. (#43236) Thanks @frankbuild.</li>
|
||||
<li>BlueBubbles/CLI agents: restore inbound prompt image refs for CLI routed turns, reapply embedded runner image size guardrails, and cover both CLI image transport paths with regression tests. (#51373)</li>
|
||||
<li>BlueBubbles/groups: optionally enrich unnamed participant lists with local macOS Contacts names after group gating passes, so group member context can show names instead of only raw phone numbers.</li>
|
||||
<li>Discord/reconnect: drain stale gateway sockets, clear cached resume state before forced fresh reconnects, and fail closed when old sockets refuse to die so Discord recovery stops looping on poisoned resume state. (#54697) Thanks @ngutman.</li>
|
||||
<li>iMessage: stop leaking inline <code>[[reply_to:...]]</code> tags into delivered text by sending <code>reply_to</code> as RPC metadata and stripping stray directive tags from outbound messages. (#39512) Thanks @mvanhorn.</li>
|
||||
<li>CLI/plugins: make routed commands use the same auto-enabled bundled-channel snapshot as gateway startup, so configured bundled channels like Slack load without requiring a prior config rewrite. (#54809) Thanks @neeravmakwana.</li>
|
||||
<li>CLI/message send: write manual <code>openclaw message send</code> deliveries into the resolved agent session transcript again by always threading the default CLI agent through outbound mirroring. (#54187) Thanks @KevInTheCloud5617.</li>
|
||||
<li>CLI/onboarding: show the Kimi Code API key option again in the Moonshot setup menu so the interactive picker includes all Kimi setup paths together. Fixes #54412 Thanks @sparkyrider</li>
|
||||
<li>Agents/status: use provider-aware context window lookup for fresh Anthropic 4.6 model overrides so <code>/status</code> shows the correct 1.0m window instead of an underreported shared-cache minimum. (#54796) Thanks @neeravmakwana.</li>
|
||||
<li>OpenAI/WebSocket: preserve reasoning replay metadata and tool-call item ids on WebSocket tool turns, and start a fresh response chain when full-context resend is required. (#53856) Thanks @xujingchen1996.</li>
|
||||
<li>OpenAI/WS: restore reasoning blocks for Responses WebSocket runs and keep reasoning/tool-call replay metadata intact so resumed sessions do not lose or break follow-up reasoning-capable turns. (#53856) Thanks @xujingchen1996.</li>
|
||||
<li>Agents/errors: surface provider quota/reset details when available, but keep HTML/Cloudflare rate-limit pages on the generic fallback so raw error pages are not shown to users. (#54512) Thanks @bugkill3r.</li>
|
||||
<li>Claude CLI: switch the bundled Claude CLI backend to <code>stream-json</code> output so watchdogs see progress on long runs, and keep session/usage metadata even when Claude finishes with an empty result line. (#49698) Thanks @felear2022.</li>
|
||||
<li>Claude CLI/MCP: always pass a strict generated <code>--mcp-config</code> overlay for background Claude CLI runs, including the empty-server case, so Claude does not inherit ambient user/global MCP servers. (#54961) Thanks @markojak.</li>
|
||||
<li>Agents/embedded replies: surface mid-turn 429 and overload failures when embedded runs end without a user-visible reply, while preserving successful media-only replies that still use legacy <code>mediaUrl</code>. (#50930) Thanks @infichen.</li>
|
||||
<li>Chat/UI: move the chat send button onto the shared ghost-button theme styling, while keeping the stop button icon readable on the danger state. (#55075) Thanks @bottenbenny.</li>
|
||||
<li>WhatsApp/allowFrom: show a specific allowFrom policy error for valid blocked targets instead of the misleading <code><E.164|group JID></code> format hint. Thanks @mcaxtr.</li>
|
||||
<li>Agents/cooldowns: scope rate-limit cooldowns per model so one 429 no longer blocks every model on the same auth profile, replace the exponential 1 min -> 1 h escalation with a stepped 30 s / 1 min / 5 min ladder, and surface a user-facing countdown message when all models are rate-limited. (#49834) Thanks @kiranvk-2011.</li>
|
||||
<li>Agents/embedded transport errors: distinguish common network failures like connection refused, DNS lookup failure, and interrupted sockets from true timeouts in embedded-run user messaging and lifecycle diagnostics. (#51419) Thanks @scoootscooob.</li>
|
||||
<li>Telegram/pairing: ignore self-authored DM <code>message</code> updates so bot-pinned status cards and similar service updates do not trigger bogus pairing requests or re-enter inbound dispatch. (#54530) thanks @huntharo</li>
|
||||
<li>Mattermost/replies: keep pairing replies, slash-command fallback replies, and model-picker messages on the resolved config path so <code>exec:</code> SecretRef bot tokens work across all outbound reply branches. (#48347) thanks @mathiasnagler.</li>
|
||||
<li>Microsoft Teams/config: accept the existing <code>welcomeCard</code>, <code>groupWelcomeCard</code>, <code>promptStarters</code>, and feedback/reflection keys in strict config validation so already-supported Teams runtime settings stop failing schema checks. (#54679) Thanks @gumclaw.</li>
|
||||
<li>MCP/channels: add a Gateway-backed channel MCP bridge with Codex/Claude-facing conversation tools, Claude channel notifications, and safer stdio bridge lifecycle handling for reconnects and routed session discovery.</li>
|
||||
<li>Plugins/SDK: thread <code>moduleUrl</code> through plugin-sdk alias resolution so user-installed plugins outside the openclaw directory correctly resolve <code>openclaw/plugin-sdk/*</code> subpath imports, and gate <code>plugin-sdk:check-exports</code> in <code>release:check</code>. (#54283) Thanks @xieyongliang.</li>
|
||||
<li>Config/web fetch: allow the documented <code>tools.web.fetch.maxResponseBytes</code> setting in runtime schema validation so valid configs no longer fail with unrecognized-key errors. (#53401) Thanks @erhhung.</li>
|
||||
<li>Message tool/buttons: keep the shared <code>buttons</code> schema optional in merged tool definitions so plain <code>action=send</code> calls stop failing validation when no buttons are provided. (#54418) Thanks @adzendo.</li>
|
||||
<li>Agents/openai-compatible tool calls: deduplicate repeated tool call ids across live assistant messages and replayed history so OpenAI-compatible backends no longer reject duplicate <code>tool_call_id</code> values with HTTP 400. (#40996) Thanks @xaeon2026.</li>
|
||||
<li>Models/openai-completions: default non-native OpenAI-compatible providers to omit tool-definition <code>strict</code> fields unless users explicitly opt back in, so tool calling keeps working on providers that reject that option. (#45497) Thanks @sahancava.</li>
|
||||
<li>Plugins/context engines: retry strict legacy <code>assemble()</code> calls without the new <code>prompt</code> field when older engines reject it, preserving prompt-aware retrieval compatibility for pre-prompt plugins. (#50848) thanks @danhdoan.</li>
|
||||
<li>CLI/update status: explicitly say <code>up to date</code> when the local version already matches npm latest, while keeping the availability logic unchanged. (#51409) Thanks @dongzhenye.</li>
|
||||
<li>Daemon/Linux: stop flagging non-gateway systemd services as duplicate gateways just because their unit files mention OpenClaw, reducing false-positive doctor/log noise. (#45328) Thanks @gregretkowski.</li>
|
||||
<li>Feishu: close WebSocket connections on monitor stop/abort so ghost connections no longer persist, preventing duplicate event processing and resource leaks across restart cycles. (#52844) Thanks @schumilin.</li>
|
||||
<li>Feishu: use the original message <code>create_time</code> instead of <code>Date.now()</code> for inbound timestamps so offline-retried messages carry the correct authoring time, preventing mis-targeted agent actions on stale instructions. (#52809) Thanks @schumilin.</li>
|
||||
<li>Control UI/Skills: open skill detail dialogs with the browser modal lifecycle so clicking a skill row keeps the panel centered instead of rendering it off-screen at the bottom of the page.</li>
|
||||
<li>Matrix/replies: include quoted poll question/options in inbound reply context so the agent sees the original poll content when users reply to Matrix poll messages. (#55056) Thanks @alberthild.</li>
|
||||
<li>Matrix/plugins: keep plugin bootstrap from crashing when built runtime mixes bare and deep <code>matrix-js-sdk</code> entrypoints, so unrelated channels do not get taken down during plugin load. (#56273) Thanks @aquaright1.</li>
|
||||
<li>Agents/sandbox: honor <code>tools.sandbox.tools.alsoAllow</code>, let explicit sandbox re-allows remove matching built-in default-deny tools, and keep sandbox explain/error guidance aligned with the effective sandbox tool policy. (#54492) Thanks @ngutman.</li>
|
||||
<li>Agents/sandbox: make blocked-tool guidance glob-aware again, redact/sanitize session-specific explain hints for safer copy-paste, and avoid leaking control-character session keys in those hints. (#54684) Thanks @ngutman.</li>
|
||||
<li>Agents/compaction: trigger timeout recovery compaction before retrying high-context LLM timeouts so embedded runs stop repeating oversized requests. (#46417) thanks @joeykrug.</li>
|
||||
<li>Agents/compaction: reconcile <code>sessions.json.compactionCount</code> after a late embedded auto-compaction success so persisted session counts catch up once the handler reports completion. (#45493) Thanks @jackal092927.</li>
|
||||
<li>Agents/failover: classify Codex accountId token extraction failures as auth errors so model fallback continues to the next configured candidate. (#55206) Thanks @cosmicnet.</li>
|
||||
<li>Plugins/runtime: reuse only compatible active plugin registries across tools, providers, web search, and channel bootstrap, align <code>/tools/invoke</code> plugin loading with the session workspace, and retry outbound channel recovery when the pinned channel surface changes so plugin tools and channels stop disappearing or re-registering from mismatched runtime loads. Thanks @gumadeiras.</li>
|
||||
<li>Talk/macOS: stop direct system-voice failures from replaying system speech, use app-locale fallback for shared watchdog timing, and add regression coverage for the macOS fallback route and language-aware timeout policy. (#53511) thanks @hongsw.</li>
|
||||
<li>Discord/gateway cleanup: keep late Carbon reconnect-exhausted errors suppressed through startup/dispose cleanup so Discord monitor shutdown no longer crashes on late gateway close events. (#55373) Thanks @Takhoffman.</li>
|
||||
<li>Discord/gateway shutdown: treat expected reconnect-exhausted events during intentional lifecycle stop as clean shutdowns so startup-abort cleanup no longer surfaces false gateway failures. (#55324) Thanks @joelnishanth.</li>
|
||||
<li>Discord/gateway shutdown: suppress reconnect-exhausted events that were already buffered before teardown flips <code>lifecycleStopping</code>, so stale-socket Discord restarts no longer crash the whole gateway. Fixes #55403 and #55421. Thanks @lml2468 and @vincentkoc.</li>
|
||||
<li>GitHub Copilot/auth refresh: treat large <code>expires_at</code> values as seconds epochs and clamp far-future runtime auth refresh timers so Copilot token refresh cannot fall into a <code>setTimeout</code> overflow hot loop. (#55360) Thanks @michael-abdo.</li>
|
||||
<li>Agents/status: use the persisted runtime session model in <code>session_status</code> when no explicit override exists, and honor per-agent <code>thinkingDefault</code> in both <code>session_status</code> and <code>/status</code>. (#55425) Thanks @scoootscooob, @xaeon2026, and @ysfbsf.</li>
|
||||
<li>Heartbeat/runner: guarantee the interval timer is re-armed after heartbeat runs and unexpected runner errors so scheduled heartbeats do not silently stop after an interrupted cycle. (#52270) Thanks @MiloStack.</li>
|
||||
<li>Config/Doctor: rewrite stale bundled plugin load paths from legacy bundled-plugin locations to the packaged bundled path, including directory-name mismatches and slash-suffixed config entries. (#55054) Thanks @SnowSky1.</li>
|
||||
<li>WhatsApp/mentions: stop treating mentions embedded in quoted messages as direct mentions so replying to a message that @mentioned the bot no longer falsely triggers mention gating. (#52711) Thanks @lurebat.</li>
|
||||
<li>Matrix: keep separate 2-person rooms out of DM routing after <code>m.direct</code> seeds successfully, while still honoring explicit <code>is_direct</code> state and startup fallback recovery. (#54890) thanks @private-peter</li>
|
||||
<li>Agents/ollama fallback: surface non-2xx Ollama HTTP errors with a leading status code so HTTP 503 responses trigger model fallback again. (#55214) Thanks @bugkill3r.</li>
|
||||
<li>Feishu/tools: stop synthetic agent ids like <code>agent-spawner</code> from being treated as Feishu account ids during tool execution, so tools fall back to the configured/default Feishu account unless the contextual id is a real enabled Feishu account. (#55627) Thanks @MonkeyLeeT.</li>
|
||||
<li>Google/tools: strip empty <code>required: []</code> arrays from Gemini tool schemas so optional-only tool parameters no longer trigger Google validator 400s. (#52106) Thanks @oliviareid-svg.</li>
|
||||
<li>Onboarding/TUI/local gateways: show the resolved gateway port in setup output, clarify no-daemon local health/dashboard messaging, and preserve loopback Control UI auth on reruns and explicit local gateway URLs so local quickstart flows recover cleanly. (#55730) Thanks @shakkernerd.</li>
|
||||
<li>TUI/chat log: keep system messages as single logical entries and prune overflow at whole-message boundaries so wrapped system spacing stays intact. (#55732) Thanks @shakkernerd.</li>
|
||||
<li>TUI/activation: validate <code>/activation</code> arguments in the TUI and reject invalid values instead of silently coercing them to <code>mention</code>. (#55733) Thanks @shakkernerd.</li>
|
||||
<li>Agents/model switching: apply <code>/model</code> changes to active embedded runs at the next safe retry boundary, so overloaded or retrying turns switch to the newly selected model instead of staying pinned to the old provider.</li>
|
||||
<li>Agents/Codex fallback: classify Codex <code>server_error</code> payloads as failoverable, sanitize <code>Codex error:</code> payloads before they reach chat, preserve context-overflow guidance for prefixed <code>invalid_request_error</code> payloads, and omit provider <code>request_id</code> values from user-facing UI copy. (#42892) Thanks @xaeon2026.</li>
|
||||
<li>Memory/search: share memory embedding provider registrations across split plugin runtimes so memory search no longer fails with unknown provider errors after memory-core registers built-in adapters. (#55945) Thanks @glitch418x.</li>
|
||||
<li>Discord/Carbon beta: update <code>@buape/carbon</code> to the latest beta and pass the new <code>RateLimitError</code> request argument so Discord stays compatible with the upstream beta constructor change. (#55980) Thanks @ngutman.</li>
|
||||
<li>Plugins/inbound claims: pass full inbound attachment arrays through <code>inbound_claim</code> hook metadata while keeping the legacy singular media attachment fields for compatibility. (#55452) Thanks @huntharo.</li>
|
||||
<li>Plugins/Matrix: preserve sender filenames for inbound media by forwarding <code>originalFilename</code> to <code>saveMediaBuffer</code>. (#55692) thanks @esrehmki.</li>
|
||||
<li>Matrix/mentions: recognize <code>matrix.to</code> mentions whose visible label uses the bot's room display name, so <code>requireMention: true</code> rooms respond correctly in modern Matrix clients. (#55393) thanks @nickludlam.</li>
|
||||
<li>Ollama/thinking off: route <code>thinkingLevel=off</code> through the live Ollama extension request path so thinking-capable Ollama models now receive top-level <code>think: false</code> instead of silently generating hidden reasoning tokens. (#53200) Thanks @BruceMacD.</li>
|
||||
<li>Plugins/diffs: stage bundled <code>@pierre/diffs</code> runtime dependencies during packaged updates so the bundled diff viewer keeps loading after global installs and updates. (#56077) Thanks @gumadeiras.</li>
|
||||
<li>Plugins/diffs: load bundled Pierre themes without JSON module imports so diff rendering keeps working on newer Node builds. (#45869) thanks @NickHood1984.</li>
|
||||
<li>Plugins/uninstall: remove owned <code>channels.<id></code> config when uninstalling channel plugins, and keep the uninstall preview aligned with explicit channel ownership so built-in channels and shared keys stay intact. (#35915) Thanks @wbxl2000.</li>
|
||||
<li>Plugins/Matrix: prefer explicit DM signals when choosing outbound direct rooms and routing unmapped verification summaries, so strict 2-person fallback rooms do not outrank the real DM. (#56076) thanks @gumadeiras</li>
|
||||
<li>Plugins/Matrix: resolve env-backed <code>accessToken</code> and <code>password</code> SecretRefs against the active Matrix config env path during startup, and officially accept SecretRef <code>accessToken</code> config values. (#54980) thanks @kakahu2015.</li>
|
||||
<li>Microsoft Teams/proactive DMs: prefer the freshest personal conversation reference for <code>user:<aadObjectId></code> sends when multiple stored references exist, so replies stop targeting stale DM threads. (#54702) Thanks @gumclaw.</li>
|
||||
<li>Gateway/plugins: reuse the session workspace when building HTTP <code>/tools/invoke</code> tool lists and harden tool construction to infer the session agent workspace by default, so workspace plugins do not re-register on repeated HTTP tool calls. (#56101) thanks @neeravmakwana</li>
|
||||
<li>Brave/web search: normalize unsupported Brave <code>country</code> filters to <code>ALL</code> before request and cache-key generation so locale-derived values like <code>VN</code> stop failing with upstream 422 validation errors. (#55695) Thanks @chen-zhang-cs-code.</li>
|
||||
<li>Discord/replies: preserve leading indentation when stripping inline reply tags so reply-tagged plain text and fenced code blocks keep their formatting. (#55960) Thanks @Nanako0129.</li>
|
||||
<li>Daemon/status: surface immediate gateway close reasons from lightweight probes and prefer those concrete auth or pairing failures over generic timeouts in <code>openclaw daemon status</code>. (#56282) Thanks @mbelinky.</li>
|
||||
<li>Agents/failover: classify HTTP 410 errors as retryable timeouts by default while still preserving explicit session-expired, billing, and auth signals from the payload. (#55201) thanks @nikus-pan.</li>
|
||||
<li>Agents/subagents: restore completion announce delivery for extension channels like BlueBubbles. (#56348)</li>
|
||||
<li>Plugins/Matrix: load bundled <code>@matrix-org/matrix-sdk-crypto-nodejs</code> through <code>createRequire(...)</code> so E2EE media send and receive keep the package-local native binding lookup working in packaged ESM builds. (#54566) thanks @joelnishanth.</li>
|
||||
<li>Plugins/Matrix: encrypt E2EE image thumbnails with <code>thumbnail_file</code> while keeping unencrypted-room previews on <code>thumbnail_url</code>, so encrypted Matrix image events keep thumbnail metadata without leaking plaintext previews. (#54711) thanks @frischeDaten.</li>
|
||||
<li>Telegram/forum topics: keep native <code>/new</code> and <code>/reset</code> routed to the active topic by preserving the topic target on forum-thread command context. (#35963)</li>
|
||||
<li>Dashboard/chat UI: stop reloading full chat history on every live tool result in dashboard v2 so tool-heavy runs no longer trigger UI freeze/re-render storms while the final event still refreshes persisted history. (#45541) Thanks @BunsDev.</li>
|
||||
<li>Gateway/client requests: reject unanswered gateway RPC calls after a bounded timeout and clear their pending state, so stalled connections no longer leak hanging <code>GatewayClient.request()</code> promises indefinitely.</li>
|
||||
<li>Build/plugin-sdk bundling: bundle plugin-sdk subpath entries in one shared build pass so published packages stop duplicating shared chunks and avoid the recent plugin-sdk memory blow-up. (#45426) Thanks @TarasShyn.</li>
|
||||
<li>Ollama/reasoning visibility: stop promoting native <code>thinking</code> and <code>reasoning</code> fields into final assistant text so local reasoning models no longer leak internal thoughts in normal replies. (#45330) Thanks @xi7ang.</li>
|
||||
<li>Android/onboarding QR scan: switch setup QR scanning to Google Code Scanner so onboarding uses a more reliable scanner instead of the legacy embedded ZXing flow. (#45021) Thanks @obviyus.</li>
|
||||
<li>Browser/existing-session: harden driver validation and session lifecycle so transport errors trigger reconnects while tool-level errors preserve the session, and extract shared ARIA role sets to deduplicate Playwright and Chrome MCP snapshot paths. (#45682) Thanks @odysseus0.</li>
|
||||
<li>Browser/existing-session: accept text-only <code>list_pages</code> and <code>new_page</code> responses from Chrome DevTools MCP so live-session tab discovery and new-tab open flows keep working when the server omits structured page metadata.</li>
|
||||
<li>Control UI/insecure auth: preserve explicit shared token and password auth on plain-HTTP Control UI connects so LAN and reverse-proxy sessions no longer drop shared auth before the first WebSocket handshake. (#45088) Thanks @velvet-shark.</li>
|
||||
<li>Gateway/session reset: preserve <code>lastAccountId</code> and <code>lastThreadId</code> across gateway session resets so replies keep routing back to the same account and thread after <code>/reset</code>. (#44773) Thanks @Lanfei.</li>
|
||||
<li>macOS/onboarding: avoid self-restarting freshly bootstrapped launchd gateways and give new daemon installs longer to become healthy, so <code>openclaw onboard --install-daemon</code> no longer false-fails on slower Macs and fresh VM snapshots.</li>
|
||||
<li>Gateway/status: add <code>openclaw gateway status --require-rpc</code> and clearer Linux non-interactive daemon-install failure reporting so automation can fail hard on probe misses instead of treating a printed RPC error as green.</li>
|
||||
<li>macOS/exec approvals: respect per-agent exec approval settings in the gateway prompter, including allowlist fallback when the native prompt cannot be shown, so gateway-triggered <code>system.run</code> requests follow configured policy instead of always prompting or denying unexpectedly. (#13707) Thanks @sliekens.</li>
|
||||
<li>Telegram/media downloads: thread the same direct or proxy transport policy into SSRF-guarded file fetches so inbound attachments keep working when Telegram falls back between env-proxy and direct networking. (#44639) Thanks @obviyus.</li>
|
||||
<li>Telegram/inbound media IPv4 fallback: retry SSRF-guarded Telegram file downloads once with the same IPv4 fallback policy as Bot API calls so fresh installs on IPv6-broken hosts no longer fail to download inbound images.</li>
|
||||
<li>Windows/gateway install: bound <code>schtasks</code> calls and fall back to the Startup-folder login item when task creation hangs, so native <code>openclaw gateway install</code> fails fast instead of wedging forever on broken Scheduled Task setups.</li>
|
||||
<li>Windows/gateway stop: resolve Startup-folder fallback listeners from the installed <code>gateway.cmd</code> port, so <code>openclaw gateway stop</code> now actually kills fallback-launched gateway processes before restart.</li>
|
||||
<li>Windows/gateway status: reuse the installed service command environment when reading runtime status, so startup-fallback gateways keep reporting the configured port and running state in <code>gateway status --json</code> instead of falling back to <code>gateway port unknown</code>.</li>
|
||||
<li>Windows/gateway auth: stop attaching device identity on local loopback shared-token and password gateway calls, so native Windows agent replies no longer log stale <code>device signature expired</code> fallback noise before succeeding.</li>
|
||||
<li>Discord/gateway startup: treat plain-text and transient <code>/gateway/bot</code> metadata fetch failures as transient startup errors so Discord gateway boot no longer crashes on unhandled rejections. (#44397) Thanks @jalehman.</li>
|
||||
<li>Slack/probe: keep <code>auth.test()</code> bot and team metadata mapping stable while simplifying the probe result path. (#44775) Thanks @Cafexss.</li>
|
||||
<li>Dashboard/chat UI: render oversized plain-text replies as normal paragraphs instead of capped gray code blocks, so long desktop chat responses stay readable without tab-switching refreshes.</li>
|
||||
<li>Dashboard/chat UI: restore the <code>chat-new-messages</code> class on the New messages scroll pill so the button uses its existing compact styling instead of rendering as a full-screen SVG overlay. (#44856) Thanks @Astro-Han.</li>
|
||||
<li>Gateway/Control UI: restore the operator-only device-auth bypass and classify browser connect failures so origin and device-identity problems no longer show up as auth errors in the Control UI and web chat. (#45512) thanks @sallyom.</li>
|
||||
<li>macOS/voice wake: stop crashing wake-word command extraction when speech segment ranges come from a different transcript instance.</li>
|
||||
<li>Discord/allowlists: honor raw <code>guild_id</code> when hydrated guild objects are missing so allowlisted channels and threads like <code>#maintainers</code> no longer get false-dropped before channel allowlist checks.</li>
|
||||
<li>macOS/runtime locator: require Node >=22.16.0 during macOS runtime discovery so the app no longer accepts Node versions that the main runtime guard rejects later. Thanks @sumleo.</li>
|
||||
<li>Agents/custom providers: preserve blank API keys for loopback OpenAI-compatible custom providers by clearing the synthetic Authorization header at runtime, while keeping explicit apiKey and oauth/token config from silently downgrading into fake bearer auth. (#45631) Thanks @xinhuagu.</li>
|
||||
<li>Models/google-vertex Gemini flash-lite normalization: apply existing bare-ID preview normalization to <code>google-vertex</code> model refs and provider configs so <code>google-vertex/gemini-3.1-flash-lite</code> resolves as <code>gemini-3.1-flash-lite-preview</code>. (#42435) thanks @scoootscooob.</li>
|
||||
<li>iMessage/remote attachments: reject unsafe remote attachment paths before spawning SCP, so sender-controlled filenames can no longer inject shell metacharacters into remote media staging. Thanks @lintsinghua.</li>
|
||||
<li>Telegram/webhook auth: validate the Telegram webhook secret before reading or parsing request bodies, so unauthenticated requests are rejected immediately instead of consuming up to 1 MB first. Thanks @space08.</li>
|
||||
<li>Security/device pairing: make bootstrap setup codes single-use so pending device pairing requests cannot be silently replayed and widened to admin before approval. Thanks @tdjackey.</li>
|
||||
<li>Security/external content: strip zero-width and soft-hyphen marker-splitting characters during boundary sanitization so spoofed <code>EXTERNAL_UNTRUSTED_CONTENT</code> markers fall back to the existing hardening path instead of bypassing marker normalization.</li>
|
||||
<li>Security/exec approvals: unwrap more <code>pnpm</code> runtime forms during approval binding, including <code>pnpm --reporter ... exec</code> and direct <code>pnpm node</code> file runs, with matching regression coverage and docs updates.</li>
|
||||
<li>Security/exec approvals: fail closed for Perl <code>-M</code> and <code>-I</code> approval flows so preload and load-path module resolution stays outside approval-backed runtime execution unless the operator uses a broader explicit trust path.</li>
|
||||
<li>Security/exec approvals: recognize PowerShell <code>-File</code> and <code>-f</code> wrapper forms during inline-command extraction so approval and command-analysis paths treat file-based PowerShell launches like the existing <code>-Command</code> variants.</li>
|
||||
<li>Security/exec approvals: unwrap <code>env</code> dispatch wrappers inside shell-segment allowlist resolution on macOS so <code>env FOO=bar /path/to/bin</code> resolves against the effective executable instead of the wrapper token.</li>
|
||||
<li>Security/exec approvals: treat backslash-newline as shell line continuation during macOS shell-chain parsing so line-continued <code>$(</code> substitutions fail closed instead of slipping past command-substitution checks.</li>
|
||||
<li>Security/exec approvals: bind macOS skill auto-allow trust to both executable name and resolved path so same-basename binaries no longer inherit trust from unrelated skill bins.</li>
|
||||
<li>Build/plugin-sdk bundling: bundle plugin-sdk subpath entries in one shared build pass so published packages stop duplicating shared chunks and avoid the recent plugin-sdk memory blow-up. (#45426) Thanks @TarasShyn.</li>
|
||||
<li>Cron/isolated sessions: route nested cron-triggered embedded runner work onto the nested lane so isolated cron jobs no longer deadlock when compaction or other queued inner work runs. Thanks @vincentkoc.</li>
|
||||
<li>Agents/OpenAI-compatible compat overrides: respect explicit user <code>models[].compat</code> opt-ins for non-native <code>openai-completions</code> endpoints so usage-in-streaming capability overrides no longer get forced off when the endpoint actually supports them. (#44432) Thanks @cheapestinference.</li>
|
||||
<li>Agents/Azure OpenAI startup prompts: rephrase the built-in <code>/new</code>, <code>/reset</code>, and post-compaction startup instruction so Azure OpenAI deployments no longer hit HTTP 400 false positives from the content filter. (#43403) Thanks @xingsy97.</li>
|
||||
<li>Agents/memory bootstrap: load only one root memory file, preferring <code>MEMORY.md</code> and using <code>memory.md</code> as a fallback, so case-insensitive Docker mounts no longer inject duplicate memory context. (#26054) Thanks @Lanfei.</li>
|
||||
<li>Agents/compaction: compare post-compaction token sanity checks against full-session pre-compaction totals and skip the check when token estimation fails, so sessions with large bootstrap context keep real token counts instead of falling back to unknown. (#28347) thanks @efe-arv.</li>
|
||||
<li>Agents/compaction: preserve safeguard compaction summary language continuity via default and configurable custom instructions so persona drift is reduced after auto-compaction. (#10456) Thanks @keepitmello.</li>
|
||||
<li>Agents/tool warnings: distinguish gated core tools like <code>apply_patch</code> from plugin-only unknown entries in <code>tools.profile</code> warnings, so unavailable core tools now report current runtime/provider/model/config gating instead of suggesting a missing plugin.</li>
|
||||
<li>Config/validation: accept documented <code>agents.list[].params</code> per-agent overrides in strict config validation so <code>openclaw config validate</code> no longer rejects runtime-supported <code>cacheRetention</code>, <code>temperature</code>, and <code>maxTokens</code> settings. (#41171) Thanks @atian8179.</li>
|
||||
<li>Config/web fetch: restore runtime validation for documented <code>tools.web.fetch.readability</code> and <code>tools.web.fetch.firecrawl</code> settings so valid web fetch configs no longer fail with unrecognized-key errors. (#42583) Thanks @stim64045-spec.</li>
|
||||
<li>Signal/config validation: add <code>channels.signal.groups</code> schema support so per-group <code>requireMention</code>, <code>tools</code>, and <code>toolsBySender</code> overrides no longer get rejected during config validation. (#27199) Thanks @unisone.</li>
|
||||
<li>Config/discovery: accept <code>discovery.wideArea.domain</code> in strict config validation so unicast DNS-SD gateway configs no longer fail with an unrecognized-key error. (#35615) Thanks @ingyukoh.</li>
|
||||
<li>Telegram/media errors: redact Telegram file URLs before building media fetch errors so failed inbound downloads do not leak bot tokens into logs. Thanks @space08.</li>
|
||||
</ul>
|
||||
<p><a href="https://github.com/openclaw/openclaw/blob/main/CHANGELOG.md">View full changelog</a></p>
|
||||
]]></description>
|
||||
<enclosure url="https://github.com/openclaw/openclaw/releases/download/v2026.3.28/OpenClaw-2026.3.28.zip" length="25811288" type="application/octet-stream" sparkle:edSignature="SJp4ptVaGlOIXRPevS89DbfN2WKP0bKMXQoaT0fmLhy7pataDfHN0kxC3zu6P0Q/HtsxaESEhJUw48SCUNNKDA=="/>
|
||||
<enclosure url="https://github.com/openclaw/openclaw/releases/download/v2026.3.13/OpenClaw-2026.3.13.zip" length="23640917" type="application/octet-stream" sparkle:edSignature="Me63UHSpFLocTo5Lt7Iqsl0Hq61y3jTcZ9DUkiFl9xQvTE0+ORuqRMFWqPgYwfaKMgcgQmUbrV/uFzEoTIRHBA=="/>
|
||||
</item>
|
||||
<item>
|
||||
<title>2026.3.24</title>
|
||||
<pubDate>Wed, 25 Mar 2026 17:06:31 +0000</pubDate>
|
||||
<title>2026.3.12</title>
|
||||
<pubDate>Fri, 13 Mar 2026 04:25:50 +0000</pubDate>
|
||||
<link>https://raw.githubusercontent.com/openclaw/openclaw/main/appcast.xml</link>
|
||||
<sparkle:version>2026032490</sparkle:version>
|
||||
<sparkle:shortVersionString>2026.3.24</sparkle:shortVersionString>
|
||||
<sparkle:version>2026031290</sparkle:version>
|
||||
<sparkle:shortVersionString>2026.3.12</sparkle:shortVersionString>
|
||||
<sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
|
||||
<description><![CDATA[<h2>OpenClaw 2026.3.24</h2>
|
||||
<h3>Breaking</h3>
|
||||
<description><![CDATA[<h2>OpenClaw 2026.3.12</h2>
|
||||
<h3>Changes</h3>
|
||||
<ul>
|
||||
<li>Gateway/OpenAI compatibility: add <code>/v1/models</code> and <code>/v1/embeddings</code>, and forward explicit model overrides through <code>/v1/chat/completions</code> and <code>/v1/responses</code> for broader client and RAG compatibility. Thanks @vincentkoc.</li>
|
||||
<li>Agents/tools: make <code>/tools</code> show the tools the current agent can actually use right now, add a compact default view with an optional detailed mode, and add a live "Available Right Now" section in the Control UI so it is easier to see what will work before you ask.</li>
|
||||
<li>Microsoft Teams: migrate to the official Teams SDK and add AI-agent UX best practices including streaming 1:1 replies, welcome cards with prompt starters, feedback/reflection, informative status updates, typing indicators, and native AI labeling. (#51808)</li>
|
||||
<li>Microsoft Teams: add message edit and delete support for sent messages, including in-thread fallbacks when no explicit target is provided. (#49925)</li>
|
||||
<li>Skills/install metadata: add one-click install recipes to bundled skills (coding-agent, gh-issues, openai-whisper-api, session-logs, tmux, trello, weather) so the CLI and Control UI can offer dependency installation when requirements are missing. (#53411) Thanks @BunsDev.</li>
|
||||
<li>Control UI/skills: add status-filter tabs (All / Ready / Needs Setup / Disabled) with counts, replace inline skill cards with a click-to-detail dialog showing requirements, toggle switch, install action, API key entry, source metadata, and homepage link. (#53411) Thanks @BunsDev.</li>
|
||||
<li>Slack/interactive replies: restore rich reply parity for direct deliveries, auto-render simple trailing <code>Options:</code> lines as buttons/selects, improve Slack interactive setup defaults, and isolate reply controls from plugin interactive handlers. (#53389) Thanks @vincentkoc.</li>
|
||||
<li>CLI/containers: add <code>--container</code> and <code>OPENCLAW_CONTAINER</code> to run <code>openclaw</code> commands inside a running Docker or Podman OpenClaw container. (#52651) Thanks @sallyom.</li>
|
||||
<li>Discord/auto threads: add optional <code>autoThreadName: "generated"</code> naming so new auto-created threads can be renamed asynchronously with concise LLM-generated titles while keeping the existing message-based naming as the default. (#43366) Thanks @davidguttman.</li>
|
||||
<li>Plugins/hooks: add <code>before_dispatch</code> with canonical inbound metadata and route handled replies through the normal final-delivery path, preserving TTS and routed delivery semantics. (#50444) Thanks @gfzhx.</li>
|
||||
<li>Control UI/agents: convert agent workspace file rows to expandable <code><details></code> with lazy-loaded inline markdown preview, and add comprehensive <code>.sidebar-markdown</code> styles for headings, lists, code blocks, tables, blockquotes, and details/summary elements. (#53411) Thanks @BunsDev.</li>
|
||||
<li>Control UI/markdown preview: restyle the agent workspace file preview dialog with a frosted backdrop, sized panel, and styled header, and integrate <code>@create-markdown/preview</code> v2 system theme for rich markdown rendering (headings, tables, code blocks, callouts, blockquotes) that auto-adapts to the app's light/dark design tokens. (#53411) Thanks @BunsDev.</li>
|
||||
<li>macOS app/config: replace horizontal pill-based subsection navigation with a collapsible tree sidebar using disclosure chevrons and indented subsection rows. (#53411) Thanks @BunsDev.</li>
|
||||
<li>CLI/skills: soften missing-requirements label from "missing" to "needs setup" and surface API key setup guidance (where to get a key, CLI save command, storage path) in <code>openclaw skills info</code> output. (#53411) Thanks @BunsDev.</li>
|
||||
<li>macOS app/skills: add "Get your key" homepage link and storage-path hint to the API key editor dialog, and show the config path in save confirmation messages. (#53411) Thanks @BunsDev.</li>
|
||||
<li>Control UI/agents: add a "Not set" placeholder to the default agent model selector dropdown. (#53411) Thanks @BunsDev.</li>
|
||||
<li>Runtime/install: lower the supported Node 22 floor to <code>22.14+</code> while continuing to recommend Node 24, so npm installs and self-updates do not strand Node 22.14 users on older releases.</li>
|
||||
<li>CLI/update: preflight the target npm package <code>engines.node</code> before <code>openclaw update</code> runs a global package install, so outdated Node runtimes fail with a clear upgrade message instead of attempting an unsupported latest release.</li>
|
||||
<li>Control UI/dashboard-v2: refresh the gateway dashboard with modular overview, chat, config, agent, and session views, plus a command palette, mobile bottom tabs, and richer chat tools like slash commands, search, export, and pinned messages. (#41503) Thanks @BunsDev.</li>
|
||||
<li>OpenAI/GPT-5.4 fast mode: add configurable session-level fast toggles across <code>/fast</code>, TUI, Control UI, and ACP, with per-model config defaults and OpenAI/Codex request shaping.</li>
|
||||
<li>Anthropic/Claude fast mode: map the shared <code>/fast</code> toggle and <code>params.fastMode</code> to direct Anthropic API-key <code>service_tier</code> requests, with live verification for both Anthropic and OpenAI fast-mode tiers.</li>
|
||||
<li>Models/plugins: move Ollama, vLLM, and SGLang onto the provider-plugin architecture, with provider-owned onboarding, discovery, model-picker setup, and post-selection hooks so core provider wiring is more modular.</li>
|
||||
<li>Docs/Kubernetes: Add a starter K8s install path with raw manifests, Kind setup, and deployment docs. Thanks @sallyom @dzianisv @egkristi</li>
|
||||
<li>Agents/subagents: add <code>sessions_yield</code> so orchestrators can end the current turn immediately, skip queued tool work, and carry a hidden follow-up payload into the next session turn. (#36537) thanks @jriff</li>
|
||||
<li>Slack/agent replies: support <code>channelData.slack.blocks</code> in the shared reply delivery path so agents can send Block Kit messages through standard Slack outbound delivery. (#44592) Thanks @vincentkoc.</li>
|
||||
</ul>
|
||||
<h3>Fixes</h3>
|
||||
<ul>
|
||||
<li>Outbound media/local files: align outbound media access with the configured fs policy so host-local files and inbound-media paths keep sending when <code>workspaceOnly</code> is off, while strict workspace-only agents remain sandboxed.</li>
|
||||
<li>Security/sandbox media dispatch: close the <code>mediaUrl</code>/<code>fileUrl</code> alias bypass so outbound tool and message actions cannot escape media-root restrictions. (#54034)</li>
|
||||
<li>Gateway/restart sentinel: wake the interrupted agent session via heartbeat after restart instead of only sending a best-effort restart note, retry outbound delivery once on transient failure, and preserve explicit thread/topic routing through the wake path so replies land in the correct Telegram topic or Slack thread. (#53940) Thanks @VACInc.</li>
|
||||
<li>Docker/setup: avoid the pre-start <code>openclaw-cli</code> shared-network namespace loop by routing setup-time onboard/config writes through <code>openclaw-gateway</code>, so fresh Docker installs stop failing before the gateway comes up. (#53385) Thanks @amsminn.</li>
|
||||
<li>Gateway/channels: keep channel startup sequential while isolating per-channel boot failures, so one broken channel no longer blocks later channels from starting. (#54215) Thanks @JonathanJing.</li>
|
||||
<li>Embedded runs/secrets: stop unresolved <code>SecretRef</code> config from crashing embedded agent runs by falling back to the resolved runtime snapshot when needed. Fixes #45838.</li>
|
||||
<li>WhatsApp/groups: track recent gateway-sent message IDs and suppress only matching group echoes, preserving owner <code>/status</code>, <code>/new</code>, and <code>/activation</code> commands from linked-account <code>fromMe</code> traffic. (#53624) Thanks @w-sss.</li>
|
||||
<li>WhatsApp/reply-to-bot detection: restore implicit group reply detection by unwrapping <code>botInvokeMessage</code> payloads and reading <code>selfLid</code> from <code>creds.json</code>, so reply-based mentions reach the bot again in linked-account group chats.</li>
|
||||
<li>Telegram/forum topics: recover <code>#General</code> topic <code>1</code> routing when Telegram omits forum metadata, including native commands, interactive callbacks, inbound message context, and fallback error replies. (#53699) thanks @huntharo</li>
|
||||
<li>Discord/gateway supervision: centralize gateway error handling behind a lifetime-owned supervisor so early, active, and late-teardown Carbon gateway errors stay classified consistently and stop surfacing as process-killing teardown crashes.</li>
|
||||
<li>Discord/timeouts: send a visible timeout reply when the inbound Discord worker times out before a final reply starts, including created auto-thread targets and queued-run ordering. (#53823) Thanks @Kimbo7870.</li>
|
||||
<li>ACP/direct chats: always deliver a terminal ACP result when final TTS does not yield audio, even if block text already streamed earlier, and skip redundant empty-text final synthesis. (#53692) Thanks @w-sss.</li>
|
||||
<li>Telegram/outbound errors: preserve actionable 403 membership/block/kick details and treat <code>bot not a member</code> as a permanent delivery failure so Telegram sends stop retrying doomed chats. (#53635) Thanks @w-sss.</li>
|
||||
<li>Telegram/photos: preflight Telegram photo dimension and aspect-ratio rules, and fall back to document sends when image metadata is invalid or unavailable so photo uploads stop failing with <code>PHOTO_INVALID_DIMENSIONS</code>. (#52545) Thanks @hnshah.</li>
|
||||
<li>Slack/runtime defaults: trim Slack DM reply overhead, restore Codex auto transport, and tighten Slack/web-search runtime defaults around DM preview threading, cache scoping, warning dedupe, and explicit web-search opt-in. (#53957) Thanks @vincentkoc.</li>
|
||||
<li>Security/device pairing: switch <code>/pair</code> and <code>openclaw qr</code> setup codes to short-lived bootstrap tokens so the next release no longer embeds shared gateway credentials in chat or QR pairing payloads. Thanks @lintsinghua.</li>
|
||||
<li>Security/plugins: disable implicit workspace plugin auto-load so cloned repositories cannot execute workspace plugin code without an explicit trust decision. (<code>GHSA-99qw-6mr3-36qr</code>)(#44174) Thanks @lintsinghua and @vincentkoc.</li>
|
||||
<li>Models/Kimi Coding: send <code>anthropic-messages</code> tools in native Anthropic format again so <code>kimi-coding</code> stops degrading tool calls into XML/plain-text pseudo invocations instead of real <code>tool_use</code> blocks. (#38669, #39907, #40552) Thanks @opriz.</li>
|
||||
<li>TUI/chat log: reuse the active assistant message component for the same streaming run so <code>openclaw tui</code> no longer renders duplicate assistant replies. (#35364) Thanks @lisitan.</li>
|
||||
<li>Telegram/model picker: make inline model button selections persist the chosen session model correctly, clear overrides when selecting the configured default, and include effective fallback models in <code>/models</code> button validation. (#40105) Thanks @avirweb.</li>
|
||||
<li>Cron/proactive delivery: keep isolated direct cron sends out of the write-ahead resend queue so transient-send retries do not replay duplicate proactive messages after restart. (#40646) Thanks @openperf and @vincentkoc.</li>
|
||||
<li>Models/Kimi Coding: send the built-in <code>User-Agent: claude-code/0.1.0</code> header by default for <code>kimi-coding</code> while still allowing explicit provider headers to override it, so Kimi Code subscription auth can work without a local header-injection proxy. (#30099) Thanks @Amineelfarssi and @vincentkoc.</li>
|
||||
<li>Models/OpenAI Codex Spark: keep <code>gpt-5.3-codex-spark</code> working on the <code>openai-codex/*</code> path via resolver fallbacks and clearer Codex-only handling, while continuing to suppress the stale direct <code>openai/*</code> Spark row that OpenAI rejects live.</li>
|
||||
<li>Ollama/Kimi Cloud: apply the Moonshot Kimi payload compatibility wrapper to Ollama-hosted Kimi models like <code>kimi-k2.5:cloud</code>, so tool routing no longer breaks when thinking is enabled. (#41519) Thanks @vincentkoc.</li>
|
||||
<li>Moonshot CN API: respect explicit <code>baseUrl</code> (api.moonshot.cn) in implicit provider resolution so platform.moonshot.cn API keys authenticate correctly instead of returning HTTP 401. (#33637) Thanks @chengzhichao-xydt.</li>
|
||||
<li>Kimi Coding/provider config: respect explicit <code>models.providers["kimi-coding"].baseUrl</code> when resolving the implicit provider so custom Kimi Coding endpoints no longer get overwritten by the built-in default. (#36353) Thanks @2233admin.</li>
|
||||
<li>Gateway/main-session routing: keep TUI and other <code>mode:UI</code> main-session sends on the internal surface when <code>deliver</code> is enabled, so replies no longer inherit the session's persisted Telegram/WhatsApp route. (#43918) Thanks @obviyus.</li>
|
||||
<li>BlueBubbles/self-chat echo dedupe: drop reflected duplicate webhook copies only when a matching <code>fromMe</code> event was just seen for the same chat, body, and timestamp, preventing self-chat loops without broad webhook suppression. Related to #32166. (#38442) Thanks @vincentkoc.</li>
|
||||
<li>iMessage/self-chat echo dedupe: drop reflected duplicate copies only when a matching <code>is_from_me</code> event was just seen for the same chat, text, and <code>created_at</code>, preventing self-chat loops without broad text-only suppression. Related to #32166. (#38440) Thanks @vincentkoc.</li>
|
||||
<li>Subagents/completion announce retries: raise the default announce timeout to 90 seconds and stop retrying gateway-timeout failures for externally delivered completion announces, preventing duplicate user-facing completion messages after slow gateway responses. Fixes #41235. Thanks @vasujain00 and @vincentkoc.</li>
|
||||
<li>Mattermost/block streaming: fix duplicate message delivery (one threaded, one top-level) when block streaming is active by excluding <code>replyToId</code> from the block reply dedup key and adding an explicit <code>threading</code> dock to the Mattermost plugin. (#41362) Thanks @mathiasnagler and @vincentkoc.</li>
|
||||
<li>Mattermost/reply media delivery: pass agent-scoped <code>mediaLocalRoots</code> through shared reply delivery so allowed local files upload correctly from button, slash-command, and model-picker replies. (#44021) Thanks @LyleLiu666.</li>
|
||||
<li>macOS/Reminders: add the missing <code>NSRemindersUsageDescription</code> to the bundled app so <code>apple-reminders</code> can trigger the system permission prompt from OpenClaw.app. (#8559) Thanks @dinakars777.</li>
|
||||
<li>Gateway/session discovery: discover disk-only and retired ACP session stores under custom templated <code>session.store</code> roots so ACP reconciliation, session-id/session-label targeting, and run-id fallback keep working after restart. (#44176) thanks @gumadeiras.</li>
|
||||
<li>Plugins/env-scoped roots: fix plugin discovery/load caches and provenance tracking so same-process <code>HOME</code>/<code>OPENCLAW_HOME</code> changes no longer reuse stale plugin state or misreport <code>~/...</code> plugins as untracked. (#44046) thanks @gumadeiras.</li>
|
||||
<li>Models/OpenRouter native ids: canonicalize native OpenRouter model keys across config writes, runtime lookups, fallback management, and <code>models list --plain</code>, and migrate legacy duplicated <code>openrouter/openrouter/...</code> config entries forward on write.</li>
|
||||
<li>Windows/native update: make package installs use the npm update path instead of the git path, carry portable Git into native Windows updates, and mirror the installer's Windows npm env so <code>openclaw update</code> no longer dies early on missing <code>git</code> or <code>node-llama-cpp</code> download setup.</li>
|
||||
<li>Sandbox/write: preserve pinned mutation-helper payload stdin so sandboxed <code>write</code> no longer reports success while creating empty files. (#43876) Thanks @glitch418x.</li>
|
||||
<li>Security/exec approvals: escape invisible Unicode format characters in approval prompts so zero-width command text renders as visible <code>\u{...}</code> escapes instead of spoofing the reviewed command. (<code>GHSA-pcqg-f7rg-xfvv</code>)(#43687) Thanks @EkiXu and @vincentkoc.</li>
|
||||
<li>Hooks/loader: fail closed when workspace hook paths cannot be resolved with <code>realpath</code>, so unreadable or broken internal hook paths are skipped instead of falling back to unresolved imports. (#44437) Thanks @vincentkoc.</li>
|
||||
<li>Hooks/agent deliveries: dedupe repeated hook requests by optional idempotency key so webhook retries can reuse the first run instead of launching duplicate agent executions. (#44438) Thanks @vincentkoc.</li>
|
||||
<li>Security/exec detection: normalize compatibility Unicode and strip invisible formatting code points before obfuscation checks so zero-width and fullwidth command tricks no longer suppress heuristic detection. (<code>GHSA-9r3v-37xh-2cf6</code>)(#44091) Thanks @wooluo and @vincentkoc.</li>
|
||||
<li>Security/exec allowlist: preserve POSIX case sensitivity and keep <code>?</code> within a single path segment so exact-looking allowlist patterns no longer overmatch executables across case or directory boundaries. (<code>GHSA-f8r2-vg7x-gh8m</code>)(#43798) Thanks @zpbrent and @vincentkoc.</li>
|
||||
<li>Security/commands: require sender ownership for <code>/config</code> and <code>/debug</code> so authorized non-owner senders can no longer reach owner-only config and runtime debug surfaces. (<code>GHSA-r7vr-gr74-94p8</code>)(#44305) Thanks @tdjackey and @vincentkoc.</li>
|
||||
<li>Security/gateway auth: clear unbound client-declared scopes on shared-token WebSocket connects so device-less shared-token operators cannot self-declare elevated scopes. (<code>GHSA-rqpp-rjj8-7wv8</code>)(#44306) Thanks @LUOYEcode and @vincentkoc.</li>
|
||||
<li>Security/browser.request: block persistent browser profile create/delete routes from write-scoped <code>browser.request</code> so callers can no longer persist admin-only browser profile changes through the browser control surface. (<code>GHSA-vmhq-cqm9-6p7q</code>)(#43800) Thanks @tdjackey and @vincentkoc.</li>
|
||||
<li>Security/agent: reject public spawned-run lineage fields and keep workspace inheritance on the internal spawned-session path so external <code>agent</code> callers can no longer override the gateway workspace boundary. (<code>GHSA-2rqg-gjgv-84jm</code>)(#43801) Thanks @tdjackey and @vincentkoc.</li>
|
||||
<li>Security/session_status: enforce sandbox session-tree visibility and shared agent-to-agent access guards before reading or mutating target session state, so sandboxed subagents can no longer inspect parent session metadata or write parent model overrides via <code>session_status</code>. (<code>GHSA-wcxr-59v9-rxr8</code>)(#43754) Thanks @tdjackey and @vincentkoc.</li>
|
||||
<li>Security/agent tools: mark <code>nodes</code> as explicitly owner-only and document/test that <code>canvas</code> remains a shared trusted-operator surface unless a real boundary bypass exists.</li>
|
||||
<li>Security/exec approvals: fail closed for Ruby approval flows that use <code>-r</code>, <code>--require</code>, or <code>-I</code> so approval-backed commands no longer bind only the main script while extra local code-loading flags remain outside the reviewed file snapshot.</li>
|
||||
<li>Security/device pairing: cap issued and verified device-token scopes to each paired device's approved scope baseline so stale or overbroad tokens cannot exceed approved access. (<code>GHSA-2pwv-x786-56f8</code>)(#43686) Thanks @tdjackey and @vincentkoc.</li>
|
||||
<li>Docs/onboarding: align the legacy wizard reference and <code>openclaw onboard</code> command docs with the Ollama onboarding flow so all onboarding reference paths now document <code>--auth-choice ollama</code>, Cloud + Local mode, and non-interactive usage. (#43473) Thanks @BruceMacD.</li>
|
||||
<li>Models/secrets: enforce source-managed SecretRef markers in generated <code>models.json</code> so runtime-resolved provider secrets are not persisted when runtime projection is skipped. (#43759) Thanks @joshavant.</li>
|
||||
<li>Security/WebSocket preauth: shorten unauthenticated handshake retention and reject oversized pre-auth frames before application-layer parsing to reduce pre-pairing exposure on unsupported public deployments. (<code>GHSA-jv4g-m82p-2j93</code>)(#44089) (<code>GHSA-xwx2-ppv2-wx98</code>)(#44089) Thanks @ez-lbz and @vincentkoc.</li>
|
||||
<li>Security/proxy attachments: restore the shared media-store size cap for persisted browser proxy files so oversized payloads are rejected instead of overriding the intended 5 MB limit. (<code>GHSA-6rph-mmhp-h7h9</code>)(#43684) Thanks @tdjackey and @vincentkoc.</li>
|
||||
<li>Security/host env: block inherited <code>GIT_EXEC_PATH</code> from sanitized host exec environments so Git helper resolution cannot be steered by host environment state. (<code>GHSA-jf5v-pqgw-gm5m</code>)(#43685) Thanks @zpbrent and @vincentkoc.</li>
|
||||
<li>Security/Feishu webhook: require <code>encryptKey</code> alongside <code>verificationToken</code> in webhook mode so unsigned forged events are rejected instead of being processed with token-only configuration. (<code>GHSA-g353-mgv3-8pcj</code>)(#44087) Thanks @lintsinghua and @vincentkoc.</li>
|
||||
<li>Security/Feishu reactions: preserve looked-up group chat typing and fail closed on ambiguous reaction context so group authorization and mention gating cannot be bypassed through synthetic <code>p2p</code> reactions. (<code>GHSA-m69h-jm2f-2pv8</code>)(#44088) Thanks @zpbrent and @vincentkoc.</li>
|
||||
<li>Security/LINE webhook: require signatures for empty-event POST probes too so unsigned requests no longer confirm webhook reachability with a <code>200</code> response. (<code>GHSA-mhxh-9pjm-w7q5</code>)(#44090) Thanks @TerminalsandCoffee and @vincentkoc.</li>
|
||||
<li>Security/Zalo webhook: rate limit invalid secret guesses before auth so weak webhook secrets cannot be brute-forced through unauthenticated churned requests without pre-auth <code>429</code> responses. (<code>GHSA-5m9r-p9g7-679c</code>)(#44173) Thanks @zpbrent and @vincentkoc.</li>
|
||||
<li>Security/Zalouser groups: require stable group IDs for allowlist auth by default and gate mutable group-name matching behind <code>channels.zalouser.dangerouslyAllowNameMatching</code>. Thanks @zpbrent.</li>
|
||||
<li>Security/Slack and Teams routing: require stable channel and team IDs for allowlist routing by default, with mutable name matching only via each channel's <code>dangerouslyAllowNameMatching</code> break-glass flag.</li>
|
||||
<li>Security/exec approvals: fail closed for ambiguous inline loader and shell-payload script execution, bind the real script after POSIX shell value-taking flags, and unwrap <code>pnpm</code>/<code>npm exec</code>/<code>npx</code> script runners before approval binding. (<code>GHSA-57jw-9722-6rf2</code>)(<code>GHSA-jvqh-rfmh-jh27</code>)(<code>GHSA-x7pp-23xv-mmr4</code>)(<code>GHSA-jc5j-vg4r-j5jx</code>)(#44247) Thanks @tdjackey and @vincentkoc.</li>
|
||||
<li>Doctor/gateway service audit: canonicalize service entrypoint paths before comparing them so symlink-vs-realpath installs no longer trigger false "entrypoint does not match the current install" repair prompts. (#43882) Thanks @ngutman.</li>
|
||||
<li>Doctor/gateway service audit: earlier groundwork for this fix landed in the superseded #28338 branch. Thanks @realriphub.</li>
|
||||
<li>Gateway/session stores: regenerate the Swift push-test protocol models and align Windows native session-store realpath handling so protocol checks and sync session discovery stop drifting on Windows. (#44266) thanks @jalehman.</li>
|
||||
<li>Context engine/session routing: forward optional <code>sessionKey</code> through context-engine lifecycle calls so plugins can see structured routing metadata during bootstrap, assembly, post-turn ingestion, and compaction. (#44157) thanks @jalehman.</li>
|
||||
<li>Agents/failover: classify z.ai <code>network_error</code> stop reasons as retryable timeouts so provider connectivity failures trigger fallback instead of surfacing raw unhandled-stop-reason errors. (#43884) Thanks @hougangdev.</li>
|
||||
<li>Memory/session sync: add mode-aware post-compaction session reindexing with <code>agents.defaults.compaction.postIndexSync</code> plus <code>agents.defaults.memorySearch.sync.sessions.postCompactionForce</code>, so compacted session memory can refresh immediately without forcing every deployment into synchronous reindexing. (#25561) thanks @rodrigouroz.</li>
|
||||
<li>Telegram/model picker: make inline model button selections persist the chosen session model correctly, clear overrides when selecting the configured default, and include effective fallback models in <code>/models</code> button validation. (#40105) Thanks @avirweb.</li>
|
||||
<li>Telegram/native command sync: suppress expected <code>BOT_COMMANDS_TOO_MUCH</code> retry error noise, add a final fallback summary log, and document the difference between command-menu overflow and real Telegram network failures.</li>
|
||||
<li>Mattermost/reply media delivery: pass agent-scoped <code>mediaLocalRoots</code> through shared reply delivery so allowed local files upload correctly from button, slash-command, and model-picker replies. (#44021) Thanks @LyleLiu666.</li>
|
||||
<li>Plugins/env-scoped roots: fix plugin discovery/load caches and provenance tracking so same-process <code>HOME</code>/<code>OPENCLAW_HOME</code> changes no longer reuse stale plugin state or misreport <code>~/...</code> plugins as untracked. (#44046) thanks @gumadeiras.</li>
|
||||
<li>Gateway/session discovery: discover disk-only and retired ACP session stores under custom templated <code>session.store</code> roots so ACP reconciliation, session-id/session-label targeting, and run-id fallback keep working after restart. (#44176) thanks @gumadeiras.</li>
|
||||
<li>Models/OpenRouter native ids: canonicalize native OpenRouter model keys across config writes, runtime lookups, fallback management, and <code>models list --plain</code>, and migrate legacy duplicated <code>openrouter/openrouter/...</code> config entries forward on write.</li>
|
||||
<li>Gateway/hooks: bucket hook auth failures by forwarded client IP behind trusted proxies and warn when <code>hooks.allowedAgentIds</code> leaves hook routing unrestricted.</li>
|
||||
<li>Agents/compaction: skip the post-compaction <code>cache-ttl</code> marker write when a compaction completed in the same attempt, preventing the next turn from immediately triggering a second tiny compaction. (#28548) thanks @MoerAI.</li>
|
||||
<li>Native chat/macOS: add <code>/new</code>, <code>/reset</code>, and <code>/clear</code> reset triggers, keep shared main-session aliases aligned, and ignore stale model-selection completions so native chat state stays in sync across reset and fast model changes. (#10898) Thanks @Nachx639.</li>
|
||||
<li>Agents/compaction safeguard: route missing-model and missing-API-key cancellation warnings through the shared subsystem logger so they land in structured and file logs. (#9974) Thanks @dinakars777.</li>
|
||||
<li>Cron/doctor: stop flagging canonical <code>agentTurn</code> and <code>systemEvent</code> payload kinds as legacy cron storage, while still normalizing whitespace-padded and non-canonical variants. (#44012) Thanks @shuicici.</li>
|
||||
<li>ACP/client final-message delivery: preserve terminal assistant text snapshots before resolving <code>end_turn</code>, so ACP clients no longer drop the last visible reply when the gateway sends the final message body on the terminal chat event. (#17615) Thanks @pjeby.</li>
|
||||
<li>Telegram/Discord status reactions: show a temporary compacting reaction during auto-compaction pauses and restore thinking afterward so the bot no longer appears frozen while context is being compacted. (#35474) thanks @Cypherm.</li>
|
||||
</ul>
|
||||
<p><a href="https://github.com/openclaw/openclaw/blob/main/CHANGELOG.md">View full changelog</a></p>
|
||||
]]></description>
|
||||
<enclosure url="https://github.com/openclaw/openclaw/releases/download/v2026.3.24/OpenClaw-2026.3.24.zip" length="24749233" type="application/octet-stream" sparkle:edSignature="gLm2VvI+PPEnNy4klYSs9WmZLkJTF5BcfFparrtPdnmeE4xgc8kFfICg445I039ev9/A6xGav7pm08reUHDcAg=="/>
|
||||
<enclosure url="https://github.com/openclaw/openclaw/releases/download/v2026.3.12/OpenClaw-2026.3.12.zip" length="23628700" type="application/octet-stream" sparkle:edSignature="o6Zdcw36l3I0jUg14H+RBqNwrhuuSsq1WMDi4tBRa1+5TC3VCVdFKZ2hzmH2Xjru9lDEzVMP8v2A6RexSbOCBQ=="/>
|
||||
</item>
|
||||
<item>
|
||||
<title>2026.3.23</title>
|
||||
<pubDate>Mon, 23 Mar 2026 16:59:51 -0700</pubDate>
|
||||
<title>2026.3.8-beta.1</title>
|
||||
<pubDate>Mon, 09 Mar 2026 07:19:57 +0000</pubDate>
|
||||
<link>https://raw.githubusercontent.com/openclaw/openclaw/main/appcast.xml</link>
|
||||
<sparkle:version>2026032390</sparkle:version>
|
||||
<sparkle:shortVersionString>2026.3.23</sparkle:shortVersionString>
|
||||
<sparkle:version>2026030801</sparkle:version>
|
||||
<sparkle:shortVersionString>2026.3.8-beta.1</sparkle:shortVersionString>
|
||||
<sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
|
||||
<description><![CDATA[<h2>OpenClaw 2026.3.23</h2>
|
||||
<h3>Breaking</h3>
|
||||
<description><![CDATA[<h2>OpenClaw 2026.3.8-beta.1</h2>
|
||||
<h3>Changes</h3>
|
||||
<ul>
|
||||
<li>CLI/backup: add <code>openclaw backup create</code> and <code>openclaw backup verify</code> for local state archives, including <code>--only-config</code>, <code>--no-include-workspace</code>, manifest/payload validation, and backup guidance in destructive flows. (#40163) thanks @shichangs.</li>
|
||||
<li>macOS/onboarding: add a remote gateway token field for remote mode, preserve existing non-plaintext <code>gateway.remote.token</code> config values until explicitly replaced, and warn when the loaded token shape cannot be used directly from the macOS app. (#40187, supersedes #34614) Thanks @cgdusek.</li>
|
||||
<li>Talk mode: add top-level <code>talk.silenceTimeoutMs</code> config so Talk waits a configurable amount of silence before auto-sending the current transcript, while keeping each platform's existing default pause window when unset. (#39607) Thanks @danodoesdesign. Fixes #17147.</li>
|
||||
<li>TUI: infer the active agent from the current workspace when launched inside a configured agent workspace, while preserving explicit <code>agent:</code> session targets. (#39591) thanks @arceus77-7.</li>
|
||||
<li>Tools/Brave web search: add opt-in <code>tools.web.search.brave.mode: "llm-context"</code> so <code>web_search</code> can call Brave's LLM Context endpoint and return extracted grounding snippets with source metadata, plus config/docs/test coverage. (#33383) Thanks @thirumaleshp.</li>
|
||||
<li>CLI/install: include the short git commit hash in <code>openclaw --version</code> output when metadata is available, and keep installer version checks compatible with the decorated format. (#39712) thanks @sourman.</li>
|
||||
<li>CLI/backup: improve archive naming for date sorting, add config-only backup mode, and harden backup planning, publication, and verification edge cases. (#40163) Thanks @gumadeiras.</li>
|
||||
<li>ACP/Provenance: add optional ACP ingress provenance metadata and visible receipt injection (<code>openclaw acp --provenance off|meta|meta+receipt</code>) so OpenClaw agents can retain and report ACP-origin context with session trace IDs. (#40473) thanks @mbelinky.</li>
|
||||
<li>Tools/web search: alphabetize provider ordering across runtime selection, onboarding/configure pickers, and config metadata, so provider lists stay neutral and multi-key auto-detect now prefers Grok before Kimi. (#40259) thanks @kesku.</li>
|
||||
<li>Docs/Web search: restore $5/month free-credit details, replace defunct "Data for Search"/"Data for AI" plan names with current "Search" plan, and note legacy subscription validity in Brave setup docs. Follows up on #26860. (#40111) Thanks @remusao.</li>
|
||||
<li>Extensions/ACPX tests: move the shared runtime fixture helper from <code>src/runtime-internals/</code> to <code>src/test-utils/</code> so the test-only helper no longer looks like shipped runtime code.</li>
|
||||
</ul>
|
||||
<h3>Fixes</h3>
|
||||
<ul>
|
||||
<li>Browser/Chrome MCP: wait for existing-session browser tabs to become usable after attach instead of treating the initial Chrome MCP handshake as ready, which reduces user-profile timeouts and repeated consent churn on macOS Chrome attach flows. Fixes #52930. Thanks @vincentkoc.</li>
|
||||
<li>Browser/CDP: reuse an already-running loopback browser after a short initial reachability miss instead of immediately falling back to relaunch detection, which fixes second-run browser start/open regressions on slower headless Linux setups. Fixes #53004. Thanks @vincentkoc.</li>
|
||||
<li>ClawHub/macOS auth: honor macOS auth config and XDG auth paths for saved ClawHub credentials, so <code>openclaw skills ...</code> and gateway skill browsing keep using the signed-in auth state instead of silently falling back to unauthenticated mode. Fixes #53034.</li>
|
||||
<li>ClawHub/macOS: read the local ClawHub login from the macOS Application Support path and still honor XDG config on macOS, so skill browsing uses the logged-in token on both default and XDG-style setups. Fixes #52949. Thanks @scoootscooob.</li>
|
||||
<li>ClawHub/skills: resolve the local ClawHub auth token for gateway skill browsing and switch browse-all requests to search so ClawControl stops falling into unauthenticated 429s and empty authenticated skill lists. Fixes #52949. Thanks @vincentkoc.</li>
|
||||
<li>Plugins/message tool: make Discord <code>components</code> and Slack <code>blocks</code> optional again, and route Feishu <code>message(..., media=...)</code> sends through the outbound media path, so pin/unpin/react flows stop failing schema validation and Feishu file/image attachments actually send. Fixes #52970 and #52962. Thanks @vincentkoc.</li>
|
||||
<li>Gateway/model pricing: stop <code>openrouter/auto</code> pricing refresh from recursing indefinitely during bootstrap, so OpenRouter auto routes can populate cached pricing and <code>usage.cost</code> again. Fixes #53035. Thanks @vincentkoc.</li>
|
||||
<li>Mistral/models: lower bundled Mistral max-token defaults to safe output budgets and teach <code>openclaw doctor --fix</code> to repair old persisted Mistral provider configs that still carry context-sized output limits, avoiding deterministic Mistral 422 rejects on fresh and existing setups. Fixes #52599. Thanks @vincentkoc.</li>
|
||||
<li>Agents/web_search: use the active runtime <code>web_search</code> provider instead of stale/default selection, so agent turns keep hitting the provider you actually configured. Fixes #53020. Thanks @jzakirov.</li>
|
||||
<li>Models/OpenAI Codex OAuth: bootstrap the env-configured HTTP/HTTPS proxy dispatcher on the stored-credential refresh path before token renewal runs, so expired Codex OAuth profiles can refresh successfully in proxy-required environments instead of locking users out after the first token expiry.</li>
|
||||
<li>Plugins/memory-lancedb: bootstrap LanceDB into plugin runtime state on first use when the bundled npm install does not already have it, so <code>plugins.slots.memory="memory-lancedb"</code> works again after global npm installs without moving LanceDB into OpenClaw core dependencies. Fixes #26100.</li>
|
||||
<li>Config/plugins: treat stale unknown <code>plugins.allow</code> ids as warnings instead of fatal config errors, so recovery commands like <code>plugins install</code>, <code>doctor --fix</code>, and <code>status</code> still run when a plugin is missing locally. Fixes #52992. Thanks @vincentkoc.</li>
|
||||
<li>Doctor/WhatsApp: stop auto-enable from appending built-in channel ids like <code>whatsapp</code> to <code>plugins.allow</code>, so <code>openclaw doctor --fix</code> no longer writes schema-invalid plugin allowlist entries when repairing built-in channels. Fixes #52931. Thanks @vincentkoc.</li>
|
||||
<li>Telegram/auto-reply: preserve same-chat inbound debounce order without stranding stale busy-session followups, and keep same-key overflow turns ordered when tracked debounce keys are saturated. (#52998) Thanks @osolmaz.</li>
|
||||
<li>Discord/commands: return an explicit unauthorized reply for privileged native slash commands instead of falling through to Discord's misleading generic completion when auth gates reject the sender. Fixes #53041. Thanks @scoootscooob.</li>
|
||||
<li>Channels/catalog: let external channel catalogs override shipped fallback metadata and honor overridden npm specs during channel setup, so custom channel catalogs no longer fall back to bundled packages when a channel id matches. (#52988)</li>
|
||||
<li>Voice-call/Plivo: stabilize Plivo v2 replay keys so webhook retries and replay protection stop colliding on valid follow-up deliveries.</li>
|
||||
<li>Agents/skills: prefer the active resolved runtime snapshot for embedded skill config and env injection, so <code>skills.entries.<skill>.apiKey</code> SecretRefs resolve correctly during embedded startup instead of failing on raw source config. Fixes #53098. Thanks @vincentkoc.</li>
|
||||
<li>Agents/subagents: recheck timed-out worker waits against the latest runtime snapshot before sending completion events, so fast-finishing workers stop being reported as timed out when they actually succeeded. Fixes #53106. Thanks @vincentkoc.</li>
|
||||
<li>Agents/Anthropic: preserve latest assistant thinking and redacted-thinking block ordering during transcript image sanitization so follow-up turns do not trip Anthropic's unmodified-thinking validation. (#52961) Thanks @vincentkoc.</li>
|
||||
<li>Gateway/probe: stop successful gateway handshakes from timing out as unreachable while post-connect detail RPCs are still loading, so slow devices report a reachable RPC failure instead of a false negative dead gateway. Fixes #52927. Thanks @vincentkoc.</li>
|
||||
<li>Gateway/supervision: stop lock conflicts from crash-looping under launchd and systemd by keeping the duplicate process in a retry wait instead of exiting as a failure while another healthy gateway still owns the lock. Fixes #52922. Thanks @vincentkoc.</li>
|
||||
<li>Gateway/auth: require auth for canvas routes and admin scope for agent session reset, so anonymous canvas access and non-admin reset requests fail closed.</li>
|
||||
<li>Release/install: keep previously released bundled plugins and Control UI assets in published openclaw npm installs, and fail release checks when those shipped artifacts are missing. Thanks @vincentkoc.</li>
|
||||
<li>macOS app/chat UI: route browser proxy through the local node browser service, preserve plain-text paste semantics, strip completed assistant trace/debug wrapper noise from transcripts, refresh permission state after returning from System Settings, and tolerate malformed cron rows in the macOS tab. (#39516) Thanks @Imhermes1.</li>
|
||||
<li>Android/Play distribution: remove self-update, background location, <code>screen.record</code>, and background mic capture from the Android app, narrow the foreground service to <code>dataSync</code> only, and clean up the legacy <code>location.enabledMode=always</code> preference migration. (#39660) Thanks @obviyus.</li>
|
||||
<li>Telegram/DM routing: dedupe inbound Telegram DMs per agent instead of per session key so the same DM cannot trigger duplicate replies when both <code>agent:main:main</code> and <code>agent:main:telegram:direct:<id></code> resolve for one agent. Fixes #40005. Supersedes #40116. (#40519) thanks @obviyus.</li>
|
||||
<li>Cron/Telegram announce delivery: route text-only announce jobs through the real outbound adapters after finalizing descendant output so plain Telegram targets no longer report <code>delivered: true</code> when no message actually reached Telegram. (#40575) thanks @obviyus.</li>
|
||||
<li>Matrix/DM routing: add safer fallback detection for broken <code>m.direct</code> homeservers, honor explicit room bindings over DM classification, and preserve room-bound agent selection for Matrix DM rooms. (#19736) Thanks @derbronko.</li>
|
||||
<li>Feishu/plugin onboarding: clear the short-lived plugin discovery cache before reloading the registry after installing a channel plugin, so onboarding no longer re-prompts to download Feishu immediately after a successful install. Fixes #39642. (#39752) Thanks @GazeKingNuWu.</li>
|
||||
<li>Plugins/channel onboarding: prefer bundled channel plugins over duplicate npm-installed copies during onboarding and release-channel sync, preventing bundled plugins from being shadowed by npm installs with the same plugin ID. (#40092)</li>
|
||||
<li>Config/runtime snapshots: keep secrets-runtime-resolved config and auth-profile snapshots intact after config writes so follow-up reads still see file-backed secret values while picking up the persisted config update. (#37313) thanks @bbblending.</li>
|
||||
<li>Gateway/Control UI: resolve bundled dashboard assets through symlinked global wrappers and auto-detected package roots, while keeping configured and custom roots on the strict hardlink boundary. (#40385) Thanks @LarytheLord.</li>
|
||||
<li>Browser/extension relay: add <code>browser.relayBindHost</code> so the Chrome relay can bind to an explicit non-loopback address for WSL2 and other cross-namespace setups, while preserving loopback-only defaults. (#39364) Thanks @mvanhorn.</li>
|
||||
<li>Browser/CDP: normalize loopback direct WebSocket CDP URLs back to HTTP(S) for <code>/json/*</code> tab operations so local <code>ws://</code> / <code>wss://</code> profiles can still list, focus, open, and close tabs after the new direct-WS support lands. (#31085) Thanks @shrey150.</li>
|
||||
<li>Browser/CDP: rewrite wildcard <code>ws://0.0.0.0</code> and <code>ws://[::]</code> debugger URLs from remote <code>/json/version</code> responses back to the external CDP host/port, fixing Browserless-style container endpoints. (#17760) Thanks @joeharouni.</li>
|
||||
<li>Browser/extension relay: wait briefly for a previously attached Chrome tab to reappear after transient relay drops before failing with <code>tab not found</code>, reducing noisy reconnect flakes. (#32461) Thanks @AaronWander.</li>
|
||||
<li>macOS/Tailscale gateway discovery: keep Tailscale Serve probing alive when other remote gateways are already discovered, prefer direct transport for resolved <code>.ts.net</code> and Tailscale Serve gateways, and set <code>TERM=dumb</code> for GUI-launched Tailscale CLI discovery. (#40167) thanks @ngutman.</li>
|
||||
<li>TUI/theme: detect light terminal backgrounds via <code>COLORFGBG</code> and pick a WCAG AA-compliant light palette, with <code>OPENCLAW_THEME=light|dark</code> override for terminals without auto-detection. (#38636) Thanks @ademczuk and @vincentkoc.</li>
|
||||
<li>Agents/openai-codex: normalize <code>gpt-5.4</code> fallback transport back to <code>openai-codex-responses</code> on <code>chatgpt.com/backend-api</code> when config drifts to the generic OpenAI responses endpoint. (#38736) Thanks @0xsline.</li>
|
||||
<li>Models/openai-codex GPT-5.4 forward-compat: use the GPT-5.4 1,050,000-token context window and 128,000 max tokens for <code>openai-codex/gpt-5.4</code> instead of inheriting stale legacy Codex limits in resolver fallbacks and model listing. (#37876) thanks @yuweuii.</li>
|
||||
<li>Tools/web search: restore Perplexity OpenRouter/Sonar compatibility for legacy <code>OPENROUTER_API_KEY</code>, <code>sk-or-...</code>, and explicit <code>perplexity.baseUrl</code> / <code>model</code> setups while keeping direct Perplexity keys on the native Search API path. (#39937) Thanks @obviyus.</li>
|
||||
<li>Agents/failover: detect Amazon Bedrock <code>Too many tokens per day</code> quota errors as rate limits across fallback, cron retry, and memory embeddings while keeping context-window <code>too many tokens per request</code> errors out of the rate-limit lane. (#39377) Thanks @gambletan.</li>
|
||||
<li>Mattermost replies: keep <code>root_id</code> pinned to the existing thread root when an agent replies inside a thread, while still using reply-target threading for top-level posts. (#27744) thanks @hnykda.</li>
|
||||
<li>Telegram/DM partial streaming: keep DM preview lanes on real message edits instead of native draft materialization so final replies no longer flash a second duplicate copy before collapsing back to one.</li>
|
||||
<li>macOS overlays: fix VoiceWake, Talk, and Notify overlay exclusivity crashes by removing shared <code>inout</code> visibility mutation from <code>OverlayPanelFactory.present</code>, and add a repeated Talk overlay smoke test. (#39275, #39321) Thanks @fellanH.</li>
|
||||
<li>macOS Talk Mode: set the speech recognition request <code>taskHint</code> to <code>.dictation</code> for mic capture, and add regression coverage for the request defaults. (#38445) Thanks @dmiv.</li>
|
||||
<li>macOS release packaging: default <code>scripts/package-mac-app.sh</code> to universal binaries for <code>BUILD_CONFIG=release</code>, and clarify that <code>scripts/package-mac-dist.sh</code> already produces the release zip + DMG. (#33891) Thanks @cgdusek.</li>
|
||||
<li>Hooks/session-memory: keep <code>/new</code> and <code>/reset</code> memory artifacts in the bound agent workspace and align saved reset session keys with that workspace when stale main-agent keys leak into the hook path. (#39875) thanks @rbutera.</li>
|
||||
<li>Sessions/model switch: clear stale cached <code>contextTokens</code> when a session changes models so status and runtime paths recompute against the active model window. (#38044) thanks @yuweuii.</li>
|
||||
<li>ACP/session history: persist transcripts for successful ACP child runs, preserve exact transcript text, record ACP spawned-session lineage, and keep spawn-time transcript-path persistence best-effort so history storage failures do not block execution. (#40137) thanks @mbelinky.</li>
|
||||
<li>Docs/browser: add a layered WSL2 + Windows remote Chrome CDP troubleshooting guide, including Control UI origin pitfalls and extension-relay bind-address guidance. (#39407) Thanks @Owlock.</li>
|
||||
<li>Context engine registry/bundled builds: share the registry state through a <code>globalThis</code> singleton so duplicated bundled module copies can resolve engines registered by each other at runtime, with regression coverage for duplicate-module imports. (#40115) thanks @jalehman.</li>
|
||||
<li>Podman/setup: fix <code>cannot chdir: Permission denied</code> in <code>run_as_user</code> when <code>setup-podman.sh</code> is invoked from a directory the target user cannot access, by wrapping user-switch calls in a subshell that cd's to <code>/tmp</code> with <code>/</code> fallback. (#39435) Thanks @langdon and @jlcbk.</li>
|
||||
<li>Podman/SELinux: auto-detect SELinux enforcing/permissive mode and add <code>:Z</code> relabel to bind mounts in <code>run-openclaw-podman.sh</code> and the Quadlet template, fixing <code>EACCES</code> on Fedora/RHEL hosts. Supports <code>OPENCLAW_BIND_MOUNT_OPTIONS</code> override. (#39449) Thanks @langdon and @githubbzxs.</li>
|
||||
<li>Agents/context-engine plugins: bootstrap runtime plugins once at embedded-run, compaction, and subagent boundaries so plugin-provided context engines and hooks load from the active workspace before runtime resolution. (#40232)</li>
|
||||
<li>Docs/Changelog: correct the contributor credit for the bundled Control UI global-install fix to @LarytheLord. (#40420) Thanks @velvet-shark.</li>
|
||||
<li>Telegram/media downloads: time out only stalled body reads so polling recovers from hung file downloads without aborting slow downloads that are still streaming data. (#40098) thanks @tysoncung.</li>
|
||||
<li>Docker/runtime image: prune dev dependencies, strip build-only dist metadata for smaller Docker images. (#40307) Thanks @vincentkoc.</li>
|
||||
<li>Gateway/restart timeout recovery: exit non-zero when restart-triggered shutdown drains time out so launchd/systemd restart the gateway instead of treating the failed restart as a clean stop. Landed from contributor PR #40380 by @dsantoreis. Thanks @dsantoreis.</li>
|
||||
<li>Gateway/config restart guard: validate config before service start/restart and keep post-SIGUSR1 startup failures from crashing the gateway process, reducing invalid-config restart loops and macOS permission loss. Landed from contributor PR #38699 by @lml2468. Thanks @lml2468.</li>
|
||||
<li>Gateway/launchd respawn detection: treat <code>XPC_SERVICE_NAME</code> as a launchd supervision hint so macOS restarts exit cleanly under launchd instead of attempting detached self-respawn. Landed from contributor PR #20555 by @dimat. Thanks @dimat.</li>
|
||||
<li>Telegram/poll restart cleanup: abort the in-flight Telegram API fetch when shutdown or forced polling restarts stop a runner, preventing stale <code>getUpdates</code> long polls from colliding with the replacement runner. Landed from contributor PR #23950 by @Gkinthecodeland. Thanks @Gkinthecodeland.</li>
|
||||
<li>Cron/restart catch-up staggering: limit immediate missed-job replay on startup and reschedule the deferred remainder from the post-catchup clock so restart bursts do not starve the gateway or silently skip overdue recurring jobs. Landed from contributor PR #18925 by @rexlunae. Thanks @rexlunae.</li>
|
||||
<li>Cron/owner-only tools: pass trusted isolated cron runs into the embedded agent with owner context so <code>cron</code>/<code>gateway</code> tooling remains available after the owner-auth hardening narrowed direct-message ownership inference.</li>
|
||||
<li>Browser/SSRF: block private-network intermediate redirect hops in strict browser navigation flows and fail closed when remote tab-open paths cannot inspect redirect chains. Thanks @zpbrent.</li>
|
||||
<li>MS Teams/authz: keep <code>groupPolicy: "allowlist"</code> enforcing sender allowlists even when a team/channel route allowlist is configured, so route matches no longer widen group access to every sender in that route. Thanks @zpbrent.</li>
|
||||
<li>Security/system.run: bind approved <code>bun</code> and <code>deno run</code> script operands to on-disk file snapshots so post-approval script rewrites are denied before execution.</li>
|
||||
<li>Skills/download installs: pin the validated per-skill tools root before writing downloaded archives, so rebinding the lexical tools path cannot redirect download writes outside the intended tools directory. Thanks @tdjackey.</li>
|
||||
</ul>
|
||||
<p><a href="https://github.com/openclaw/openclaw/blob/main/CHANGELOG.md">View full changelog</a></p>
|
||||
]]></description>
|
||||
<enclosure url="https://github.com/openclaw/openclaw/releases/download/v2026.3.23/OpenClaw-2026.3.23.zip" length="24522883" type="application/octet-stream" sparkle:edSignature="ptBgHYLBqq/TSdONYCfIB5d6aP/ij/9G0gYQ5mJI9jf8Y31sbQIh5CqpJVxEEWLTMIGQKsHQir/kXZjtRvvZAg=="/>
|
||||
<enclosure url="https://github.com/openclaw/openclaw/releases/download/v2026.3.8-beta.1/OpenClaw-2026.3.8-beta.1.zip" length="23407015" type="application/octet-stream" sparkle:edSignature="KCqhSmu4b0tHf55RqcQOHorsc55CgBI5BUmK/NTizxNq04INn/7QvsamHYQou9DbB2IW6B2nawBC4nn4au5yDA=="/>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>
|
||||
</rss>
|
||||
@@ -65,8 +65,8 @@ android {
|
||||
applicationId = "ai.openclaw.app"
|
||||
minSdk = 31
|
||||
targetSdk = 36
|
||||
versionCode = 2026033000
|
||||
versionName = "2026.3.30"
|
||||
versionCode = 2026032000
|
||||
versionName = "2026.3.20"
|
||||
ndk {
|
||||
// Support all major ABIs — native libs are tiny (~47 KB per ABI)
|
||||
abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
|
||||
|
||||
@@ -31,13 +31,6 @@
|
||||
android:name="android.hardware.telephony"
|
||||
android:required="false" />
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<application
|
||||
android:name=".NodeApp"
|
||||
android:allowBackup="true"
|
||||
|
||||
@@ -56,17 +56,6 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
val gateways: StateFlow<List<GatewayEndpoint>> = runtimeState(initial = emptyList()) { it.gateways }
|
||||
val discoveryStatusText: StateFlow<String> = runtimeState(initial = "Searching…") { it.discoveryStatusText }
|
||||
val notificationForwardingEnabled: StateFlow<Boolean> = prefs.notificationForwardingEnabled
|
||||
val notificationForwardingMode: StateFlow<NotificationPackageFilterMode> =
|
||||
prefs.notificationForwardingMode
|
||||
val notificationForwardingPackages: StateFlow<Set<String>> = prefs.notificationForwardingPackages
|
||||
val notificationForwardingQuietHoursEnabled: StateFlow<Boolean> =
|
||||
prefs.notificationForwardingQuietHoursEnabled
|
||||
val notificationForwardingQuietStart: StateFlow<String> = prefs.notificationForwardingQuietStart
|
||||
val notificationForwardingQuietEnd: StateFlow<String> = prefs.notificationForwardingQuietEnd
|
||||
val notificationForwardingMaxEventsPerMinute: StateFlow<Int> =
|
||||
prefs.notificationForwardingMaxEventsPerMinute
|
||||
val notificationForwardingSessionKey: StateFlow<String?> = prefs.notificationForwardingSessionKey
|
||||
|
||||
val isConnected: StateFlow<Boolean> = runtimeState(initial = false) { it.isConnected }
|
||||
val isNodeConnected: StateFlow<Boolean> = runtimeState(initial = false) { it.nodeConnected }
|
||||
@@ -208,39 +197,6 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
|
||||
prefs.setCanvasDebugStatusEnabled(value)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingEnabled(value: Boolean) {
|
||||
ensureRuntime().setNotificationForwardingEnabled(value)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingMode(mode: NotificationPackageFilterMode) {
|
||||
ensureRuntime().setNotificationForwardingMode(mode)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingPackagesCsv(csv: String) {
|
||||
val packages =
|
||||
csv
|
||||
.split(',')
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
ensureRuntime().setNotificationForwardingPackages(packages)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingQuietHours(
|
||||
enabled: Boolean,
|
||||
start: String,
|
||||
end: String,
|
||||
): Boolean {
|
||||
return ensureRuntime().setNotificationForwardingQuietHours(enabled = enabled, start = start, end = end)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingMaxEventsPerMinute(value: Int) {
|
||||
ensureRuntime().setNotificationForwardingMaxEventsPerMinute(value)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingSessionKey(value: String?) {
|
||||
ensureRuntime().setNotificationForwardingSessionKey(value)
|
||||
}
|
||||
|
||||
fun setVoiceScreenActive(active: Boolean) {
|
||||
ensureRuntime().setVoiceScreenActive(active)
|
||||
}
|
||||
@@ -281,10 +237,6 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
|
||||
ensureRuntime().handleCanvasA2UIActionFromWebView(payloadJson)
|
||||
}
|
||||
|
||||
fun isTrustedCanvasActionUrl(rawUrl: String?): Boolean {
|
||||
return ensureRuntime().isTrustedCanvasActionUrl(rawUrl)
|
||||
}
|
||||
|
||||
fun requestCanvasRehydrate(source: String = "screen_tab") {
|
||||
ensureRuntime().requestCanvasRehydrate(source = source, force = true)
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import ai.openclaw.app.voice.TalkModeManager
|
||||
import ai.openclaw.app.voice.VoiceConversationEntry
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -33,6 +34,7 @@ import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
@@ -139,7 +141,6 @@ class NodeRuntime(
|
||||
motionPedometerAvailable = { motionHandler.isPedometerAvailable() },
|
||||
sendSmsAvailable = { BuildConfig.OPENCLAW_ENABLE_SMS && sms.canSendSms() },
|
||||
readSmsAvailable = { BuildConfig.OPENCLAW_ENABLE_SMS && sms.canReadSms() },
|
||||
smsSearchPossible = { BuildConfig.OPENCLAW_ENABLE_SMS && sms.hasTelephonyFeature() },
|
||||
callLogAvailable = { BuildConfig.OPENCLAW_ENABLE_CALL_LOG },
|
||||
hasRecordAudioPermission = { hasRecordAudioPermission() },
|
||||
manualTls = { manualTls.value },
|
||||
@@ -165,8 +166,6 @@ class NodeRuntime(
|
||||
locationEnabled = { locationMode.value != LocationMode.Off },
|
||||
sendSmsAvailable = { BuildConfig.OPENCLAW_ENABLE_SMS && sms.canSendSms() },
|
||||
readSmsAvailable = { BuildConfig.OPENCLAW_ENABLE_SMS && sms.canReadSms() },
|
||||
smsFeatureEnabled = { BuildConfig.OPENCLAW_ENABLE_SMS },
|
||||
smsTelephonyAvailable = { sms.hasTelephonyFeature() },
|
||||
callLogAvailable = { BuildConfig.OPENCLAW_ENABLE_CALL_LOG },
|
||||
debugBuild = { BuildConfig.DEBUG },
|
||||
refreshNodeCanvasCapability = { nodeSession.refreshNodeCanvasCapability() },
|
||||
@@ -196,12 +195,7 @@ class NodeRuntime(
|
||||
private val _pendingGatewayTrust = MutableStateFlow<GatewayTrustPrompt?>(null)
|
||||
val pendingGatewayTrust: StateFlow<GatewayTrustPrompt?> = _pendingGatewayTrust.asStateFlow()
|
||||
|
||||
private fun resolveNodeMainSessionKey(agentId: String? = gatewayDefaultAgentId): String {
|
||||
val deviceId = identityStore.loadOrCreate().deviceId
|
||||
return buildNodeMainSessionKey(deviceId, agentId)
|
||||
}
|
||||
|
||||
private val _mainSessionKey = MutableStateFlow(resolveNodeMainSessionKey())
|
||||
private val _mainSessionKey = MutableStateFlow("main")
|
||||
val mainSessionKey: StateFlow<String> = _mainSessionKey.asStateFlow()
|
||||
|
||||
private val cameraHudSeq = AtomicLong(0)
|
||||
@@ -249,7 +243,7 @@ class NodeRuntime(
|
||||
_serverName.value = name
|
||||
_remoteAddress.value = remote
|
||||
_seamColorArgb.value = DEFAULT_SEAM_COLOR_ARGB
|
||||
syncMainSessionKey(resolveAgentIdFromMainSessionKey(mainSessionKey))
|
||||
applyMainSessionKey(mainSessionKey)
|
||||
updateStatus()
|
||||
micCapture.onGatewayConnectionChanged(true)
|
||||
scope.launch {
|
||||
@@ -265,6 +259,9 @@ class NodeRuntime(
|
||||
_serverName.value = null
|
||||
_remoteAddress.value = null
|
||||
_seamColorArgb.value = DEFAULT_SEAM_COLOR_ARGB
|
||||
if (!isCanonicalMainSessionKey(_mainSessionKey.value)) {
|
||||
_mainSessionKey.value = "main"
|
||||
}
|
||||
chat.applyMainSessionKey(resolveMainSessionKey())
|
||||
chat.onDisconnected(message)
|
||||
updateStatus()
|
||||
@@ -323,11 +320,9 @@ class NodeRuntime(
|
||||
session = operatorSession,
|
||||
json = json,
|
||||
supportsChatSubscribe = false,
|
||||
).also {
|
||||
it.applyMainSessionKey(_mainSessionKey.value)
|
||||
}
|
||||
)
|
||||
private val voiceReplySpeakerLazy: Lazy<TalkModeManager> = lazy {
|
||||
// Reuse the existing TalkMode speech engine for native Android TTS playback
|
||||
// Reuse the existing TalkMode speech engine (ElevenLabs + deterministic system-TTS fallback)
|
||||
// without enabling the legacy talk capture loop.
|
||||
TalkModeManager(
|
||||
context = appContext,
|
||||
@@ -409,12 +404,13 @@ class NodeRuntime(
|
||||
)
|
||||
}
|
||||
|
||||
private fun syncMainSessionKey(agentId: String?) {
|
||||
val resolvedKey = resolveNodeMainSessionKey(agentId)
|
||||
if (_mainSessionKey.value == resolvedKey) return
|
||||
_mainSessionKey.value = resolvedKey
|
||||
talkMode.setMainSessionKey(resolvedKey)
|
||||
chat.applyMainSessionKey(resolvedKey)
|
||||
private fun applyMainSessionKey(candidate: String?) {
|
||||
val trimmed = normalizeMainKey(candidate) ?: return
|
||||
if (isCanonicalMainSessionKey(_mainSessionKey.value)) return
|
||||
if (_mainSessionKey.value == trimmed) return
|
||||
_mainSessionKey.value = trimmed
|
||||
talkMode.setMainSessionKey(trimmed)
|
||||
chat.applyMainSessionKey(trimmed)
|
||||
updateHomeCanvasState()
|
||||
}
|
||||
|
||||
@@ -537,17 +533,6 @@ class NodeRuntime(
|
||||
fun setOnboardingCompleted(value: Boolean) = prefs.setOnboardingCompleted(value)
|
||||
val lastDiscoveredStableId: StateFlow<String> = prefs.lastDiscoveredStableId
|
||||
val canvasDebugStatusEnabled: StateFlow<Boolean> = prefs.canvasDebugStatusEnabled
|
||||
val notificationForwardingEnabled: StateFlow<Boolean> = prefs.notificationForwardingEnabled
|
||||
val notificationForwardingMode: StateFlow<NotificationPackageFilterMode> =
|
||||
prefs.notificationForwardingMode
|
||||
val notificationForwardingPackages: StateFlow<Set<String>> = prefs.notificationForwardingPackages
|
||||
val notificationForwardingQuietHoursEnabled: StateFlow<Boolean> =
|
||||
prefs.notificationForwardingQuietHoursEnabled
|
||||
val notificationForwardingQuietStart: StateFlow<String> = prefs.notificationForwardingQuietStart
|
||||
val notificationForwardingQuietEnd: StateFlow<String> = prefs.notificationForwardingQuietEnd
|
||||
val notificationForwardingMaxEventsPerMinute: StateFlow<Int> =
|
||||
prefs.notificationForwardingMaxEventsPerMinute
|
||||
val notificationForwardingSessionKey: StateFlow<String?> = prefs.notificationForwardingSessionKey
|
||||
|
||||
private var didAutoConnect = false
|
||||
|
||||
@@ -700,34 +685,6 @@ class NodeRuntime(
|
||||
prefs.setCanvasDebugStatusEnabled(value)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingEnabled(value: Boolean) {
|
||||
prefs.setNotificationForwardingEnabled(value)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingMode(mode: NotificationPackageFilterMode) {
|
||||
prefs.setNotificationForwardingMode(mode)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingPackages(packages: List<String>) {
|
||||
prefs.setNotificationForwardingPackages(packages)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingQuietHours(
|
||||
enabled: Boolean,
|
||||
start: String,
|
||||
end: String,
|
||||
): Boolean {
|
||||
return prefs.setNotificationForwardingQuietHours(enabled = enabled, start = start, end = end)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingMaxEventsPerMinute(value: Int) {
|
||||
prefs.setNotificationForwardingMaxEventsPerMinute(value)
|
||||
}
|
||||
|
||||
fun setNotificationForwardingSessionKey(value: String?) {
|
||||
prefs.setNotificationForwardingSessionKey(value)
|
||||
}
|
||||
|
||||
fun setVoiceScreenActive(active: Boolean) {
|
||||
if (!active) {
|
||||
stopActiveVoiceSession()
|
||||
@@ -947,10 +904,6 @@ class NodeRuntime(
|
||||
}
|
||||
}
|
||||
|
||||
fun isTrustedCanvasActionUrl(rawUrl: String?): Boolean {
|
||||
return a2uiHandler.isTrustedCanvasActionUrl(rawUrl)
|
||||
}
|
||||
|
||||
fun loadChat(sessionKey: String) {
|
||||
val key = sessionKey.trim().ifEmpty { resolveMainSessionKey() }
|
||||
chat.load(key)
|
||||
@@ -1003,7 +956,9 @@ class NodeRuntime(
|
||||
val config = root?.get("config").asObjectOrNull()
|
||||
val ui = config?.get("ui").asObjectOrNull()
|
||||
val raw = ui?.get("seamColor").asStringOrNull()?.trim()
|
||||
syncMainSessionKey(gatewayDefaultAgentId)
|
||||
val sessionCfg = config?.get("session").asObjectOrNull()
|
||||
val mainKey = normalizeMainKey(sessionCfg?.get("mainKey").asStringOrNull())
|
||||
applyMainSessionKey(mainKey)
|
||||
|
||||
val parsed = parseHexColorArgb(raw)
|
||||
_seamColorArgb.value = parsed ?: DEFAULT_SEAM_COLOR_ARGB
|
||||
@@ -1036,7 +991,7 @@ class NodeRuntime(
|
||||
|
||||
gatewayDefaultAgentId = defaultAgentId.ifEmpty { null }
|
||||
gatewayAgents = agents
|
||||
syncMainSessionKey(resolveAgentIdFromMainSessionKey(mainKey) ?: gatewayDefaultAgentId)
|
||||
applyMainSessionKey(mainKey)
|
||||
updateHomeCanvasState()
|
||||
} catch (_: Throwable) {
|
||||
// ignore
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
package ai.openclaw.app
|
||||
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
|
||||
enum class NotificationPackageFilterMode(val rawValue: String) {
|
||||
Allowlist("allowlist"),
|
||||
Blocklist("blocklist"),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun fromRawValue(raw: String?): NotificationPackageFilterMode {
|
||||
return entries.firstOrNull { it.rawValue == raw?.trim()?.lowercase() } ?: Blocklist
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class NotificationForwardingPolicy(
|
||||
val enabled: Boolean,
|
||||
val mode: NotificationPackageFilterMode,
|
||||
val packages: Set<String>,
|
||||
val quietHoursEnabled: Boolean,
|
||||
val quietStart: String,
|
||||
val quietEnd: String,
|
||||
val maxEventsPerMinute: Int,
|
||||
val sessionKey: String?,
|
||||
)
|
||||
|
||||
internal fun NotificationForwardingPolicy.allowsPackage(packageName: String): Boolean {
|
||||
val normalized = packageName.trim()
|
||||
if (normalized.isEmpty()) {
|
||||
return false
|
||||
}
|
||||
return when (mode) {
|
||||
NotificationPackageFilterMode.Allowlist -> packages.contains(normalized)
|
||||
NotificationPackageFilterMode.Blocklist -> !packages.contains(normalized)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun NotificationForwardingPolicy.isWithinQuietHours(
|
||||
nowEpochMs: Long,
|
||||
zoneId: ZoneId = ZoneId.systemDefault(),
|
||||
): Boolean {
|
||||
if (!quietHoursEnabled) {
|
||||
return false
|
||||
}
|
||||
val startMinutes = parseLocalHourMinute(quietStart) ?: return false
|
||||
val endMinutes = parseLocalHourMinute(quietEnd) ?: return false
|
||||
if (startMinutes == endMinutes) {
|
||||
return true
|
||||
}
|
||||
val now =
|
||||
Instant.ofEpochMilli(nowEpochMs)
|
||||
.atZone(zoneId)
|
||||
.toLocalTime()
|
||||
val nowMinutes = now.hour * 60 + now.minute
|
||||
return if (startMinutes < endMinutes) {
|
||||
nowMinutes in startMinutes until endMinutes
|
||||
} else {
|
||||
nowMinutes >= startMinutes || nowMinutes < endMinutes
|
||||
}
|
||||
}
|
||||
|
||||
private val localHourMinuteRegex = Regex("""^([01]\d|2[0-3]):([0-5]\d)$""")
|
||||
|
||||
internal fun normalizeLocalHourMinute(raw: String): String? {
|
||||
val trimmed = raw.trim()
|
||||
val match = localHourMinuteRegex.matchEntire(trimmed) ?: return null
|
||||
return "${match.groupValues[1]}:${match.groupValues[2]}"
|
||||
}
|
||||
|
||||
internal fun parseLocalHourMinute(raw: String): Int? {
|
||||
val normalized = normalizeLocalHourMinute(raw) ?: return null
|
||||
val parts = normalized.split(':')
|
||||
val hour = parts[0].toInt()
|
||||
val minute = parts[1].toInt()
|
||||
return hour * 60 + minute
|
||||
}
|
||||
|
||||
internal class NotificationBurstLimiter {
|
||||
private val lock = Any()
|
||||
private var windowStartMs: Long = -1L
|
||||
private var eventsInWindow: Int = 0
|
||||
|
||||
fun allow(nowEpochMs: Long, maxEventsPerMinute: Int): Boolean {
|
||||
if (maxEventsPerMinute <= 0) {
|
||||
return false
|
||||
}
|
||||
val currentWindow = nowEpochMs - (nowEpochMs % 60_000L)
|
||||
synchronized(lock) {
|
||||
if (currentWindow != windowStartMs) {
|
||||
windowStartMs = currentWindow
|
||||
eventsInWindow = 0
|
||||
}
|
||||
if (eventsInWindow >= maxEventsPerMinute) {
|
||||
return false
|
||||
}
|
||||
eventsInWindow += 1
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,6 @@ import android.content.pm.PackageManager
|
||||
import android.content.Intent
|
||||
import android.Manifest
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.Settings
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.activity.ComponentActivity
|
||||
@@ -13,21 +11,17 @@ import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.app.ActivityCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import kotlin.coroutines.resume
|
||||
|
||||
class PermissionRequester(private val activity: ComponentActivity) {
|
||||
private val mutex = Mutex()
|
||||
private var pending: CompletableDeferred<Map<String, Boolean>>? = null
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
private val launcher: ActivityResultLauncher<Array<String>> =
|
||||
activity.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
|
||||
@@ -92,84 +86,32 @@ class PermissionRequester(private val activity: ComponentActivity) {
|
||||
|
||||
private suspend fun showRationaleDialog(permissions: List<String>): Boolean =
|
||||
withContext(Dispatchers.Main) {
|
||||
if (activity.isFinishing || activity.isDestroyed) {
|
||||
return@withContext false
|
||||
}
|
||||
suspendCancellableCoroutine { cont ->
|
||||
val lifecycle = activity.lifecycle
|
||||
var dialog: AlertDialog? = null
|
||||
var observer: LifecycleEventObserver? = null
|
||||
val finished = AtomicBoolean(false)
|
||||
val removeObserver = {
|
||||
observer?.let(lifecycle::removeObserver)
|
||||
observer = null
|
||||
}
|
||||
fun finish(result: Boolean?) {
|
||||
if (!finished.compareAndSet(false, true)) return
|
||||
removeObserver()
|
||||
dialog?.dismiss()
|
||||
if (result != null) {
|
||||
cont.resume(result)
|
||||
}
|
||||
}
|
||||
val actualObserver =
|
||||
LifecycleEventObserver { _, event ->
|
||||
if (event != Lifecycle.Event.ON_DESTROY) return@LifecycleEventObserver
|
||||
finish(false)
|
||||
}
|
||||
observer = actualObserver
|
||||
lifecycle.addObserver(actualObserver)
|
||||
cont.invokeOnCancellation {
|
||||
mainHandler.post {
|
||||
finish(null)
|
||||
}
|
||||
}
|
||||
dialog =
|
||||
AlertDialog.Builder(activity)
|
||||
.setTitle("Permission required")
|
||||
.setMessage(buildRationaleMessage(permissions))
|
||||
.setPositiveButton("Continue") { _, _ -> finish(true) }
|
||||
.setNegativeButton("Not now") { _, _ -> finish(false) }
|
||||
.setOnCancelListener { finish(false) }
|
||||
.show()
|
||||
AlertDialog.Builder(activity)
|
||||
.setTitle("Permission required")
|
||||
.setMessage(buildRationaleMessage(permissions))
|
||||
.setPositiveButton("Continue") { _, _ -> cont.resume(true) }
|
||||
.setNegativeButton("Not now") { _, _ -> cont.resume(false) }
|
||||
.setOnCancelListener { cont.resume(false) }
|
||||
.show()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun showSettingsDialog(permissions: List<String>) =
|
||||
withContext(Dispatchers.Main) {
|
||||
if (activity.isFinishing || activity.isDestroyed) return@withContext
|
||||
val lifecycle = activity.lifecycle
|
||||
var dialog: AlertDialog? = null
|
||||
var observer: LifecycleEventObserver? = null
|
||||
val removeObserver = {
|
||||
observer?.let(lifecycle::removeObserver)
|
||||
observer = null
|
||||
private fun showSettingsDialog(permissions: List<String>) {
|
||||
AlertDialog.Builder(activity)
|
||||
.setTitle("Enable permission in Settings")
|
||||
.setMessage(buildSettingsMessage(permissions))
|
||||
.setPositiveButton("Open Settings") { _, _ ->
|
||||
val intent =
|
||||
Intent(
|
||||
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Uri.fromParts("package", activity.packageName, null),
|
||||
)
|
||||
activity.startActivity(intent)
|
||||
}
|
||||
val actualObserver =
|
||||
LifecycleEventObserver { _, event ->
|
||||
if (event != Lifecycle.Event.ON_DESTROY) return@LifecycleEventObserver
|
||||
removeObserver()
|
||||
dialog?.dismiss()
|
||||
}
|
||||
observer = actualObserver
|
||||
lifecycle.addObserver(actualObserver)
|
||||
dialog =
|
||||
AlertDialog.Builder(activity)
|
||||
.setTitle("Enable permission in Settings")
|
||||
.setMessage(buildSettingsMessage(permissions))
|
||||
.setPositiveButton("Open Settings") { _, _ ->
|
||||
if (activity.isFinishing || activity.isDestroyed) return@setPositiveButton
|
||||
val intent =
|
||||
Intent(
|
||||
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Uri.fromParts("package", activity.packageName, null),
|
||||
)
|
||||
activity.startActivity(intent)
|
||||
}
|
||||
.setNegativeButton("Cancel", null)
|
||||
.setOnDismissListener { removeObserver() }
|
||||
.show()
|
||||
}
|
||||
.setNegativeButton("Cancel", null)
|
||||
.show()
|
||||
}
|
||||
|
||||
private fun buildRationaleMessage(permissions: List<String>): String {
|
||||
val labels = permissions.map { permissionLabel(it) }
|
||||
@@ -185,16 +127,7 @@ class PermissionRequester(private val activity: ComponentActivity) {
|
||||
when (permission) {
|
||||
Manifest.permission.CAMERA -> "Camera"
|
||||
Manifest.permission.RECORD_AUDIO -> "Microphone"
|
||||
Manifest.permission.SEND_SMS -> "Send SMS"
|
||||
Manifest.permission.READ_SMS -> "Read SMS"
|
||||
Manifest.permission.READ_CONTACTS -> "Read Contacts"
|
||||
Manifest.permission.WRITE_CONTACTS -> "Write Contacts"
|
||||
Manifest.permission.READ_CALENDAR -> "Read Calendar"
|
||||
Manifest.permission.WRITE_CALENDAR -> "Write Calendar"
|
||||
Manifest.permission.READ_CALL_LOG -> "Read Call Log"
|
||||
Manifest.permission.ACTIVITY_RECOGNITION -> "Motion Activity"
|
||||
Manifest.permission.READ_MEDIA_IMAGES -> "Photos"
|
||||
Manifest.permission.READ_EXTERNAL_STORAGE -> "Photos"
|
||||
Manifest.permission.SEND_SMS -> "SMS"
|
||||
else -> permission
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,17 +26,6 @@ class SecurePrefs(
|
||||
private const val voiceWakeModeKey = "voiceWake.mode"
|
||||
private const val plainPrefsName = "openclaw.node"
|
||||
private const val securePrefsName = "openclaw.node.secure"
|
||||
private const val notificationsForwardingEnabledKey = "notifications.forwarding.enabled"
|
||||
private const val defaultNotificationForwardingEnabled = false
|
||||
private const val notificationsForwardingModeKey = "notifications.forwarding.mode"
|
||||
private const val notificationsForwardingPackagesKey = "notifications.forwarding.packages"
|
||||
private const val notificationsForwardingQuietHoursEnabledKey =
|
||||
"notifications.forwarding.quietHoursEnabled"
|
||||
private const val notificationsForwardingQuietStartKey = "notifications.forwarding.quietStart"
|
||||
private const val notificationsForwardingQuietEndKey = "notifications.forwarding.quietEnd"
|
||||
private const val notificationsForwardingMaxEventsPerMinuteKey =
|
||||
"notifications.forwarding.maxEventsPerMinute"
|
||||
private const val notificationsForwardingSessionKeyKey = "notifications.forwarding.sessionKey"
|
||||
}
|
||||
|
||||
private val appContext = context.applicationContext
|
||||
@@ -107,55 +96,6 @@ class SecurePrefs(
|
||||
MutableStateFlow(plainPrefs.getBoolean("canvas.debugStatusEnabled", false))
|
||||
val canvasDebugStatusEnabled: StateFlow<Boolean> = _canvasDebugStatusEnabled
|
||||
|
||||
private val _notificationForwardingEnabled =
|
||||
MutableStateFlow(plainPrefs.getBoolean(notificationsForwardingEnabledKey, defaultNotificationForwardingEnabled))
|
||||
val notificationForwardingEnabled: StateFlow<Boolean> = _notificationForwardingEnabled
|
||||
|
||||
private val _notificationForwardingMode =
|
||||
MutableStateFlow(
|
||||
NotificationPackageFilterMode.fromRawValue(
|
||||
plainPrefs.getString(notificationsForwardingModeKey, null),
|
||||
),
|
||||
)
|
||||
val notificationForwardingMode: StateFlow<NotificationPackageFilterMode> = _notificationForwardingMode
|
||||
|
||||
private val _notificationForwardingPackages = MutableStateFlow(loadNotificationForwardingPackages())
|
||||
val notificationForwardingPackages: StateFlow<Set<String>> = _notificationForwardingPackages
|
||||
|
||||
private val storedQuietStart =
|
||||
normalizeLocalHourMinute(plainPrefs.getString(notificationsForwardingQuietStartKey, "22:00").orEmpty())
|
||||
?: "22:00"
|
||||
private val storedQuietEnd =
|
||||
normalizeLocalHourMinute(plainPrefs.getString(notificationsForwardingQuietEndKey, "07:00").orEmpty())
|
||||
?: "07:00"
|
||||
private val storedQuietHoursEnabled =
|
||||
plainPrefs.getBoolean(notificationsForwardingQuietHoursEnabledKey, false) &&
|
||||
normalizeLocalHourMinute(plainPrefs.getString(notificationsForwardingQuietStartKey, "22:00").orEmpty()) != null &&
|
||||
normalizeLocalHourMinute(plainPrefs.getString(notificationsForwardingQuietEndKey, "07:00").orEmpty()) != null
|
||||
|
||||
private val _notificationForwardingQuietHoursEnabled =
|
||||
MutableStateFlow(storedQuietHoursEnabled)
|
||||
val notificationForwardingQuietHoursEnabled: StateFlow<Boolean> = _notificationForwardingQuietHoursEnabled
|
||||
|
||||
private val _notificationForwardingQuietStart = MutableStateFlow(storedQuietStart)
|
||||
val notificationForwardingQuietStart: StateFlow<String> = _notificationForwardingQuietStart
|
||||
|
||||
private val _notificationForwardingQuietEnd = MutableStateFlow(storedQuietEnd)
|
||||
val notificationForwardingQuietEnd: StateFlow<String> = _notificationForwardingQuietEnd
|
||||
|
||||
private val _notificationForwardingMaxEventsPerMinute =
|
||||
MutableStateFlow(plainPrefs.getInt(notificationsForwardingMaxEventsPerMinuteKey, 20).coerceAtLeast(1))
|
||||
val notificationForwardingMaxEventsPerMinute: StateFlow<Int> = _notificationForwardingMaxEventsPerMinute
|
||||
|
||||
private val _notificationForwardingSessionKey =
|
||||
MutableStateFlow(
|
||||
plainPrefs
|
||||
.getString(notificationsForwardingSessionKeyKey, "")
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() },
|
||||
)
|
||||
val notificationForwardingSessionKey: StateFlow<String?> = _notificationForwardingSessionKey
|
||||
|
||||
private val _wakeWords = MutableStateFlow(loadWakeWords())
|
||||
val wakeWords: StateFlow<List<String>> = _wakeWords
|
||||
|
||||
@@ -245,114 +185,6 @@ class SecurePrefs(
|
||||
_canvasDebugStatusEnabled.value = value
|
||||
}
|
||||
|
||||
internal fun getNotificationForwardingPolicy(appPackageName: String): NotificationForwardingPolicy {
|
||||
val modeRaw = plainPrefs.getString(notificationsForwardingModeKey, null)
|
||||
val mode = NotificationPackageFilterMode.fromRawValue(modeRaw)
|
||||
|
||||
val configuredPackages = loadNotificationForwardingPackages()
|
||||
val normalizedAppPackage = appPackageName.trim()
|
||||
val defaultBlockedPackages =
|
||||
if (normalizedAppPackage.isNotEmpty()) setOf(normalizedAppPackage) else emptySet()
|
||||
|
||||
val packages =
|
||||
when (mode) {
|
||||
NotificationPackageFilterMode.Allowlist -> configuredPackages
|
||||
NotificationPackageFilterMode.Blocklist -> configuredPackages + defaultBlockedPackages
|
||||
}
|
||||
|
||||
val maxEvents = plainPrefs.getInt(notificationsForwardingMaxEventsPerMinuteKey, 20)
|
||||
val quietStart =
|
||||
normalizeLocalHourMinute(plainPrefs.getString(notificationsForwardingQuietStartKey, "22:00").orEmpty())
|
||||
?: "22:00"
|
||||
val quietEnd =
|
||||
normalizeLocalHourMinute(plainPrefs.getString(notificationsForwardingQuietEndKey, "07:00").orEmpty())
|
||||
?: "07:00"
|
||||
val sessionKey =
|
||||
plainPrefs
|
||||
.getString(notificationsForwardingSessionKeyKey, "")
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
|
||||
val quietHoursEnabled =
|
||||
plainPrefs.getBoolean(notificationsForwardingQuietHoursEnabledKey, false) &&
|
||||
normalizeLocalHourMinute(plainPrefs.getString(notificationsForwardingQuietStartKey, "22:00").orEmpty()) != null &&
|
||||
normalizeLocalHourMinute(plainPrefs.getString(notificationsForwardingQuietEndKey, "07:00").orEmpty()) != null
|
||||
|
||||
return NotificationForwardingPolicy(
|
||||
enabled = plainPrefs.getBoolean(notificationsForwardingEnabledKey, defaultNotificationForwardingEnabled),
|
||||
mode = mode,
|
||||
packages = packages,
|
||||
quietHoursEnabled = quietHoursEnabled,
|
||||
quietStart = quietStart,
|
||||
quietEnd = quietEnd,
|
||||
maxEventsPerMinute = maxEvents.coerceAtLeast(1),
|
||||
sessionKey = sessionKey,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun setNotificationForwardingEnabled(value: Boolean) {
|
||||
plainPrefs.edit { putBoolean(notificationsForwardingEnabledKey, value) }
|
||||
_notificationForwardingEnabled.value = value
|
||||
}
|
||||
|
||||
internal fun setNotificationForwardingMode(mode: NotificationPackageFilterMode) {
|
||||
plainPrefs.edit { putString(notificationsForwardingModeKey, mode.rawValue) }
|
||||
_notificationForwardingMode.value = mode
|
||||
}
|
||||
|
||||
internal fun setNotificationForwardingPackages(packages: List<String>) {
|
||||
val sanitized =
|
||||
packages
|
||||
.asSequence()
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.toSet()
|
||||
.toList()
|
||||
.sorted()
|
||||
val encoded = JsonArray(sanitized.map { JsonPrimitive(it) }).toString()
|
||||
plainPrefs.edit { putString(notificationsForwardingPackagesKey, encoded) }
|
||||
_notificationForwardingPackages.value = sanitized.toSet()
|
||||
}
|
||||
|
||||
internal fun setNotificationForwardingQuietHours(
|
||||
enabled: Boolean,
|
||||
start: String,
|
||||
end: String,
|
||||
): Boolean {
|
||||
if (!enabled) {
|
||||
plainPrefs.edit { putBoolean(notificationsForwardingQuietHoursEnabledKey, false) }
|
||||
_notificationForwardingQuietHoursEnabled.value = false
|
||||
return true
|
||||
}
|
||||
val normalizedStart = normalizeLocalHourMinute(start) ?: return false
|
||||
val normalizedEnd = normalizeLocalHourMinute(end) ?: return false
|
||||
plainPrefs.edit {
|
||||
putBoolean(notificationsForwardingQuietHoursEnabledKey, enabled)
|
||||
putString(notificationsForwardingQuietStartKey, normalizedStart)
|
||||
putString(notificationsForwardingQuietEndKey, normalizedEnd)
|
||||
}
|
||||
_notificationForwardingQuietHoursEnabled.value = enabled
|
||||
_notificationForwardingQuietStart.value = normalizedStart
|
||||
_notificationForwardingQuietEnd.value = normalizedEnd
|
||||
return true
|
||||
}
|
||||
|
||||
internal fun setNotificationForwardingMaxEventsPerMinute(value: Int) {
|
||||
val normalized = value.coerceAtLeast(1)
|
||||
plainPrefs.edit {
|
||||
putInt(notificationsForwardingMaxEventsPerMinuteKey, normalized)
|
||||
}
|
||||
_notificationForwardingMaxEventsPerMinute.value = normalized
|
||||
}
|
||||
|
||||
internal fun setNotificationForwardingSessionKey(value: String?) {
|
||||
val normalized = value?.trim()?.takeIf { it.isNotEmpty() }
|
||||
plainPrefs.edit {
|
||||
putString(notificationsForwardingSessionKeyKey, normalized.orEmpty())
|
||||
}
|
||||
_notificationForwardingSessionKey.value = normalized
|
||||
}
|
||||
|
||||
fun loadGatewayToken(): String? {
|
||||
val manual =
|
||||
_gatewayToken.value.trim().ifEmpty {
|
||||
@@ -476,28 +308,6 @@ class SecurePrefs(
|
||||
_speakerEnabled.value = value
|
||||
}
|
||||
|
||||
private fun loadNotificationForwardingPackages(): Set<String> {
|
||||
val raw = plainPrefs.getString(notificationsForwardingPackagesKey, null)?.trim()
|
||||
if (raw.isNullOrEmpty()) {
|
||||
return emptySet()
|
||||
}
|
||||
return try {
|
||||
val element = json.parseToJsonElement(raw)
|
||||
val array = element as? JsonArray ?: return emptySet()
|
||||
array
|
||||
.mapNotNull { item ->
|
||||
when (item) {
|
||||
is JsonNull -> null
|
||||
is JsonPrimitive -> item.content.trim().takeIf { it.isNotEmpty() }
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
.toSet()
|
||||
} catch (_: Throwable) {
|
||||
emptySet()
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadVoiceWakeMode(): VoiceWakeMode {
|
||||
val raw = plainPrefs.getString(voiceWakeModeKey, null)
|
||||
val resolved = VoiceWakeMode.fromRawValue(raw)
|
||||
|
||||
@@ -11,14 +11,3 @@ internal fun isCanonicalMainSessionKey(raw: String?): Boolean {
|
||||
if (trimmed == "global") return true
|
||||
return trimmed.startsWith("agent:")
|
||||
}
|
||||
|
||||
internal fun resolveAgentIdFromMainSessionKey(raw: String?): String? {
|
||||
val trimmed = raw?.trim().orEmpty()
|
||||
if (!trimmed.startsWith("agent:")) return null
|
||||
return trimmed.removePrefix("agent:").substringBefore(':').trim().ifEmpty { null }
|
||||
}
|
||||
|
||||
internal fun buildNodeMainSessionKey(deviceId: String, agentId: String?): String {
|
||||
val resolvedAgentId = agentId?.trim().orEmpty().ifEmpty { "main" }
|
||||
return "agent:$resolvedAgentId:node-${deviceId.take(12)}"
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ class ChatController(
|
||||
private val json: Json,
|
||||
private val supportsChatSubscribe: Boolean,
|
||||
) {
|
||||
private var appliedMainSessionKey = "main"
|
||||
private val _sessionKey = MutableStateFlow("main")
|
||||
val sessionKey: StateFlow<String> = _sessionKey.asStateFlow()
|
||||
|
||||
@@ -74,7 +73,7 @@ class ChatController(
|
||||
}
|
||||
|
||||
fun load(sessionKey: String) {
|
||||
val key = normalizeRequestedSessionKey(sessionKey)
|
||||
val key = sessionKey.trim().ifEmpty { "main" }
|
||||
_sessionKey.value = key
|
||||
scope.launch { bootstrap(forceHealth = true, refreshSessions = true) }
|
||||
}
|
||||
@@ -82,15 +81,9 @@ class ChatController(
|
||||
fun applyMainSessionKey(mainSessionKey: String) {
|
||||
val trimmed = mainSessionKey.trim()
|
||||
if (trimmed.isEmpty()) return
|
||||
val nextState =
|
||||
applyMainSessionKey(
|
||||
currentSessionKey = normalizeRequestedSessionKey(_sessionKey.value),
|
||||
appliedMainSessionKey = appliedMainSessionKey,
|
||||
nextMainSessionKey = trimmed,
|
||||
)
|
||||
appliedMainSessionKey = nextState.appliedMainSessionKey
|
||||
if (_sessionKey.value == nextState.currentSessionKey) return
|
||||
_sessionKey.value = nextState.currentSessionKey
|
||||
if (_sessionKey.value == trimmed) return
|
||||
if (_sessionKey.value != "main") return
|
||||
_sessionKey.value = trimmed
|
||||
scope.launch { bootstrap(forceHealth = true, refreshSessions = true) }
|
||||
}
|
||||
|
||||
@@ -109,7 +102,7 @@ class ChatController(
|
||||
}
|
||||
|
||||
fun switchSession(sessionKey: String) {
|
||||
val key = normalizeRequestedSessionKey(sessionKey)
|
||||
val key = sessionKey.trim()
|
||||
if (key.isEmpty()) return
|
||||
if (key == _sessionKey.value) return
|
||||
_sessionKey.value = key
|
||||
@@ -118,13 +111,6 @@ class ChatController(
|
||||
scope.launch { bootstrap(forceHealth = true, refreshSessions = false) }
|
||||
}
|
||||
|
||||
private fun normalizeRequestedSessionKey(sessionKey: String): String {
|
||||
val key = sessionKey.trim()
|
||||
if (key.isEmpty()) return appliedMainSessionKey
|
||||
if (key == "main" && appliedMainSessionKey != "main") return appliedMainSessionKey
|
||||
return key
|
||||
}
|
||||
|
||||
fun sendMessage(
|
||||
message: String,
|
||||
thinkingLevel: String,
|
||||
@@ -546,28 +532,6 @@ class ChatController(
|
||||
}
|
||||
}
|
||||
|
||||
internal data class MainSessionState(
|
||||
val currentSessionKey: String,
|
||||
val appliedMainSessionKey: String,
|
||||
)
|
||||
|
||||
internal fun applyMainSessionKey(
|
||||
currentSessionKey: String,
|
||||
appliedMainSessionKey: String,
|
||||
nextMainSessionKey: String,
|
||||
): MainSessionState {
|
||||
if (currentSessionKey == appliedMainSessionKey) {
|
||||
return MainSessionState(
|
||||
currentSessionKey = nextMainSessionKey,
|
||||
appliedMainSessionKey = nextMainSessionKey,
|
||||
)
|
||||
}
|
||||
return MainSessionState(
|
||||
currentSessionKey = currentSessionKey,
|
||||
appliedMainSessionKey = nextMainSessionKey,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun reconcileMessageIds(previous: List<ChatMessage>, incoming: List<ChatMessage>): List<ChatMessage> {
|
||||
if (previous.isEmpty() || incoming.isEmpty()) return incoming
|
||||
|
||||
|
||||
@@ -181,10 +181,17 @@ class GatewaySession(
|
||||
|
||||
suspend fun sendNodeEvent(event: String, payloadJson: String?): Boolean {
|
||||
val conn = currentConnection ?: return false
|
||||
val parsedPayload = payloadJson?.let { parseJsonOrNull(it) }
|
||||
val params =
|
||||
buildJsonObject {
|
||||
put("event", JsonPrimitive(event))
|
||||
put("payloadJSON", JsonPrimitive(payloadJson ?: "{}"))
|
||||
if (parsedPayload != null) {
|
||||
put("payload", parsedPayload)
|
||||
} else if (payloadJson != null) {
|
||||
put("payloadJSON", JsonPrimitive(payloadJson))
|
||||
} else {
|
||||
put("payloadJSON", JsonNull)
|
||||
}
|
||||
}
|
||||
try {
|
||||
conn.request("node.event", params, timeoutMs = 8_000)
|
||||
|
||||
@@ -13,13 +13,6 @@ class A2UIHandler(
|
||||
private val getNodeCanvasHostUrl: () -> String?,
|
||||
private val getOperatorCanvasHostUrl: () -> String?,
|
||||
) {
|
||||
fun isTrustedCanvasActionUrl(rawUrl: String?): Boolean {
|
||||
return CanvasActionTrust.isTrustedCanvasActionUrl(
|
||||
rawUrl = rawUrl,
|
||||
trustedA2uiUrls = listOfNotNull(resolveA2uiHostUrl()),
|
||||
)
|
||||
}
|
||||
|
||||
fun resolveA2uiHostUrl(): String? {
|
||||
val nodeRaw = getNodeCanvasHostUrl()?.trim().orEmpty()
|
||||
val operatorRaw = getOperatorCanvasHostUrl()?.trim().orEmpty()
|
||||
|
||||
@@ -121,48 +121,42 @@ class CameraCaptureManager(private val context: Context) {
|
||||
(rotated.height.toDouble() * (maxWidth.toDouble() / rotated.width.toDouble()))
|
||||
.toInt()
|
||||
.coerceAtLeast(1)
|
||||
val s = rotated.scale(maxWidth, h)
|
||||
if (s !== rotated) rotated.recycle()
|
||||
s
|
||||
rotated.scale(maxWidth, h)
|
||||
} else {
|
||||
rotated
|
||||
}
|
||||
|
||||
try {
|
||||
val maxPayloadBytes = 5 * 1024 * 1024
|
||||
// Base64 inflates payloads by ~4/3; cap encoded bytes so the payload stays under 5MB (API limit).
|
||||
val maxEncodedBytes = (maxPayloadBytes / 4) * 3
|
||||
val result =
|
||||
JpegSizeLimiter.compressToLimit(
|
||||
initialWidth = scaled.width,
|
||||
initialHeight = scaled.height,
|
||||
startQuality = (quality * 100.0).roundToInt().coerceIn(10, 100),
|
||||
maxBytes = maxEncodedBytes,
|
||||
encode = { width, height, q ->
|
||||
val bitmap =
|
||||
if (width == scaled.width && height == scaled.height) {
|
||||
scaled
|
||||
} else {
|
||||
scaled.scale(width, height)
|
||||
}
|
||||
val out = ByteArrayOutputStream()
|
||||
if (!bitmap.compress(Bitmap.CompressFormat.JPEG, q, out)) {
|
||||
if (bitmap !== scaled) bitmap.recycle()
|
||||
throw IllegalStateException("UNAVAILABLE: failed to encode JPEG")
|
||||
val maxPayloadBytes = 5 * 1024 * 1024
|
||||
// Base64 inflates payloads by ~4/3; cap encoded bytes so the payload stays under 5MB (API limit).
|
||||
val maxEncodedBytes = (maxPayloadBytes / 4) * 3
|
||||
val result =
|
||||
JpegSizeLimiter.compressToLimit(
|
||||
initialWidth = scaled.width,
|
||||
initialHeight = scaled.height,
|
||||
startQuality = (quality * 100.0).roundToInt().coerceIn(10, 100),
|
||||
maxBytes = maxEncodedBytes,
|
||||
encode = { width, height, q ->
|
||||
val bitmap =
|
||||
if (width == scaled.width && height == scaled.height) {
|
||||
scaled
|
||||
} else {
|
||||
scaled.scale(width, height)
|
||||
}
|
||||
if (bitmap !== scaled) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
out.toByteArray()
|
||||
},
|
||||
)
|
||||
val base64 = Base64.encodeToString(result.bytes, Base64.NO_WRAP)
|
||||
Payload(
|
||||
"""{"format":"jpg","base64":"$base64","width":${result.width},"height":${result.height}}""",
|
||||
val out = ByteArrayOutputStream()
|
||||
if (!bitmap.compress(Bitmap.CompressFormat.JPEG, q, out)) {
|
||||
if (bitmap !== scaled) bitmap.recycle()
|
||||
throw IllegalStateException("UNAVAILABLE: failed to encode JPEG")
|
||||
}
|
||||
if (bitmap !== scaled) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
out.toByteArray()
|
||||
},
|
||||
)
|
||||
} finally {
|
||||
scaled.recycle()
|
||||
}
|
||||
val base64 = Base64.encodeToString(result.bytes, Base64.NO_WRAP)
|
||||
Payload(
|
||||
"""{"format":"jpg","base64":"$base64","width":${result.width},"height":${result.height}}""",
|
||||
)
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
|
||||
@@ -134,11 +134,9 @@ class CameraHandler(
|
||||
}
|
||||
|
||||
val bytes = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
filePayload.file.readBytes()
|
||||
} finally {
|
||||
filePayload.file.delete()
|
||||
}
|
||||
val b = filePayload.file.readBytes()
|
||||
filePayload.file.delete()
|
||||
b
|
||||
}
|
||||
val base64 = android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
|
||||
clipLog("returning base64 payload")
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
package ai.openclaw.app.node
|
||||
|
||||
import java.net.URI
|
||||
|
||||
object CanvasActionTrust {
|
||||
const val scaffoldAssetUrl: String = "file:///android_asset/CanvasScaffold/scaffold.html"
|
||||
|
||||
fun isTrustedCanvasActionUrl(rawUrl: String?, trustedA2uiUrls: List<String>): Boolean {
|
||||
val candidate = rawUrl?.trim().orEmpty()
|
||||
if (candidate.isEmpty()) return false
|
||||
if (candidate == scaffoldAssetUrl) return true
|
||||
|
||||
val candidateUri = parseUri(candidate) ?: return false
|
||||
if (candidateUri.scheme.equals("file", ignoreCase = true)) {
|
||||
return false
|
||||
}
|
||||
|
||||
return trustedA2uiUrls.any { trusted ->
|
||||
isTrustedA2uiPage(candidateUri, trusted)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isTrustedA2uiPage(candidateUri: URI, trustedUrl: String): Boolean {
|
||||
val trustedUri = parseUri(trustedUrl) ?: return false
|
||||
if (!candidateUri.scheme.equals(trustedUri.scheme, ignoreCase = true)) return false
|
||||
if (candidateUri.host?.equals(trustedUri.host, ignoreCase = true) != true) return false
|
||||
if (effectivePort(candidateUri) != effectivePort(trustedUri)) return false
|
||||
|
||||
val trustedPath = trustedUri.rawPath?.takeIf { it.isNotBlank() } ?: return false
|
||||
val candidatePath = candidateUri.rawPath?.takeIf { it.isNotBlank() } ?: return false
|
||||
val trustedPrefix = if (trustedPath.endsWith("/")) trustedPath else "$trustedPath/"
|
||||
return candidatePath == trustedPath || candidatePath.startsWith(trustedPrefix)
|
||||
}
|
||||
|
||||
private fun effectivePort(uri: URI): Int {
|
||||
if (uri.port >= 0) return uri.port
|
||||
return when (uri.scheme?.lowercase()) {
|
||||
"https" -> 443
|
||||
"http" -> 80
|
||||
else -> -1
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseUri(raw: String): URI? =
|
||||
try {
|
||||
URI(raw)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -180,41 +180,27 @@ class CanvasController {
|
||||
withContext(Dispatchers.Main) {
|
||||
val wv = webView ?: throw IllegalStateException("no webview")
|
||||
val bmp = wv.captureBitmap()
|
||||
try {
|
||||
val scaled = bmp.scaleForMaxWidth(maxWidth)
|
||||
try {
|
||||
val out = ByteArrayOutputStream()
|
||||
scaled.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||
Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP)
|
||||
} finally {
|
||||
if (scaled !== bmp) scaled.recycle()
|
||||
}
|
||||
} finally {
|
||||
bmp.recycle()
|
||||
}
|
||||
val scaled = bmp.scaleForMaxWidth(maxWidth)
|
||||
|
||||
val out = ByteArrayOutputStream()
|
||||
scaled.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||
Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
suspend fun snapshotBase64(format: SnapshotFormat, quality: Double?, maxWidth: Int?): String =
|
||||
withContext(Dispatchers.Main) {
|
||||
val wv = webView ?: throw IllegalStateException("no webview")
|
||||
val bmp = wv.captureBitmap()
|
||||
try {
|
||||
val scaled = bmp.scaleForMaxWidth(maxWidth)
|
||||
try {
|
||||
val out = ByteArrayOutputStream()
|
||||
val (compressFormat, compressQuality) =
|
||||
when (format) {
|
||||
SnapshotFormat.Png -> Bitmap.CompressFormat.PNG to 100
|
||||
SnapshotFormat.Jpeg -> Bitmap.CompressFormat.JPEG to clampJpegQuality(quality)
|
||||
}
|
||||
scaled.compress(compressFormat, compressQuality, out)
|
||||
Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP)
|
||||
} finally {
|
||||
if (scaled !== bmp) scaled.recycle()
|
||||
val scaled = bmp.scaleForMaxWidth(maxWidth)
|
||||
|
||||
val out = ByteArrayOutputStream()
|
||||
val (compressFormat, compressQuality) =
|
||||
when (format) {
|
||||
SnapshotFormat.Png -> Bitmap.CompressFormat.PNG to 100
|
||||
SnapshotFormat.Jpeg -> Bitmap.CompressFormat.JPEG to clampJpegQuality(quality)
|
||||
}
|
||||
} finally {
|
||||
bmp.recycle()
|
||||
}
|
||||
scaled.compress(compressFormat, compressQuality, out)
|
||||
Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
private suspend fun WebView.captureBitmap(): Bitmap =
|
||||
|
||||
@@ -19,7 +19,6 @@ class ConnectionManager(
|
||||
private val motionPedometerAvailable: () -> Boolean,
|
||||
private val sendSmsAvailable: () -> Boolean,
|
||||
private val readSmsAvailable: () -> Boolean,
|
||||
private val smsSearchPossible: () -> Boolean,
|
||||
private val callLogAvailable: () -> Boolean,
|
||||
private val hasRecordAudioPermission: () -> Boolean,
|
||||
private val manualTls: () -> Boolean,
|
||||
@@ -83,7 +82,6 @@ class ConnectionManager(
|
||||
locationEnabled = locationMode() != LocationMode.Off,
|
||||
sendSmsAvailable = sendSmsAvailable(),
|
||||
readSmsAvailable = readSmsAvailable(),
|
||||
smsSearchPossible = smsSearchPossible(),
|
||||
callLogAvailable = callLogAvailable(),
|
||||
voiceWakeEnabled = voiceWakeMode() != VoiceWakeMode.Off && hasRecordAudioPermission(),
|
||||
motionActivityAvailable = motionActivityAvailable(),
|
||||
|
||||
@@ -76,8 +76,8 @@ private object SystemContactsDataSource : ContactsDataSource {
|
||||
selection = null
|
||||
selectionArgs = null
|
||||
} else {
|
||||
selection = "${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} LIKE ? ESCAPE '\\'"
|
||||
selectionArgs = arrayOf("%${escapeLikePattern(request.query)}%")
|
||||
selection = "${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} LIKE ?"
|
||||
selectionArgs = arrayOf("%${request.query}%")
|
||||
}
|
||||
val sortOrder = "${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} COLLATE NOCASE ASC LIMIT ${request.limit}"
|
||||
resolver.query(
|
||||
@@ -247,9 +247,6 @@ private object SystemContactsDataSource : ContactsDataSource {
|
||||
}
|
||||
}
|
||||
|
||||
private fun escapeLikePattern(pattern: String): String =
|
||||
pattern.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
|
||||
private fun loadPhones(resolver: ContentResolver, contactId: Long): List<String> {
|
||||
return queryContactValues(
|
||||
resolver = resolver,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package ai.openclaw.app.node
|
||||
|
||||
import ai.openclaw.app.BuildConfig
|
||||
import android.Manifest
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
@@ -16,9 +15,9 @@ import android.os.PowerManager
|
||||
import android.os.StatFs
|
||||
import android.os.SystemClock
|
||||
import androidx.core.content.ContextCompat
|
||||
import ai.openclaw.app.BuildConfig
|
||||
import ai.openclaw.app.gateway.GatewaySession
|
||||
import java.util.Locale
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
@@ -29,25 +28,6 @@ class DeviceHandler(
|
||||
private val smsEnabled: Boolean = BuildConfig.OPENCLAW_ENABLE_SMS,
|
||||
private val callLogEnabled: Boolean = BuildConfig.OPENCLAW_ENABLE_CALL_LOG,
|
||||
) {
|
||||
companion object {
|
||||
internal fun hasAnySmsCapability(
|
||||
smsEnabled: Boolean,
|
||||
telephonyAvailable: Boolean,
|
||||
smsSendGranted: Boolean,
|
||||
smsReadGranted: Boolean,
|
||||
): Boolean {
|
||||
return smsEnabled && telephonyAvailable && (smsSendGranted || smsReadGranted)
|
||||
}
|
||||
|
||||
internal fun isSmsPromptable(
|
||||
smsEnabled: Boolean,
|
||||
telephonyAvailable: Boolean,
|
||||
smsSendGranted: Boolean,
|
||||
smsReadGranted: Boolean,
|
||||
): Boolean {
|
||||
return smsEnabled && telephonyAvailable && (!smsSendGranted || !smsReadGranted)
|
||||
}
|
||||
}
|
||||
private data class BatterySnapshot(
|
||||
val status: Int,
|
||||
val plugged: Int,
|
||||
@@ -151,8 +131,6 @@ class DeviceHandler(
|
||||
|
||||
private fun permissionsPayloadJson(): String {
|
||||
val canSendSms = appContext.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
|
||||
val smsSendGranted = hasPermission(Manifest.permission.SEND_SMS)
|
||||
val smsReadGranted = hasPermission(Manifest.permission.READ_SMS)
|
||||
val notificationAccess = DeviceNotificationListenerService.isAccessEnabled(appContext)
|
||||
val photosGranted =
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
@@ -196,34 +174,10 @@ class DeviceHandler(
|
||||
)
|
||||
put(
|
||||
"sms",
|
||||
buildJsonObject {
|
||||
put(
|
||||
"status",
|
||||
JsonPrimitive(
|
||||
if (hasAnySmsCapability(smsEnabled, canSendSms, smsSendGranted, smsReadGranted)) "granted" else "denied",
|
||||
),
|
||||
)
|
||||
put("promptable", JsonPrimitive(isSmsPromptable(smsEnabled, canSendSms, smsSendGranted, smsReadGranted)))
|
||||
put(
|
||||
"capabilities",
|
||||
buildJsonObject {
|
||||
put(
|
||||
"send",
|
||||
permissionStateJson(
|
||||
granted = smsEnabled && smsSendGranted && canSendSms,
|
||||
promptableWhenDenied = smsEnabled && canSendSms,
|
||||
),
|
||||
)
|
||||
put(
|
||||
"read",
|
||||
permissionStateJson(
|
||||
granted = smsEnabled && smsReadGranted && canSendSms,
|
||||
promptableWhenDenied = smsEnabled && canSendSms,
|
||||
),
|
||||
)
|
||||
},
|
||||
)
|
||||
},
|
||||
permissionStateJson(
|
||||
granted = smsEnabled && hasPermission(Manifest.permission.SEND_SMS) && canSendSms,
|
||||
promptableWhenDenied = smsEnabled && canSendSms,
|
||||
),
|
||||
)
|
||||
put(
|
||||
"notificationListener",
|
||||
|
||||
@@ -8,10 +8,6 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.service.notification.NotificationListenerService
|
||||
import android.service.notification.StatusBarNotification
|
||||
import ai.openclaw.app.NotificationBurstLimiter
|
||||
import ai.openclaw.app.SecurePrefs
|
||||
import ai.openclaw.app.allowsPackage
|
||||
import ai.openclaw.app.isWithinQuietHours
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
@@ -130,9 +126,6 @@ private object DeviceNotificationStore {
|
||||
}
|
||||
|
||||
class DeviceNotificationListenerService : NotificationListenerService() {
|
||||
private val securePrefs by lazy { SecurePrefs(applicationContext) }
|
||||
private val forwardingLimiter = NotificationBurstLimiter()
|
||||
|
||||
override fun onListenerConnected() {
|
||||
super.onListenerConnected()
|
||||
activeService = this
|
||||
@@ -159,12 +152,24 @@ class DeviceNotificationListenerService : NotificationListenerService() {
|
||||
super.onNotificationPosted(sbn)
|
||||
val entry = sbn?.toEntry() ?: return
|
||||
DeviceNotificationStore.upsert(entry)
|
||||
rememberRecentPackage(entry.packageName)
|
||||
if (entry.packageName == packageName) {
|
||||
return
|
||||
}
|
||||
val payload = notificationChangedPayload(entry) ?: return
|
||||
emitNotificationsChanged(payload)
|
||||
emitNotificationsChanged(
|
||||
buildJsonObject {
|
||||
put("change", JsonPrimitive("posted"))
|
||||
put("key", JsonPrimitive(entry.key))
|
||||
put("packageName", JsonPrimitive(entry.packageName))
|
||||
put("postTimeMs", JsonPrimitive(entry.postTimeMs))
|
||||
put("isOngoing", JsonPrimitive(entry.isOngoing))
|
||||
put("isClearable", JsonPrimitive(entry.isClearable))
|
||||
entry.title?.let { put("title", JsonPrimitive(it)) }
|
||||
entry.text?.let { put("text", JsonPrimitive(it)) }
|
||||
entry.subText?.let { put("subText", JsonPrimitive(it)) }
|
||||
entry.category?.let { put("category", JsonPrimitive(it)) }
|
||||
entry.channelId?.let { put("channelId", JsonPrimitive(it)) }
|
||||
}.toString(),
|
||||
)
|
||||
}
|
||||
|
||||
override fun onNotificationRemoved(sbn: StatusBarNotification?) {
|
||||
@@ -175,79 +180,21 @@ class DeviceNotificationListenerService : NotificationListenerService() {
|
||||
return
|
||||
}
|
||||
DeviceNotificationStore.remove(key)
|
||||
rememberRecentPackage(removed.packageName)
|
||||
if (removed.packageName == packageName) {
|
||||
return
|
||||
}
|
||||
val packageName = removed.packageName.trim()
|
||||
val payload =
|
||||
notificationChangedPayload(
|
||||
entry = null,
|
||||
change = "removed",
|
||||
key = key,
|
||||
packageName = packageName,
|
||||
postTimeMs = removed.postTime,
|
||||
isOngoing = removed.isOngoing,
|
||||
isClearable = removed.isClearable,
|
||||
) ?: return
|
||||
emitNotificationsChanged(payload)
|
||||
}
|
||||
|
||||
private fun notificationChangedPayload(entry: DeviceNotificationEntry): String? {
|
||||
return notificationChangedPayload(
|
||||
entry = entry,
|
||||
change = "posted",
|
||||
key = entry.key,
|
||||
packageName = entry.packageName,
|
||||
postTimeMs = entry.postTimeMs,
|
||||
isOngoing = entry.isOngoing,
|
||||
isClearable = entry.isClearable,
|
||||
emitNotificationsChanged(
|
||||
buildJsonObject {
|
||||
put("change", JsonPrimitive("removed"))
|
||||
put("key", JsonPrimitive(key))
|
||||
val packageName = removed.packageName.trim()
|
||||
if (packageName.isNotEmpty()) {
|
||||
put("packageName", JsonPrimitive(packageName))
|
||||
}
|
||||
}.toString(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun notificationChangedPayload(
|
||||
entry: DeviceNotificationEntry?,
|
||||
change: String,
|
||||
key: String,
|
||||
packageName: String,
|
||||
postTimeMs: Long,
|
||||
isOngoing: Boolean,
|
||||
isClearable: Boolean,
|
||||
): String? {
|
||||
val normalizedPackage = packageName.trim()
|
||||
if (normalizedPackage.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
val policy = securePrefs.getNotificationForwardingPolicy(appPackageName = this.packageName)
|
||||
if (!policy.enabled) {
|
||||
return null
|
||||
}
|
||||
if (!policy.allowsPackage(normalizedPackage)) {
|
||||
return null
|
||||
}
|
||||
val nowEpochMs = System.currentTimeMillis()
|
||||
if (policy.isWithinQuietHours(nowEpochMs = nowEpochMs)) {
|
||||
return null
|
||||
}
|
||||
if (!forwardingLimiter.allow(nowEpochMs, policy.maxEventsPerMinute)) {
|
||||
return null
|
||||
}
|
||||
return buildJsonObject {
|
||||
put("change", JsonPrimitive(change))
|
||||
put("key", JsonPrimitive(key))
|
||||
put("packageName", JsonPrimitive(normalizedPackage))
|
||||
put("postTimeMs", JsonPrimitive(postTimeMs))
|
||||
put("isOngoing", JsonPrimitive(isOngoing))
|
||||
put("isClearable", JsonPrimitive(isClearable))
|
||||
policy.sessionKey?.let { put("sessionKey", JsonPrimitive(it)) }
|
||||
entry?.title?.let { put("title", JsonPrimitive(it)) }
|
||||
entry?.text?.let { put("text", JsonPrimitive(it)) }
|
||||
entry?.subText?.let { put("subText", JsonPrimitive(it)) }
|
||||
entry?.category?.let { put("category", JsonPrimitive(it)) }
|
||||
entry?.channelId?.let { put("channelId", JsonPrimitive(it)) }
|
||||
}.toString()
|
||||
}
|
||||
|
||||
private fun refreshActiveNotifications() {
|
||||
val entries =
|
||||
runCatching {
|
||||
@@ -281,9 +228,6 @@ class DeviceNotificationListenerService : NotificationListenerService() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val recentPackagesPref = "notifications.forwarding.recentPackages"
|
||||
private const val legacyRecentPackagesPref = "notifications.recentPackages"
|
||||
private const val recentPackagesLimit = 64
|
||||
@Volatile private var activeService: DeviceNotificationListenerService? = null
|
||||
@Volatile private var nodeEventSink: ((event: String, payloadJson: String?) -> Unit)? = null
|
||||
|
||||
@@ -295,31 +239,6 @@ class DeviceNotificationListenerService : NotificationListenerService() {
|
||||
nodeEventSink = sink
|
||||
}
|
||||
|
||||
private fun recentPackagesPrefs(context: Context) =
|
||||
context.applicationContext.getSharedPreferences("openclaw.secure", Context.MODE_PRIVATE)
|
||||
|
||||
private fun migrateLegacyRecentPackagesIfNeeded(context: Context) {
|
||||
val prefs = recentPackagesPrefs(context)
|
||||
val hasNew = prefs.contains(recentPackagesPref)
|
||||
val legacy = prefs.getString(legacyRecentPackagesPref, null)?.trim().orEmpty()
|
||||
if (!hasNew && legacy.isNotEmpty()) {
|
||||
prefs.edit().putString(recentPackagesPref, legacy).remove(legacyRecentPackagesPref).apply()
|
||||
} else if (hasNew && prefs.contains(legacyRecentPackagesPref)) {
|
||||
prefs.edit().remove(legacyRecentPackagesPref).apply()
|
||||
}
|
||||
}
|
||||
|
||||
fun recentPackages(context: Context): List<String> {
|
||||
migrateLegacyRecentPackagesIfNeeded(context)
|
||||
val prefs = recentPackagesPrefs(context)
|
||||
val stored = prefs.getString(recentPackagesPref, null).orEmpty()
|
||||
return stored
|
||||
.split(',')
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.distinct()
|
||||
}
|
||||
|
||||
fun isAccessEnabled(context: Context): Boolean {
|
||||
val manager = context.getSystemService(NotificationManager::class.java) ?: return false
|
||||
return manager.isNotificationListenerAccessGranted(serviceComponent(context))
|
||||
@@ -357,21 +276,6 @@ class DeviceNotificationListenerService : NotificationListenerService() {
|
||||
nodeEventSink?.invoke(NOTIFICATIONS_CHANGED_EVENT, payloadJson)
|
||||
}
|
||||
}
|
||||
|
||||
private fun rememberRecentPackage(packageName: String?) {
|
||||
val service = activeService ?: return
|
||||
val normalized = packageName?.trim().orEmpty()
|
||||
if (normalized.isEmpty() || normalized == service.packageName) return
|
||||
migrateLegacyRecentPackagesIfNeeded(service.applicationContext)
|
||||
val prefs = recentPackagesPrefs(service.applicationContext)
|
||||
val existing = prefs.getString(recentPackagesPref, null).orEmpty()
|
||||
.split(',')
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() && it != normalized }
|
||||
.take(recentPackagesLimit - 1)
|
||||
val updated = listOf(normalized) + existing
|
||||
prefs.edit().putString(recentPackagesPref, updated.joinToString(",")).apply()
|
||||
}
|
||||
}
|
||||
|
||||
private fun executeActionInternal(request: NotificationActionRequest): NotificationActionResult {
|
||||
|
||||
@@ -20,7 +20,6 @@ data class NodeRuntimeFlags(
|
||||
val locationEnabled: Boolean,
|
||||
val sendSmsAvailable: Boolean,
|
||||
val readSmsAvailable: Boolean,
|
||||
val smsSearchPossible: Boolean,
|
||||
val callLogAvailable: Boolean,
|
||||
val voiceWakeEnabled: Boolean,
|
||||
val motionActivityAvailable: Boolean,
|
||||
@@ -34,7 +33,6 @@ enum class InvokeCommandAvailability {
|
||||
LocationEnabled,
|
||||
SendSmsAvailable,
|
||||
ReadSmsAvailable,
|
||||
RequestableSmsSearchAvailable,
|
||||
CallLogAvailable,
|
||||
MotionActivityAvailable,
|
||||
MotionPedometerAvailable,
|
||||
@@ -201,7 +199,7 @@ object InvokeCommandRegistry {
|
||||
),
|
||||
InvokeCommandSpec(
|
||||
name = OpenClawSmsCommand.Search.rawValue,
|
||||
availability = InvokeCommandAvailability.RequestableSmsSearchAvailable,
|
||||
availability = InvokeCommandAvailability.ReadSmsAvailable,
|
||||
),
|
||||
InvokeCommandSpec(
|
||||
name = OpenClawCallLogCommand.Search.rawValue,
|
||||
@@ -246,7 +244,6 @@ object InvokeCommandRegistry {
|
||||
InvokeCommandAvailability.LocationEnabled -> flags.locationEnabled
|
||||
InvokeCommandAvailability.SendSmsAvailable -> flags.sendSmsAvailable
|
||||
InvokeCommandAvailability.ReadSmsAvailable -> flags.readSmsAvailable
|
||||
InvokeCommandAvailability.RequestableSmsSearchAvailable -> flags.smsSearchPossible
|
||||
InvokeCommandAvailability.CallLogAvailable -> flags.callLogAvailable
|
||||
InvokeCommandAvailability.MotionActivityAvailable -> flags.motionActivityAvailable
|
||||
InvokeCommandAvailability.MotionPedometerAvailable -> flags.motionPedometerAvailable
|
||||
|
||||
@@ -14,44 +14,6 @@ import ai.openclaw.app.protocol.OpenClawNotificationsCommand
|
||||
import ai.openclaw.app.protocol.OpenClawSmsCommand
|
||||
import ai.openclaw.app.protocol.OpenClawSystemCommand
|
||||
|
||||
internal enum class SmsSearchAvailabilityReason {
|
||||
Available,
|
||||
PermissionRequired,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
internal fun classifySmsSearchAvailability(
|
||||
readSmsAvailable: Boolean,
|
||||
smsFeatureEnabled: Boolean,
|
||||
smsTelephonyAvailable: Boolean,
|
||||
): SmsSearchAvailabilityReason {
|
||||
if (readSmsAvailable) return SmsSearchAvailabilityReason.Available
|
||||
if (!smsFeatureEnabled || !smsTelephonyAvailable) return SmsSearchAvailabilityReason.Unavailable
|
||||
return SmsSearchAvailabilityReason.PermissionRequired
|
||||
}
|
||||
|
||||
internal fun smsSearchAvailabilityError(
|
||||
readSmsAvailable: Boolean,
|
||||
smsFeatureEnabled: Boolean,
|
||||
smsTelephonyAvailable: Boolean,
|
||||
): GatewaySession.InvokeResult? {
|
||||
return when (
|
||||
classifySmsSearchAvailability(
|
||||
readSmsAvailable = readSmsAvailable,
|
||||
smsFeatureEnabled = smsFeatureEnabled,
|
||||
smsTelephonyAvailable = smsTelephonyAvailable,
|
||||
)
|
||||
) {
|
||||
SmsSearchAvailabilityReason.Available,
|
||||
SmsSearchAvailabilityReason.PermissionRequired -> null
|
||||
SmsSearchAvailabilityReason.Unavailable ->
|
||||
GatewaySession.InvokeResult.error(
|
||||
code = "SMS_UNAVAILABLE",
|
||||
message = "SMS_UNAVAILABLE: SMS not available on this device",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class InvokeDispatcher(
|
||||
private val canvas: CanvasController,
|
||||
private val cameraHandler: CameraHandler,
|
||||
@@ -72,8 +34,6 @@ class InvokeDispatcher(
|
||||
private val locationEnabled: () -> Boolean,
|
||||
private val sendSmsAvailable: () -> Boolean,
|
||||
private val readSmsAvailable: () -> Boolean,
|
||||
private val smsFeatureEnabled: () -> Boolean,
|
||||
private val smsTelephonyAvailable: () -> Boolean,
|
||||
private val callLogAvailable: () -> Boolean,
|
||||
private val debugBuild: () -> Boolean,
|
||||
private val refreshNodeCanvasCapability: suspend () -> Boolean,
|
||||
@@ -308,13 +268,15 @@ class InvokeDispatcher(
|
||||
message = "SMS_UNAVAILABLE: SMS not available on this device",
|
||||
)
|
||||
}
|
||||
InvokeCommandAvailability.ReadSmsAvailable,
|
||||
InvokeCommandAvailability.RequestableSmsSearchAvailable ->
|
||||
smsSearchAvailabilityError(
|
||||
readSmsAvailable = readSmsAvailable(),
|
||||
smsFeatureEnabled = smsFeatureEnabled(),
|
||||
smsTelephonyAvailable = smsTelephonyAvailable(),
|
||||
)
|
||||
InvokeCommandAvailability.ReadSmsAvailable ->
|
||||
if (readSmsAvailable()) {
|
||||
null
|
||||
} else {
|
||||
GatewaySession.InvokeResult.error(
|
||||
code = "SMS_UNAVAILABLE",
|
||||
message = "SMS_UNAVAILABLE: SMS not available on this device",
|
||||
)
|
||||
}
|
||||
InvokeCommandAvailability.CallLogAvailable ->
|
||||
if (callLogAvailable()) {
|
||||
null
|
||||
|
||||
@@ -12,6 +12,8 @@ import java.time.format.DateTimeFormatter
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
|
||||
class LocationCaptureManager(private val context: Context) {
|
||||
@@ -98,15 +100,18 @@ class LocationCaptureManager(private val context: Context) {
|
||||
val resolved =
|
||||
providers.firstOrNull { manager.isProviderEnabled(it) }
|
||||
?: throw IllegalStateException("LOCATION_UNAVAILABLE: no providers available")
|
||||
val location = withTimeout(timeoutMs.coerceAtLeast(1)) {
|
||||
suspendCancellableCoroutine<Location?> { cont ->
|
||||
return withTimeout(timeoutMs.coerceAtLeast(1)) {
|
||||
suspendCancellableCoroutine { cont ->
|
||||
val signal = CancellationSignal()
|
||||
cont.invokeOnCancellation { signal.cancel() }
|
||||
manager.getCurrentLocation(resolved, signal, context.mainExecutor) { location ->
|
||||
cont.resume(location) { _, _, _ -> }
|
||||
if (location != null) {
|
||||
cont.resume(location)
|
||||
} else {
|
||||
cont.resumeWithException(IllegalStateException("LOCATION_UNAVAILABLE: no fix"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return location ?: throw IllegalStateException("LOCATION_UNAVAILABLE: no fix")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import android.os.SystemClock
|
||||
import androidx.core.content.ContextCompat
|
||||
import ai.openclaw.app.gateway.GatewaySession
|
||||
import java.time.Instant
|
||||
import kotlinx.coroutines.InternalCoroutinesApi
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.serialization.json.Json
|
||||
@@ -19,6 +18,7 @@ import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
import kotlin.math.sqrt
|
||||
@@ -142,18 +142,19 @@ private object SystemMotionDataSource : MotionDataSource {
|
||||
val averageDelta: Double,
|
||||
)
|
||||
|
||||
@OptIn(InternalCoroutinesApi::class)
|
||||
private suspend fun readStepCounter(sensorManager: SensorManager, sensor: Sensor): Int? {
|
||||
val sample =
|
||||
withTimeoutOrNull(1200L) {
|
||||
suspendCancellableCoroutine<Float?> { cont ->
|
||||
var resumed = false
|
||||
val listener =
|
||||
object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent?) {
|
||||
if (resumed) return
|
||||
val value = event?.values?.firstOrNull()
|
||||
val token = cont.tryResume(value) ?: return
|
||||
cont.completeResume(token)
|
||||
resumed = true
|
||||
sensorManager.unregisterListener(this)
|
||||
cont.resume(value)
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
|
||||
@@ -161,7 +162,8 @@ private object SystemMotionDataSource : MotionDataSource {
|
||||
val registered = sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL)
|
||||
if (!registered) {
|
||||
sensorManager.unregisterListener(listener)
|
||||
cont.resume(null) { _, _, _ -> }
|
||||
resumed = true
|
||||
cont.resume(null)
|
||||
return@suspendCancellableCoroutine
|
||||
}
|
||||
cont.invokeOnCancellation { sensorManager.unregisterListener(listener) }
|
||||
@@ -170,7 +172,6 @@ private object SystemMotionDataSource : MotionDataSource {
|
||||
return sample?.toInt()?.takeIf { it >= 0 }
|
||||
}
|
||||
|
||||
@OptIn(InternalCoroutinesApi::class)
|
||||
private suspend fun readAccelerometerSample(
|
||||
sensorManager: SensorManager,
|
||||
sensor: Sensor,
|
||||
@@ -180,6 +181,7 @@ private object SystemMotionDataSource : MotionDataSource {
|
||||
suspendCancellableCoroutine<AccelerometerSample?> { cont ->
|
||||
var count = 0
|
||||
var sumDelta = 0.0
|
||||
var resumed = false
|
||||
val listener =
|
||||
object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent?) {
|
||||
@@ -193,14 +195,15 @@ private object SystemMotionDataSource : MotionDataSource {
|
||||
).toDouble()
|
||||
sumDelta += abs(magnitude - SensorManager.GRAVITY_EARTH.toDouble())
|
||||
count += 1
|
||||
if (count >= ACCELEROMETER_SAMPLE_TARGET) {
|
||||
val result = AccelerometerSample(
|
||||
samples = count,
|
||||
averageDelta = sumDelta / count,
|
||||
)
|
||||
val token = cont.tryResume(result) ?: return
|
||||
cont.completeResume(token)
|
||||
if (count >= ACCELEROMETER_SAMPLE_TARGET && !resumed) {
|
||||
resumed = true
|
||||
sensorManager.unregisterListener(this)
|
||||
cont.resume(
|
||||
AccelerometerSample(
|
||||
samples = count,
|
||||
averageDelta = if (count == 0) 0.0 else sumDelta / count,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,7 +211,8 @@ private object SystemMotionDataSource : MotionDataSource {
|
||||
}
|
||||
val registered = sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL)
|
||||
if (!registered) {
|
||||
cont.resume(null) { _, _, _ -> }
|
||||
resumed = true
|
||||
cont.resume(null)
|
||||
return@suspendCancellableCoroutine
|
||||
}
|
||||
cont.invokeOnCancellation { sensorManager.unregisterListener(listener) }
|
||||
|
||||
@@ -71,22 +71,17 @@ private object SystemPhotosDataSource : PhotosDataSource {
|
||||
for (row in rows) {
|
||||
if (remainingBudget <= 0) break
|
||||
val bitmap = decodeScaledBitmap(resolver, row.uri, request.maxWidth) ?: continue
|
||||
try {
|
||||
val encoded = encodeJpegUnderBudget(bitmap, request.quality, MAX_PER_PHOTO_BASE64_CHARS)
|
||||
if (encoded == null) continue
|
||||
if (encoded.base64.length > remainingBudget) break
|
||||
remainingBudget -= encoded.base64.length
|
||||
out +=
|
||||
EncodedPhotoPayload(
|
||||
format = "jpeg",
|
||||
base64 = encoded.base64,
|
||||
width = encoded.width,
|
||||
height = encoded.height,
|
||||
createdAt = row.createdAtMs?.let { Instant.ofEpochMilli(it).toString() },
|
||||
)
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
val encoded = encodeJpegUnderBudget(bitmap, request.quality, MAX_PER_PHOTO_BASE64_CHARS) ?: continue
|
||||
if (encoded.base64.length > remainingBudget) break
|
||||
remainingBudget -= encoded.base64.length
|
||||
out +=
|
||||
EncodedPhotoPayload(
|
||||
format = "jpeg",
|
||||
base64 = encoded.base64,
|
||||
width = encoded.width,
|
||||
height = encoded.height,
|
||||
createdAt = row.createdAtMs?.let { Instant.ofEpochMilli(it).toString() },
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -164,11 +159,7 @@ private object SystemPhotosDataSource : PhotosDataSource {
|
||||
|
||||
if (decoded.width <= maxWidth) return decoded
|
||||
val targetHeight = max(1, ((decoded.height.toDouble() * maxWidth) / decoded.width).roundToInt())
|
||||
return try {
|
||||
decoded.scale(maxWidth, targetHeight, true)
|
||||
} finally {
|
||||
decoded.recycle()
|
||||
}
|
||||
return decoded.scale(maxWidth, targetHeight, true)
|
||||
}
|
||||
|
||||
private fun computeInSampleSize(width: Int, maxWidth: Int): Int {
|
||||
@@ -187,36 +178,30 @@ private object SystemPhotosDataSource : PhotosDataSource {
|
||||
maxBase64Chars: Int,
|
||||
): EncodedJpeg? {
|
||||
var working = bitmap
|
||||
try {
|
||||
var jpegQuality = (quality.coerceIn(0.1, 1.0) * 100.0).roundToInt().coerceIn(10, 100)
|
||||
repeat(10) {
|
||||
val out = ByteArrayOutputStream()
|
||||
val ok = working.compress(Bitmap.CompressFormat.JPEG, jpegQuality, out)
|
||||
if (!ok) return null
|
||||
val bytes = out.toByteArray()
|
||||
val base64 = android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
|
||||
if (base64.length <= maxBase64Chars) {
|
||||
return EncodedJpeg(
|
||||
base64 = base64,
|
||||
width = working.width,
|
||||
height = working.height,
|
||||
)
|
||||
}
|
||||
if (jpegQuality > 35) {
|
||||
jpegQuality = max(25, jpegQuality - 15)
|
||||
return@repeat
|
||||
}
|
||||
val nextWidth = max(240, (working.width * 0.75f).roundToInt())
|
||||
if (nextWidth >= working.width) return null
|
||||
val nextHeight = max(1, ((working.height.toDouble() * nextWidth) / working.width).roundToInt())
|
||||
val previous = working
|
||||
working = working.scale(nextWidth, nextHeight, true)
|
||||
if (previous !== bitmap) previous.recycle()
|
||||
var jpegQuality = (quality.coerceIn(0.1, 1.0) * 100.0).roundToInt().coerceIn(10, 100)
|
||||
repeat(10) {
|
||||
val out = ByteArrayOutputStream()
|
||||
val ok = working.compress(Bitmap.CompressFormat.JPEG, jpegQuality, out)
|
||||
if (!ok) return null
|
||||
val bytes = out.toByteArray()
|
||||
val base64 = android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
|
||||
if (base64.length <= maxBase64Chars) {
|
||||
return EncodedJpeg(
|
||||
base64 = base64,
|
||||
width = working.width,
|
||||
height = working.height,
|
||||
)
|
||||
}
|
||||
return null
|
||||
} finally {
|
||||
if (working !== bitmap) working.recycle()
|
||||
if (jpegQuality > 35) {
|
||||
jpegQuality = max(25, jpegQuality - 15)
|
||||
return@repeat
|
||||
}
|
||||
val nextWidth = max(240, (working.width * 0.75f).roundToInt())
|
||||
if (nextWidth >= working.width) return null
|
||||
val nextHeight = max(1, ((working.height.toDouble() * nextWidth) / working.width).roundToInt())
|
||||
working = working.scale(nextWidth, nextHeight, true)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,28 +9,23 @@ class SmsHandler(
|
||||
val res = sms.send(paramsJson)
|
||||
if (res.ok) {
|
||||
return GatewaySession.InvokeResult.ok(res.payloadJson)
|
||||
} else {
|
||||
val error = res.error ?: "SMS_SEND_FAILED"
|
||||
val idx = error.indexOf(':')
|
||||
val code = if (idx > 0) error.substring(0, idx).trim() else "SMS_SEND_FAILED"
|
||||
return GatewaySession.InvokeResult.error(code = code, message = error)
|
||||
}
|
||||
return errorResult(res.error, defaultCode = "SMS_SEND_FAILED")
|
||||
}
|
||||
|
||||
suspend fun handleSmsSearch(paramsJson: String?): GatewaySession.InvokeResult {
|
||||
val res = sms.search(paramsJson)
|
||||
if (res.ok) {
|
||||
return GatewaySession.InvokeResult.ok(res.payloadJson)
|
||||
} else {
|
||||
val error = res.error ?: "SMS_SEARCH_FAILED"
|
||||
val idx = error.indexOf(':')
|
||||
val code = if (idx > 0) error.substring(0, idx).trim() else "SMS_SEARCH_FAILED"
|
||||
return GatewaySession.InvokeResult.error(code = code, message = error)
|
||||
}
|
||||
return errorResult(res.error, defaultCode = "SMS_SEARCH_FAILED")
|
||||
}
|
||||
|
||||
private fun errorResult(error: String?, defaultCode: String): GatewaySession.InvokeResult {
|
||||
val rawMessage = error ?: defaultCode
|
||||
val idx = rawMessage.indexOf(':')
|
||||
val code = if (idx > 0) rawMessage.substring(0, idx).trim() else defaultCode
|
||||
val message =
|
||||
if (idx > 0 && code == rawMessage.substring(0, idx).trim()) {
|
||||
rawMessage.substring(idx + 1).trim().ifEmpty { rawMessage }
|
||||
} else {
|
||||
rawMessage
|
||||
}
|
||||
return GatewaySession.InvokeResult.error(code = code, message = message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,21 +3,21 @@ package ai.openclaw.app.node
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.provider.ContactsContract
|
||||
import android.provider.Telephony
|
||||
import android.telephony.SmsManager as AndroidSmsManager
|
||||
import androidx.core.content.ContextCompat
|
||||
import ai.openclaw.app.PermissionRequester
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.Serializable
|
||||
import ai.openclaw.app.PermissionRequester
|
||||
|
||||
/**
|
||||
* Sends SMS messages via the Android SMS API.
|
||||
@@ -39,7 +39,7 @@ class SmsManager(private val context: Context) {
|
||||
)
|
||||
|
||||
/**
|
||||
* Represents a single SMS message.
|
||||
* Represents a single SMS message
|
||||
*/
|
||||
@Serializable
|
||||
data class SmsMessage(
|
||||
@@ -53,7 +53,6 @@ class SmsManager(private val context: Context) {
|
||||
val type: Int,
|
||||
val body: String?,
|
||||
val status: Int,
|
||||
val transportType: String? = null,
|
||||
)
|
||||
|
||||
data class SearchResult(
|
||||
@@ -63,13 +62,6 @@ class SmsManager(private val context: Context) {
|
||||
val payloadJson: String,
|
||||
)
|
||||
|
||||
internal data class QueryMetadata(
|
||||
val mmsRequested: Boolean,
|
||||
val mmsEligible: Boolean,
|
||||
val mmsAttempted: Boolean,
|
||||
val mmsIncluded: Boolean,
|
||||
)
|
||||
|
||||
internal data class ParsedParams(
|
||||
val to: String,
|
||||
val message: String,
|
||||
@@ -92,8 +84,6 @@ class SmsManager(private val context: Context) {
|
||||
val keyword: String? = null,
|
||||
val type: Int? = null,
|
||||
val isRead: Boolean? = null,
|
||||
val includeMms: Boolean = false,
|
||||
val conversationReview: Boolean = false,
|
||||
val limit: Int = DEFAULT_SMS_LIMIT,
|
||||
val offset: Int = 0,
|
||||
)
|
||||
@@ -110,11 +100,6 @@ class SmsManager(private val context: Context) {
|
||||
|
||||
companion object {
|
||||
private const val DEFAULT_SMS_LIMIT = 25
|
||||
internal const val MAX_MIXED_BY_PHONE_CANDIDATE_WINDOW = 500
|
||||
private const val MMS_SMS_BY_PHONE_BASE = "content://mms-sms/messages/byphone"
|
||||
private const val MMS_CONTENT_BASE = "content://mms"
|
||||
private const val MMS_PART_URI = "content://mms/part"
|
||||
private val PHONE_FORMATTING_REGEX = Regex("""[\s\-()]""")
|
||||
internal val JsonConfig = Json { ignoreUnknownKeys = true }
|
||||
|
||||
internal fun parseParams(paramsJson: String?, json: Json = JsonConfig): ParseResult {
|
||||
@@ -172,333 +157,31 @@ class SmsManager(private val context: Context) {
|
||||
val keyword = (obj["keyword"] as? JsonPrimitive)?.content?.trim()
|
||||
val type = (obj["type"] as? JsonPrimitive)?.content?.toIntOrNull()
|
||||
val isRead = (obj["isRead"] as? JsonPrimitive)?.content?.toBooleanStrictOrNull()
|
||||
val includeMms = (obj["includeMms"] as? JsonPrimitive)?.content?.toBooleanStrictOrNull() ?: false
|
||||
val conversationReview = (obj["conversationReview"] as? JsonPrimitive)?.content?.toBooleanStrictOrNull() ?: false
|
||||
val limit = ((obj["limit"] as? JsonPrimitive)?.content?.toIntOrNull() ?: DEFAULT_SMS_LIMIT)
|
||||
.coerceIn(1, 200)
|
||||
val offset = ((obj["offset"] as? JsonPrimitive)?.content?.toIntOrNull() ?: 0)
|
||||
.coerceAtLeast(0)
|
||||
|
||||
// Validate time range
|
||||
if (startTime != null && endTime != null && startTime > endTime) {
|
||||
return QueryParseResult.Error("INVALID_REQUEST: startTime must be less than or equal to endTime")
|
||||
}
|
||||
|
||||
return QueryParseResult.Ok(
|
||||
QueryParams(
|
||||
startTime = startTime,
|
||||
endTime = endTime,
|
||||
contactName = contactName,
|
||||
phoneNumber = phoneNumber,
|
||||
keyword = keyword,
|
||||
type = type,
|
||||
isRead = isRead,
|
||||
includeMms = includeMms,
|
||||
conversationReview = conversationReview,
|
||||
limit = limit,
|
||||
offset = offset,
|
||||
)
|
||||
)
|
||||
return QueryParseResult.Ok(QueryParams(
|
||||
startTime = startTime,
|
||||
endTime = endTime,
|
||||
contactName = contactName,
|
||||
phoneNumber = phoneNumber,
|
||||
keyword = keyword,
|
||||
type = type,
|
||||
isRead = isRead,
|
||||
limit = limit,
|
||||
offset = offset,
|
||||
))
|
||||
}
|
||||
|
||||
private fun normalizePhoneNumber(phone: String): String {
|
||||
return phone.replace(PHONE_FORMATTING_REGEX, "")
|
||||
}
|
||||
|
||||
internal fun normalizePhoneNumberOrNull(phone: String?): String? {
|
||||
val normalized = phone?.let(::normalizePhoneNumber)?.trim().orEmpty()
|
||||
if (normalized.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
val digits = toByPhoneLookupNumber(normalized)
|
||||
return normalized.takeIf { digits.isNotEmpty() }
|
||||
}
|
||||
|
||||
internal fun sanitizeContactPhoneNumberOrNull(phone: String?): String? {
|
||||
val normalized = normalizePhoneNumberOrNull(phone) ?: return null
|
||||
return normalized.takeUnless(::hasSqlLikeWildcard)
|
||||
}
|
||||
|
||||
internal fun shouldPromptForContactNameSearchPermission(
|
||||
contactName: String?,
|
||||
phoneNumber: String?,
|
||||
hasReadContactsPermission: Boolean,
|
||||
): Boolean {
|
||||
return !contactName.isNullOrEmpty() && phoneNumber.isNullOrEmpty() && !hasReadContactsPermission
|
||||
}
|
||||
|
||||
internal fun mapMmsMsgBoxToSearchType(msgBox: Int?): Int? {
|
||||
return when (msgBox) {
|
||||
1 -> 1 // inbox
|
||||
2 -> 2 // sent
|
||||
3 -> 3 // draft
|
||||
4 -> 4 // outbox
|
||||
5 -> 5 // failed
|
||||
6 -> 6 // queued
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
internal fun escapeSqlLikeLiteral(value: String): String {
|
||||
return buildString(value.length) {
|
||||
for (ch in value) {
|
||||
when (ch) {
|
||||
'\\', '%', '_' -> {
|
||||
append('\\')
|
||||
append(ch)
|
||||
}
|
||||
else -> append(ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun buildContactNameLikeSelection(): String {
|
||||
return "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} LIKE ? ESCAPE '\\'"
|
||||
}
|
||||
|
||||
internal fun buildContactNameLikeArg(contactName: String): String {
|
||||
return "%${escapeSqlLikeLiteral(contactName)}%"
|
||||
}
|
||||
|
||||
internal fun buildKeywordLikeSelection(): String {
|
||||
return "${Telephony.Sms.BODY} LIKE ? ESCAPE '\\'"
|
||||
}
|
||||
|
||||
internal fun buildKeywordLikeArg(keyword: String): String {
|
||||
return "%${escapeSqlLikeLiteral(keyword)}%"
|
||||
}
|
||||
|
||||
internal fun buildMixedByPhoneProjection(): Array<String> {
|
||||
return arrayOf(
|
||||
"_id",
|
||||
"thread_id",
|
||||
"transport_type",
|
||||
"address",
|
||||
"date",
|
||||
"date_sent",
|
||||
"read",
|
||||
"type",
|
||||
"body",
|
||||
"status",
|
||||
)
|
||||
}
|
||||
|
||||
internal fun hasSqlLikeWildcard(value: String): Boolean {
|
||||
return value.contains('%') || value.contains('_')
|
||||
}
|
||||
|
||||
internal fun isExplicitPhoneInputInvalid(rawPhone: String?, normalizedPhone: String?): Boolean {
|
||||
if (rawPhone.isNullOrBlank()) {
|
||||
return false
|
||||
}
|
||||
if (normalizedPhone == null) {
|
||||
return true
|
||||
}
|
||||
return hasSqlLikeWildcard(normalizedPhone)
|
||||
}
|
||||
|
||||
internal fun resolveMixedByPhoneRowStatus(transportType: String?, smsStatus: Int?): Int {
|
||||
return if (transportType.equals("mms", ignoreCase = true)) -1 else (smsStatus ?: 0)
|
||||
}
|
||||
|
||||
internal fun resolveMixedByPhoneRowAddress(
|
||||
providerAddress: String?,
|
||||
phoneNumber: String,
|
||||
mmsAddress: String? = null,
|
||||
): String? {
|
||||
val resolvedMmsAddress = normalizePhoneNumberOrNull(mmsAddress)
|
||||
if (resolvedMmsAddress != null) {
|
||||
return resolvedMmsAddress
|
||||
}
|
||||
|
||||
val resolvedProviderAddress = normalizePhoneNumberOrNull(providerAddress)
|
||||
return resolvedProviderAddress ?: phoneNumber
|
||||
}
|
||||
|
||||
internal fun selectPreferredMmsAddress(
|
||||
addressRows: List<Pair<String?, Int?>>,
|
||||
lookupNumber: String,
|
||||
): String? {
|
||||
val lookupDigits = toByPhoneLookupNumber(lookupNumber)
|
||||
val normalizedRows = addressRows.mapNotNull { (address, type) ->
|
||||
val normalized = normalizePhoneNumberOrNull(address) ?: return@mapNotNull null
|
||||
val digits = toByPhoneLookupNumber(normalized)
|
||||
if (digits.isBlank()) return@mapNotNull null
|
||||
Triple(normalized, digits, type)
|
||||
}
|
||||
|
||||
fun firstPreferred(vararg types: Int): String? {
|
||||
return normalizedRows.firstOrNull { row ->
|
||||
(types.isEmpty() || types.contains(row.third ?: -1)) && row.second != lookupDigits
|
||||
}?.first
|
||||
}
|
||||
|
||||
return firstPreferred(137)
|
||||
?: firstPreferred(151, 130, 129)
|
||||
?: firstPreferred()
|
||||
?: normalizedRows.firstOrNull()?.first
|
||||
}
|
||||
|
||||
internal fun shouldUseConversationReviewByPhoneMode(
|
||||
params: QueryParams,
|
||||
resolvedPhoneNumbers: List<String> = emptyList(),
|
||||
): Boolean {
|
||||
val hasExplicitPhoneNumber = !params.phoneNumber.isNullOrEmpty()
|
||||
val hasSingleResolvedPhoneNumber = resolvedPhoneNumbers.size == 1
|
||||
return params.conversationReview && params.includeMms && (hasExplicitPhoneNumber || hasSingleResolvedPhoneNumber)
|
||||
}
|
||||
|
||||
internal fun effectiveSearchParams(
|
||||
params: QueryParams,
|
||||
resolvedPhoneNumbers: List<String> = emptyList(),
|
||||
): QueryParams {
|
||||
if (!shouldUseConversationReviewByPhoneMode(params, resolvedPhoneNumbers)) return params
|
||||
val reviewLimit = maxOf(params.limit, 25)
|
||||
return params.copy(limit = reviewLimit)
|
||||
}
|
||||
|
||||
internal fun resolveSearchParams(
|
||||
params: QueryParams,
|
||||
normalizedPhoneNumber: String?,
|
||||
resolvedPhoneNumbers: List<String> = emptyList(),
|
||||
): QueryParams {
|
||||
val effectivePhoneNumber = normalizedPhoneNumber ?: resolvedPhoneNumbers.singleOrNull()
|
||||
val normalizedParams = params.copy(phoneNumber = effectivePhoneNumber)
|
||||
return effectiveSearchParams(normalizedParams, resolvedPhoneNumbers)
|
||||
}
|
||||
|
||||
internal fun toByPhoneLookupNumber(phone: String): String {
|
||||
return phone.filter { it.isDigit() }
|
||||
}
|
||||
|
||||
internal fun normalizeProviderDateMillis(rawDate: Long): Long {
|
||||
return if (rawDate in 1..99_999_999_999L) rawDate * 1000L else rawDate
|
||||
}
|
||||
|
||||
internal fun canonicalizeMixedPathPhoneFilters(phoneNumbers: List<String>): List<String> {
|
||||
return phoneNumbers
|
||||
.map(::toByPhoneLookupNumber)
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
}
|
||||
|
||||
internal fun requestedMixedByPhoneCandidateWindow(params: QueryParams): Long {
|
||||
return params.offset.toLong() + params.limit.toLong()
|
||||
}
|
||||
|
||||
internal fun exceedsMixedByPhoneCandidateWindow(
|
||||
params: QueryParams,
|
||||
allPhoneNumbers: List<String>,
|
||||
): Boolean {
|
||||
return params.includeMms &&
|
||||
allPhoneNumbers.size == 1 &&
|
||||
requestedMixedByPhoneCandidateWindow(params) > MAX_MIXED_BY_PHONE_CANDIDATE_WINDOW
|
||||
}
|
||||
|
||||
internal fun mixedByPhoneWindowError(): String {
|
||||
return "INVALID_REQUEST: includeMms offset+limit exceeds supported window ($MAX_MIXED_BY_PHONE_CANDIDATE_WINDOW)"
|
||||
}
|
||||
|
||||
internal fun isMmsTransportRow(message: SmsMessage): Boolean {
|
||||
return message.transportType.equals("mms", ignoreCase = true)
|
||||
}
|
||||
|
||||
internal fun shouldHydrateMmsByPhoneRow(transportType: String?, body: String?, type: Int): Boolean {
|
||||
return transportType.equals("mms", ignoreCase = true) && (body.isNullOrBlank() || type == 0)
|
||||
}
|
||||
|
||||
internal fun buildQueryMetadata(
|
||||
params: QueryParams,
|
||||
allPhoneNumbers: List<String>,
|
||||
messages: List<SmsMessage>,
|
||||
): QueryMetadata {
|
||||
val mmsRequested = params.includeMms
|
||||
val mmsEligible = mmsRequested && allPhoneNumbers.size == 1
|
||||
val mmsAttempted = mmsEligible
|
||||
val mmsIncluded = mmsAttempted && messages.any(::isMmsTransportRow)
|
||||
return QueryMetadata(
|
||||
mmsRequested = mmsRequested,
|
||||
mmsEligible = mmsEligible,
|
||||
mmsAttempted = mmsAttempted,
|
||||
mmsIncluded = mmsIncluded,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun compareByPhoneCandidateOrder(left: SmsMessage, right: SmsMessage): Int {
|
||||
return when {
|
||||
left.date != right.date -> right.date.compareTo(left.date)
|
||||
left.id != right.id -> right.id.compareTo(left.id)
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
|
||||
internal fun buildMixedRowIdentity(rowId: Long, transportType: String?): String {
|
||||
return "${transportType?.ifBlank { "unknown" } ?: "unknown"}:$rowId"
|
||||
}
|
||||
|
||||
internal fun upsertTopDateCandidates(
|
||||
candidates: MutableList<Pair<String, SmsMessage>>,
|
||||
identityKey: String,
|
||||
message: SmsMessage,
|
||||
maxCandidates: Int,
|
||||
) {
|
||||
if (maxCandidates <= 0) {
|
||||
return
|
||||
}
|
||||
|
||||
candidates.removeAll { existing -> existing.first == identityKey }
|
||||
candidates.add(identityKey to message)
|
||||
candidates.sortWith { left, right -> compareByPhoneCandidateOrder(left.second, right.second) }
|
||||
|
||||
while (candidates.size > maxCandidates) {
|
||||
candidates.removeAt(candidates.lastIndex)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun materializeByPhoneCandidate(
|
||||
candidates: MutableMap<String, SmsMessage>,
|
||||
identityKey: String,
|
||||
message: SmsMessage,
|
||||
) {
|
||||
candidates[identityKey] = message
|
||||
}
|
||||
|
||||
internal fun collectMixedByPhoneCandidate(
|
||||
topCandidates: MutableList<Pair<String, SmsMessage>>,
|
||||
materializedCandidates: MutableMap<String, SmsMessage>,
|
||||
identityKey: String,
|
||||
message: SmsMessage,
|
||||
maxCandidates: Int,
|
||||
reviewMode: Boolean,
|
||||
) {
|
||||
if (reviewMode) {
|
||||
materializeByPhoneCandidate(materializedCandidates, identityKey, message)
|
||||
} else {
|
||||
upsertTopDateCandidates(topCandidates, identityKey, message, maxCandidates)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun pageMixedByPhoneCandidates(
|
||||
topCandidates: Collection<Pair<String, SmsMessage>>,
|
||||
materializedCandidates: Map<String, SmsMessage>,
|
||||
params: QueryParams,
|
||||
reviewMode: Boolean,
|
||||
): List<SmsMessage> {
|
||||
return if (reviewMode) {
|
||||
pageByPhoneCandidates(materializedCandidates.values, params)
|
||||
} else {
|
||||
pageByPhoneCandidates(topCandidates.map { it.second }, params)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun pageByPhoneCandidates(
|
||||
candidates: Collection<SmsMessage>,
|
||||
params: QueryParams,
|
||||
): List<SmsMessage> {
|
||||
return candidates
|
||||
.sortedWith(::compareByPhoneCandidateOrder)
|
||||
.drop(params.offset)
|
||||
.take(params.limit)
|
||||
return phone.replace(Regex("""[\s\-()]"""), "")
|
||||
}
|
||||
|
||||
internal fun buildSendPlan(
|
||||
@@ -531,21 +214,14 @@ class SmsManager(private val context: Context) {
|
||||
ok: Boolean,
|
||||
messages: List<SmsMessage>,
|
||||
error: String? = null,
|
||||
queryMetadata: QueryMetadata? = null,
|
||||
): String {
|
||||
val messagesArray = json.encodeToString(messages)
|
||||
val messagesElement = json.parseToJsonElement(messagesArray)
|
||||
val payload = mutableMapOf<String, JsonElement>(
|
||||
"ok" to JsonPrimitive(ok),
|
||||
"count" to JsonPrimitive(messages.size),
|
||||
"messages" to messagesElement,
|
||||
"messages" to messagesElement
|
||||
)
|
||||
queryMetadata?.let {
|
||||
payload["mmsRequested"] = JsonPrimitive(it.mmsRequested)
|
||||
payload["mmsEligible"] = JsonPrimitive(it.mmsEligible)
|
||||
payload["mmsAttempted"] = JsonPrimitive(it.mmsAttempted)
|
||||
payload["mmsIncluded"] = JsonPrimitive(it.mmsIncluded)
|
||||
}
|
||||
if (!ok && error != null) {
|
||||
payload["error"] = JsonPrimitive(error)
|
||||
}
|
||||
@@ -578,12 +254,8 @@ class SmsManager(private val context: Context) {
|
||||
return hasSmsPermission() && hasTelephonyFeature()
|
||||
}
|
||||
|
||||
fun canSearchSms(): Boolean {
|
||||
return hasReadSmsPermission() && hasTelephonyFeature()
|
||||
}
|
||||
|
||||
fun canReadSms(): Boolean {
|
||||
return canSearchSms()
|
||||
return hasReadSmsPermission() && hasTelephonyFeature()
|
||||
}
|
||||
|
||||
fun hasTelephonyFeature(): Boolean {
|
||||
@@ -630,19 +302,19 @@ class SmsManager(private val context: Context) {
|
||||
val plan = buildSendPlan(params.message) { smsManager.divideMessage(it) }
|
||||
if (plan.useMultipart) {
|
||||
smsManager.sendMultipartTextMessage(
|
||||
params.to,
|
||||
null,
|
||||
ArrayList(plan.parts),
|
||||
null,
|
||||
null,
|
||||
params.to, // destination
|
||||
null, // service center (null = default)
|
||||
ArrayList(plan.parts), // message parts
|
||||
null, // sent intents
|
||||
null, // delivery intents
|
||||
)
|
||||
} else {
|
||||
smsManager.sendTextMessage(
|
||||
params.to,
|
||||
null,
|
||||
params.message,
|
||||
null,
|
||||
null,
|
||||
params.to, // destination
|
||||
null, // service center (null = default)
|
||||
params.message,// message
|
||||
null, // sent intent
|
||||
null, // delivery intent
|
||||
)
|
||||
}
|
||||
|
||||
@@ -662,82 +334,6 @@ class SmsManager(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search SMS messages with the specified parameters.
|
||||
*/
|
||||
suspend fun search(paramsJson: String?): SearchResult = withContext(Dispatchers.IO) {
|
||||
if (!hasTelephonyFeature()) {
|
||||
return@withContext queryError("SMS_UNAVAILABLE: telephony not available")
|
||||
}
|
||||
|
||||
if (!ensureReadSmsPermission()) {
|
||||
return@withContext queryError("SMS_PERMISSION_REQUIRED: grant READ_SMS permission")
|
||||
}
|
||||
|
||||
val parseResult = parseQueryParams(paramsJson, json)
|
||||
if (parseResult is QueryParseResult.Error) {
|
||||
return@withContext queryError(parseResult.error)
|
||||
}
|
||||
val parsedParams = (parseResult as QueryParseResult.Ok).params
|
||||
val normalizedPhoneNumber = normalizePhoneNumberOrNull(parsedParams.phoneNumber)
|
||||
if (isExplicitPhoneInputInvalid(parsedParams.phoneNumber, normalizedPhoneNumber)) {
|
||||
val error =
|
||||
if (!parsedParams.phoneNumber.isNullOrBlank() && normalizedPhoneNumber != null && hasSqlLikeWildcard(normalizedPhoneNumber)) {
|
||||
"INVALID_REQUEST: phoneNumber must not contain SQL LIKE wildcard characters"
|
||||
} else {
|
||||
"INVALID_REQUEST: phoneNumber must contain at least one digit"
|
||||
}
|
||||
return@withContext queryError(error)
|
||||
}
|
||||
val normalizedParams = resolveSearchParams(parsedParams, normalizedPhoneNumber)
|
||||
|
||||
return@withContext try {
|
||||
val contactsPermissionGranted = hasReadContactsPermission()
|
||||
val shouldPromptForContactsPermission =
|
||||
shouldPromptForContactNameSearchPermission(
|
||||
contactName = normalizedParams.contactName,
|
||||
phoneNumber = normalizedParams.phoneNumber,
|
||||
hasReadContactsPermission = contactsPermissionGranted,
|
||||
)
|
||||
val phoneNumbers = if (!normalizedParams.contactName.isNullOrEmpty()) {
|
||||
if (contactsPermissionGranted || (shouldPromptForContactsPermission && ensureReadContactsPermission())) {
|
||||
getPhoneNumbersFromContactName(normalizedParams.contactName)
|
||||
} else if (shouldPromptForContactsPermission) {
|
||||
return@withContext queryError("CONTACTS_PERMISSION_REQUIRED: grant READ_CONTACTS permission")
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
val params = resolveSearchParams(parsedParams, normalizedPhoneNumber, phoneNumbers)
|
||||
|
||||
val mixedPathPhoneFilters = if (!params.phoneNumber.isNullOrEmpty()) {
|
||||
canonicalizeMixedPathPhoneFilters(phoneNumbers + params.phoneNumber)
|
||||
} else {
|
||||
canonicalizeMixedPathPhoneFilters(phoneNumbers)
|
||||
}
|
||||
|
||||
if (exceedsMixedByPhoneCandidateWindow(params, mixedPathPhoneFilters)) {
|
||||
val error = mixedByPhoneWindowError()
|
||||
return@withContext queryError(error)
|
||||
}
|
||||
|
||||
if (!params.contactName.isNullOrEmpty() && phoneNumbers.isEmpty() && params.phoneNumber.isNullOrEmpty()) {
|
||||
val queryMetadata = buildQueryMetadata(params, mixedPathPhoneFilters, emptyList())
|
||||
return@withContext queryOk(emptyList(), queryMetadata)
|
||||
}
|
||||
|
||||
val messages = querySmsMessages(params, phoneNumbers)
|
||||
val queryMetadata = buildQueryMetadata(params, mixedPathPhoneFilters, messages)
|
||||
queryOk(messages, queryMetadata)
|
||||
} catch (e: SecurityException) {
|
||||
queryError("SMS_PERMISSION_REQUIRED: ${e.message}")
|
||||
} catch (e: Throwable) {
|
||||
queryError("SMS_QUERY_FAILED: ${e.message ?: "unknown error"}")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun ensureSmsPermission(): Boolean {
|
||||
if (hasSmsPermission()) return true
|
||||
val requester = permissionRequester ?: return false
|
||||
@@ -779,31 +375,98 @@ class SmsManager(private val context: Context) {
|
||||
)
|
||||
}
|
||||
|
||||
private fun queryOk(
|
||||
messages: List<SmsMessage>,
|
||||
queryMetadata: QueryMetadata? = null,
|
||||
): SearchResult {
|
||||
return SearchResult(
|
||||
ok = true,
|
||||
messages = messages,
|
||||
error = null,
|
||||
payloadJson = buildQueryPayloadJson(json, ok = true, messages = messages, queryMetadata = queryMetadata),
|
||||
)
|
||||
}
|
||||
|
||||
private fun queryError(error: String): SearchResult {
|
||||
return SearchResult(
|
||||
ok = false,
|
||||
messages = emptyList(),
|
||||
error = error,
|
||||
payloadJson = buildQueryPayloadJson(json, ok = false, messages = emptyList(), error = error),
|
||||
)
|
||||
/**
|
||||
* search SMS messages with the specified parameters.
|
||||
*
|
||||
* @param paramsJson JSON with optional fields:
|
||||
* - startTime (Long): Start time in milliseconds
|
||||
* - endTime (Long): End time in milliseconds
|
||||
* - contactName (String): Contact name to search
|
||||
* - phoneNumber (String): Phone number to search (supports partial matching)
|
||||
* - keyword (String): Keyword to search in message body
|
||||
* - type (Int): SMS type (1=Inbox, 2=Sent, 3=Draft, etc.)
|
||||
* - isRead (Boolean): Read status
|
||||
* - limit (Int): Number of records to return (default: 25, range: 1-200)
|
||||
* - offset (Int): Number of records to skip (default: 0)
|
||||
* @return SearchResult containing the list of SMS messages or an error
|
||||
*/
|
||||
suspend fun search(paramsJson: String?): SearchResult = withContext(Dispatchers.IO) {
|
||||
if (!hasTelephonyFeature()) {
|
||||
return@withContext SearchResult(
|
||||
ok = false,
|
||||
messages = emptyList(),
|
||||
error = "SMS_UNAVAILABLE: telephony not available",
|
||||
payloadJson = buildQueryPayloadJson(json, ok = false, messages = emptyList(), error = "SMS_UNAVAILABLE: telephony not available")
|
||||
)
|
||||
}
|
||||
|
||||
if (!ensureReadSmsPermission()) {
|
||||
return@withContext SearchResult(
|
||||
ok = false,
|
||||
messages = emptyList(),
|
||||
error = "SMS_PERMISSION_REQUIRED: grant READ_SMS permission",
|
||||
payloadJson = buildQueryPayloadJson(json, ok = false, messages = emptyList(), error = "SMS_PERMISSION_REQUIRED: grant READ_SMS permission")
|
||||
)
|
||||
}
|
||||
|
||||
val parseResult = parseQueryParams(paramsJson, json)
|
||||
if (parseResult is QueryParseResult.Error) {
|
||||
return@withContext SearchResult(
|
||||
ok = false,
|
||||
messages = emptyList(),
|
||||
error = parseResult.error,
|
||||
payloadJson = buildQueryPayloadJson(json, ok = false, messages = emptyList(), error = parseResult.error)
|
||||
)
|
||||
}
|
||||
val params = (parseResult as QueryParseResult.Ok).params
|
||||
|
||||
return@withContext try {
|
||||
// Get phone numbers from contact name if provided
|
||||
val phoneNumbers = if (!params.contactName.isNullOrEmpty()) {
|
||||
if (!ensureReadContactsPermission()) {
|
||||
return@withContext SearchResult(
|
||||
ok = false,
|
||||
messages = emptyList(),
|
||||
error = "CONTACTS_PERMISSION_REQUIRED: grant READ_CONTACTS permission",
|
||||
payloadJson = buildQueryPayloadJson(json, ok = false, messages = emptyList(), error = "CONTACTS_PERMISSION_REQUIRED: grant READ_CONTACTS permission")
|
||||
)
|
||||
}
|
||||
getPhoneNumbersFromContactName(params.contactName)
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
val messages = querySmsMessages(params, phoneNumbers)
|
||||
SearchResult(
|
||||
ok = true,
|
||||
messages = messages,
|
||||
error = null,
|
||||
payloadJson = buildQueryPayloadJson(json, ok = true, messages = messages)
|
||||
)
|
||||
} catch (e: SecurityException) {
|
||||
SearchResult(
|
||||
ok = false,
|
||||
messages = emptyList(),
|
||||
error = "SMS_PERMISSION_REQUIRED: ${e.message}",
|
||||
payloadJson = buildQueryPayloadJson(json, ok = false, messages = emptyList(), error = "SMS_PERMISSION_REQUIRED: ${e.message}")
|
||||
)
|
||||
} catch (e: Throwable) {
|
||||
SearchResult(
|
||||
ok = false,
|
||||
messages = emptyList(),
|
||||
error = "SMS_QUERY_FAILED: ${e.message ?: "unknown error"}",
|
||||
payloadJson = buildQueryPayloadJson(json, ok = false, messages = emptyList(), error = "SMS_QUERY_FAILED: ${e.message ?: "unknown error"}")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all phone numbers associated with a contact name
|
||||
*/
|
||||
private fun getPhoneNumbersFromContactName(contactName: String): List<String> {
|
||||
val phoneNumbers = mutableListOf<String>()
|
||||
val selection = buildContactNameLikeSelection()
|
||||
val selectionArgs = arrayOf(buildContactNameLikeArg(contactName))
|
||||
val selection = "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} LIKE ?"
|
||||
val selectionArgs = arrayOf("%$contactName%")
|
||||
|
||||
val cursor = context.contentResolver.query(
|
||||
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
|
||||
@@ -817,19 +480,26 @@ class SmsManager(private val context: Context) {
|
||||
val numberIndex = it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
|
||||
while (it.moveToNext()) {
|
||||
val number = it.getString(numberIndex)
|
||||
sanitizeContactPhoneNumberOrNull(number)?.let(phoneNumbers::add)
|
||||
if (!number.isNullOrBlank()) {
|
||||
phoneNumbers.add(normalizePhoneNumber(number))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return phoneNumbers
|
||||
}
|
||||
|
||||
/**
|
||||
* Query SMS messages based on the provided parameters
|
||||
*/
|
||||
private fun querySmsMessages(params: QueryParams, phoneNumbers: List<String>): List<SmsMessage> {
|
||||
val messages = mutableListOf<SmsMessage>()
|
||||
|
||||
// Build selection and selectionArgs
|
||||
val selections = mutableListOf<String>()
|
||||
val selectionArgs = mutableListOf<String>()
|
||||
|
||||
// Time range
|
||||
if (params.startTime != null) {
|
||||
selections.add("${Telephony.Sms.DATE} >= ?")
|
||||
selectionArgs.add(params.startTime.toString())
|
||||
@@ -839,17 +509,11 @@ class SmsManager(private val context: Context) {
|
||||
selectionArgs.add(params.endTime.toString())
|
||||
}
|
||||
|
||||
// Phone numbers (from contact name or direct phone number)
|
||||
val allPhoneNumbers = if (!params.phoneNumber.isNullOrEmpty()) {
|
||||
(phoneNumbers + normalizePhoneNumber(params.phoneNumber)).distinct()
|
||||
phoneNumbers + normalizePhoneNumber(params.phoneNumber)
|
||||
} else {
|
||||
phoneNumbers.distinct()
|
||||
}
|
||||
val mixedPathPhoneFilters = canonicalizeMixedPathPhoneFilters(allPhoneNumbers)
|
||||
|
||||
// Unified SMS+MMS query path is opt-in to keep sms.search semantics
|
||||
// stable by default. Use includeMms=true for by-phone provider behavior.
|
||||
if (params.includeMms && mixedPathPhoneFilters.size == 1) {
|
||||
return querySmsMmsMessagesByPhone(mixedPathPhoneFilters.first(), params)
|
||||
phoneNumbers
|
||||
}
|
||||
|
||||
if (allPhoneNumbers.isNotEmpty()) {
|
||||
@@ -862,16 +526,19 @@ class SmsManager(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// Keyword in body
|
||||
if (!params.keyword.isNullOrEmpty()) {
|
||||
selections.add(buildKeywordLikeSelection())
|
||||
selectionArgs.add(buildKeywordLikeArg(params.keyword))
|
||||
selections.add("${Telephony.Sms.BODY} LIKE ?")
|
||||
selectionArgs.add("%${params.keyword}%")
|
||||
}
|
||||
|
||||
// Type
|
||||
if (params.type != null) {
|
||||
selections.add("${Telephony.Sms.TYPE} = ?")
|
||||
selectionArgs.add(params.type.toString())
|
||||
}
|
||||
|
||||
// Read status
|
||||
if (params.isRead != null) {
|
||||
selections.add("${Telephony.Sms.READ} = ?")
|
||||
selectionArgs.add(if (params.isRead) "1" else "0")
|
||||
@@ -889,8 +556,7 @@ class SmsManager(private val context: Context) {
|
||||
null
|
||||
}
|
||||
|
||||
// Android SMS providers still honor LIMIT/OFFSET through sortOrder on this path.
|
||||
// Keep the bounded interpolation here because parseQueryParams already clamps both values.
|
||||
// Query SMS with SQL-level LIMIT and OFFSET to avoid loading all matching rows
|
||||
val sortOrder = "${Telephony.Sms.DATE} DESC LIMIT ${params.limit} OFFSET ${params.offset}"
|
||||
val cursor = context.contentResolver.query(
|
||||
Telephony.Sms.CONTENT_URI,
|
||||
@@ -904,7 +570,7 @@ class SmsManager(private val context: Context) {
|
||||
Telephony.Sms.READ,
|
||||
Telephony.Sms.TYPE,
|
||||
Telephony.Sms.BODY,
|
||||
Telephony.Sms.STATUS,
|
||||
Telephony.Sms.STATUS
|
||||
),
|
||||
selection,
|
||||
selectionArgsArray,
|
||||
@@ -935,7 +601,7 @@ class SmsManager(private val context: Context) {
|
||||
read = it.getInt(readIndex) == 1,
|
||||
type = it.getInt(typeIndex),
|
||||
body = it.getString(bodyIndex),
|
||||
status = it.getInt(statusIndex),
|
||||
status = it.getInt(statusIndex)
|
||||
)
|
||||
messages.add(message)
|
||||
count++
|
||||
@@ -944,184 +610,4 @@ class SmsManager(private val context: Context) {
|
||||
|
||||
return messages
|
||||
}
|
||||
|
||||
private fun querySmsMmsMessagesByPhone(phoneNumber: String, params: QueryParams): List<SmsMessage> {
|
||||
val lookupNumber = toByPhoneLookupNumber(phoneNumber)
|
||||
if (lookupNumber.isBlank()) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
val uri = Uri.parse("$MMS_SMS_BY_PHONE_BASE/${Uri.encode(lookupNumber)}")
|
||||
val projection = buildMixedByPhoneProjection()
|
||||
|
||||
val maxCandidates = params.offset + params.limit
|
||||
if (maxCandidates <= 0) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
val reviewMode = shouldUseConversationReviewByPhoneMode(params)
|
||||
val topCandidates = mutableListOf<Pair<String, SmsMessage>>()
|
||||
val materializedCandidates = linkedMapOf<String, SmsMessage>()
|
||||
val cursor = context.contentResolver.query(uri, projection, null, null, "date DESC")
|
||||
cursor?.use {
|
||||
val idIndex = it.getColumnIndex("_id")
|
||||
val threadIdIndex = it.getColumnIndex("thread_id")
|
||||
val transportTypeIndex = it.getColumnIndex("transport_type")
|
||||
val addressIndex = it.getColumnIndex("address")
|
||||
val dateIndex = it.getColumnIndex("date")
|
||||
val dateSentIndex = it.getColumnIndex("date_sent")
|
||||
val readIndex = it.getColumnIndex("read")
|
||||
val typeIndex = it.getColumnIndex("type")
|
||||
val bodyIndex = it.getColumnIndex("body")
|
||||
val statusIndex = it.getColumnIndex("status")
|
||||
|
||||
while (it.moveToNext()) {
|
||||
val id = if (idIndex >= 0 && !it.isNull(idIndex)) it.getLong(idIndex) else continue
|
||||
val rawDate = if (dateIndex >= 0 && !it.isNull(dateIndex)) it.getLong(dateIndex) else 0L
|
||||
val dateMs = normalizeProviderDateMillis(rawDate)
|
||||
|
||||
if (params.startTime != null && dateMs < params.startTime) continue
|
||||
if (params.endTime != null && dateMs > params.endTime) continue
|
||||
|
||||
val threadId = if (threadIdIndex >= 0 && !it.isNull(threadIdIndex)) it.getLong(threadIdIndex) else 0L
|
||||
val transportType = if (transportTypeIndex >= 0 && !it.isNull(transportTypeIndex)) it.getString(transportTypeIndex) else null
|
||||
val providerAddress = if (addressIndex >= 0 && !it.isNull(addressIndex)) it.getString(addressIndex) else null
|
||||
val mmsAddress = if (transportType.equals("mms", ignoreCase = true)) getMmsAddress(id, phoneNumber) else null
|
||||
val address = resolveMixedByPhoneRowAddress(providerAddress, phoneNumber, mmsAddress)
|
||||
var read = if (readIndex >= 0 && !it.isNull(readIndex)) it.getInt(readIndex) == 1 else true
|
||||
var type = if (typeIndex >= 0 && !it.isNull(typeIndex)) it.getInt(typeIndex) else 0
|
||||
var body = if (bodyIndex >= 0 && !it.isNull(bodyIndex)) it.getString(bodyIndex) else null
|
||||
val smsStatus = if (statusIndex >= 0 && !it.isNull(statusIndex)) it.getInt(statusIndex) else null
|
||||
|
||||
// Only MMS transport rows are allowed to hydrate from MMS storage.
|
||||
if (shouldHydrateMmsByPhoneRow(transportType, body, type)) {
|
||||
body = body?.takeIf { msg -> msg.isNotBlank() } ?: getMmsTextBody(id)
|
||||
val mmsMeta = getMmsMeta(id)
|
||||
if (type == 0) {
|
||||
type = mmsMeta.first ?: type
|
||||
}
|
||||
if (readIndex < 0 || it.isNull(readIndex)) {
|
||||
read = mmsMeta.second ?: read
|
||||
}
|
||||
}
|
||||
|
||||
val dateSentRaw = if (dateSentIndex >= 0 && !it.isNull(dateSentIndex)) it.getLong(dateSentIndex) else 0L
|
||||
val dateSentMs = normalizeProviderDateMillis(dateSentRaw)
|
||||
|
||||
if (!params.keyword.isNullOrEmpty()) {
|
||||
val keyword = params.keyword
|
||||
if (body.isNullOrEmpty() || !body.contains(keyword, ignoreCase = true)) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (params.type != null && type != params.type) continue
|
||||
if (params.isRead != null && read != params.isRead) continue
|
||||
|
||||
val message = SmsMessage(
|
||||
id = id,
|
||||
threadId = threadId,
|
||||
address = address,
|
||||
person = null,
|
||||
date = dateMs,
|
||||
dateSent = dateSentMs,
|
||||
read = read,
|
||||
type = type,
|
||||
body = body,
|
||||
status = resolveMixedByPhoneRowStatus(transportType, smsStatus),
|
||||
transportType = transportType,
|
||||
)
|
||||
val identityKey = buildMixedRowIdentity(id, transportType)
|
||||
collectMixedByPhoneCandidate(
|
||||
topCandidates = topCandidates,
|
||||
materializedCandidates = materializedCandidates,
|
||||
identityKey = identityKey,
|
||||
message = message,
|
||||
maxCandidates = maxCandidates,
|
||||
reviewMode = reviewMode,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return pageMixedByPhoneCandidates(
|
||||
topCandidates = topCandidates,
|
||||
materializedCandidates = materializedCandidates,
|
||||
params = params,
|
||||
reviewMode = reviewMode,
|
||||
)
|
||||
}
|
||||
|
||||
private fun getMmsTextBody(messageId: Long): String? {
|
||||
val cursor = context.contentResolver.query(
|
||||
Uri.parse(MMS_PART_URI),
|
||||
arrayOf("text", "ct"),
|
||||
"mid=?",
|
||||
arrayOf(messageId.toString()),
|
||||
null,
|
||||
)
|
||||
|
||||
cursor?.use {
|
||||
val textIndex = it.getColumnIndex("text")
|
||||
val ctIndex = it.getColumnIndex("ct")
|
||||
while (it.moveToNext()) {
|
||||
val contentType = if (ctIndex >= 0 && !it.isNull(ctIndex)) it.getString(ctIndex) else null
|
||||
if (contentType != null && contentType != "text/plain") continue
|
||||
val text = if (textIndex >= 0 && !it.isNull(textIndex)) it.getString(textIndex) else null
|
||||
if (!text.isNullOrBlank()) return text
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
private fun getMmsMeta(messageId: Long): Pair<Int?, Boolean?> {
|
||||
val cursor = context.contentResolver.query(
|
||||
Uri.parse("$MMS_CONTENT_BASE/$messageId"),
|
||||
arrayOf("msg_box", "read"),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
|
||||
cursor?.use {
|
||||
if (it.moveToFirst()) {
|
||||
val msgBoxIndex = it.getColumnIndex("msg_box")
|
||||
val readIndex = it.getColumnIndex("read")
|
||||
val msgBox = if (msgBoxIndex >= 0 && !it.isNull(msgBoxIndex)) it.getInt(msgBoxIndex) else null
|
||||
val mappedType = mapMmsMsgBoxToSearchType(msgBox)
|
||||
val read = if (readIndex >= 0 && !it.isNull(readIndex)) it.getInt(readIndex) == 1 else null
|
||||
return mappedType to read
|
||||
}
|
||||
}
|
||||
|
||||
return null to null
|
||||
}
|
||||
|
||||
private fun getMmsAddress(messageId: Long, phoneNumber: String): String? {
|
||||
val lookupNumber = toByPhoneLookupNumber(phoneNumber)
|
||||
if (lookupNumber.isBlank()) {
|
||||
return null
|
||||
}
|
||||
|
||||
val cursor = context.contentResolver.query(
|
||||
Uri.parse("$MMS_CONTENT_BASE/$messageId/addr"),
|
||||
arrayOf("address", "type"),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
|
||||
cursor?.use {
|
||||
val addressIndex = it.getColumnIndex("address")
|
||||
val typeIndex = it.getColumnIndex("type")
|
||||
val addressRows = mutableListOf<Pair<String?, Int?>>()
|
||||
while (it.moveToNext()) {
|
||||
val address = if (addressIndex >= 0 && !it.isNull(addressIndex)) it.getString(addressIndex) else null
|
||||
val type = if (typeIndex >= 0 && !it.isNull(typeIndex)) it.getInt(typeIndex) else null
|
||||
addressRows.add(address to type)
|
||||
}
|
||||
return selectPreferredMmsAddress(addressRows, lookupNumber)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,12 +58,9 @@ object OpenClawCanvasA2UIAction {
|
||||
}
|
||||
|
||||
fun jsDispatchA2UIActionStatus(actionId: String, ok: Boolean, error: String?): String {
|
||||
val err = jsonStringLiteral(error ?: "")
|
||||
val err = (error ?: "").replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
val okLiteral = if (ok) "true" else "false"
|
||||
val idLiteral = jsonStringLiteral(actionId)
|
||||
return "window.dispatchEvent(new CustomEvent('openclaw:a2ui-action-status', { detail: { id: ${idLiteral}, ok: ${okLiteral}, error: ${err} } }));"
|
||||
val idEscaped = actionId.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
return "window.dispatchEvent(new CustomEvent('openclaw:a2ui-action-status', { detail: { id: \"${idEscaped}\", ok: ${okLiteral}, error: \"${err}\" } }));"
|
||||
}
|
||||
|
||||
private fun jsonStringLiteral(raw: String): String =
|
||||
JsonPrimitive(raw).toString().replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.webkit.WebSettingsCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import ai.openclaw.app.MainViewModel
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
@@ -30,7 +29,6 @@ fun CanvasScreen(viewModel: MainViewModel, visible: Boolean, modifier: Modifier
|
||||
val context = LocalContext.current
|
||||
val isDebuggable = (context.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) != 0
|
||||
val webViewRef = remember { mutableStateOf<WebView?>(null) }
|
||||
val currentPageUrlRef = remember { AtomicReference<String?>(null) }
|
||||
|
||||
DisposableEffect(viewModel) {
|
||||
onDispose {
|
||||
@@ -70,14 +68,6 @@ fun CanvasScreen(viewModel: MainViewModel, visible: Boolean, modifier: Modifier
|
||||
isHorizontalScrollBarEnabled = true
|
||||
webViewClient =
|
||||
object : WebViewClient() {
|
||||
override fun onPageStarted(
|
||||
view: WebView,
|
||||
url: String?,
|
||||
favicon: android.graphics.Bitmap?,
|
||||
) {
|
||||
currentPageUrlRef.set(url)
|
||||
}
|
||||
|
||||
override fun onReceivedError(
|
||||
view: WebView,
|
||||
request: WebResourceRequest,
|
||||
@@ -100,7 +90,6 @@ fun CanvasScreen(viewModel: MainViewModel, visible: Boolean, modifier: Modifier
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView, url: String?) {
|
||||
currentPageUrlRef.set(url)
|
||||
if (isDebuggable) {
|
||||
Log.d("OpenClawWebView", "onPageFinished: $url")
|
||||
}
|
||||
@@ -133,12 +122,7 @@ fun CanvasScreen(viewModel: MainViewModel, visible: Boolean, modifier: Modifier
|
||||
}
|
||||
}
|
||||
|
||||
val bridge =
|
||||
CanvasA2UIActionBridge(
|
||||
isTrustedPage = { viewModel.isTrustedCanvasActionUrl(currentPageUrlRef.get()) },
|
||||
) { payload ->
|
||||
viewModel.handleCanvasA2UIActionFromWebView(payload)
|
||||
}
|
||||
val bridge = CanvasA2UIActionBridge { payload -> viewModel.handleCanvasA2UIActionFromWebView(payload) }
|
||||
addJavascriptInterface(bridge, CanvasA2UIActionBridge.interfaceName)
|
||||
viewModel.canvas.attach(this)
|
||||
webViewRef.value = this
|
||||
@@ -163,15 +147,11 @@ private fun disableForceDarkIfSupported(settings: WebSettings) {
|
||||
WebSettingsCompat.setForceDark(settings, WebSettingsCompat.FORCE_DARK_OFF)
|
||||
}
|
||||
|
||||
private class CanvasA2UIActionBridge(
|
||||
private val isTrustedPage: () -> Boolean,
|
||||
private val onMessage: (String) -> Unit,
|
||||
) {
|
||||
private class CanvasA2UIActionBridge(private val onMessage: (String) -> Unit) {
|
||||
@JavascriptInterface
|
||||
fun postMessage(payload: String?) {
|
||||
val msg = payload?.trim().orEmpty()
|
||||
if (msg.isEmpty()) return
|
||||
if (!isTrustedPage()) return
|
||||
onMessage(msg)
|
||||
}
|
||||
|
||||
|
||||
@@ -97,25 +97,8 @@ internal fun parseGatewayEndpoint(rawInput: String): GatewayEndpointConfig? {
|
||||
"wss", "https" -> true
|
||||
else -> true
|
||||
}
|
||||
val defaultPort =
|
||||
when (scheme) {
|
||||
"wss", "https" -> 443
|
||||
"ws", "http" -> 18789
|
||||
else -> 443
|
||||
}
|
||||
val displayPort =
|
||||
when (scheme) {
|
||||
"wss", "https" -> 443
|
||||
"ws", "http" -> 80
|
||||
else -> 443
|
||||
}
|
||||
val port = uri.port.takeIf { it in 1..65535 } ?: defaultPort
|
||||
val displayUrl =
|
||||
if (port == displayPort && defaultPort == displayPort) {
|
||||
"${if (tls) "https" else "http"}://$host"
|
||||
} else {
|
||||
"${if (tls) "https" else "http"}://$host:$port"
|
||||
}
|
||||
val port = uri.port.takeIf { it in 1..65535 } ?: if (tls) 443 else 18789
|
||||
val displayUrl = "${if (tls) "https" else "http"}://$host:$port"
|
||||
|
||||
return GatewayEndpointConfig(host = host, port = port, tls = tls, displayUrl = displayUrl)
|
||||
}
|
||||
|
||||
@@ -1459,8 +1459,8 @@ private fun PermissionsStep(
|
||||
subtitle = "Send and search text messages via the gateway",
|
||||
checked = enableSms,
|
||||
granted =
|
||||
isPermissionGranted(context, Manifest.permission.SEND_SMS) ||
|
||||
isPermissionGranted(context, Manifest.permission.READ_SMS),
|
||||
isPermissionGranted(context, Manifest.permission.SEND_SMS) &&
|
||||
isPermissionGranted(context, Manifest.permission.READ_SMS),
|
||||
onCheckedChange = onSmsChange,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
package ai.openclaw.app.ui
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.core.view.WindowCompat
|
||||
|
||||
@Composable
|
||||
fun OpenClawTheme(content: @Composable () -> Unit) {
|
||||
@@ -20,15 +16,6 @@ fun OpenClawTheme(content: @Composable () -> Unit) {
|
||||
val colorScheme = if (isDark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||
val mobileColors = if (isDark) darkMobileColors() else lightMobileColors()
|
||||
|
||||
val view = LocalView.current
|
||||
if (!view.isInEditMode) {
|
||||
SideEffect {
|
||||
val window = (view.context as Activity).window
|
||||
WindowCompat.getInsetsController(window, window.decorView)
|
||||
.isAppearanceLightStatusBars = !isDark
|
||||
}
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalMobileColors provides mobileColors) {
|
||||
MaterialTheme(colorScheme = colorScheme, content = content)
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -53,23 +54,20 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import ai.openclaw.app.BuildConfig
|
||||
import ai.openclaw.app.LocationMode
|
||||
import ai.openclaw.app.MainViewModel
|
||||
import ai.openclaw.app.normalizeLocalHourMinute
|
||||
import ai.openclaw.app.NotificationPackageFilterMode
|
||||
import ai.openclaw.app.node.DeviceNotificationListenerService
|
||||
|
||||
@Composable
|
||||
@@ -83,55 +81,6 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
val locationPreciseEnabled by viewModel.locationPreciseEnabled.collectAsState()
|
||||
val preventSleep by viewModel.preventSleep.collectAsState()
|
||||
val canvasDebugStatusEnabled by viewModel.canvasDebugStatusEnabled.collectAsState()
|
||||
val notificationForwardingEnabled by viewModel.notificationForwardingEnabled.collectAsState()
|
||||
val notificationForwardingMode by viewModel.notificationForwardingMode.collectAsState()
|
||||
val notificationForwardingPackages by viewModel.notificationForwardingPackages.collectAsState()
|
||||
val notificationForwardingQuietHoursEnabled by viewModel.notificationForwardingQuietHoursEnabled.collectAsState()
|
||||
val notificationForwardingQuietStart by viewModel.notificationForwardingQuietStart.collectAsState()
|
||||
val notificationForwardingQuietEnd by viewModel.notificationForwardingQuietEnd.collectAsState()
|
||||
val notificationForwardingMaxEventsPerMinute by viewModel.notificationForwardingMaxEventsPerMinute.collectAsState()
|
||||
val notificationForwardingSessionKey by viewModel.notificationForwardingSessionKey.collectAsState()
|
||||
|
||||
var notificationQuietStartDraft by remember(notificationForwardingQuietStart) {
|
||||
mutableStateOf(notificationForwardingQuietStart)
|
||||
}
|
||||
var notificationQuietEndDraft by remember(notificationForwardingQuietEnd) {
|
||||
mutableStateOf(notificationForwardingQuietEnd)
|
||||
}
|
||||
var notificationRateDraft by remember(notificationForwardingMaxEventsPerMinute) {
|
||||
mutableStateOf(notificationForwardingMaxEventsPerMinute.toString())
|
||||
}
|
||||
var notificationSessionKeyDraft by remember(notificationForwardingSessionKey) {
|
||||
mutableStateOf(notificationForwardingSessionKey.orEmpty())
|
||||
}
|
||||
val normalizedQuietStartDraft = remember(notificationQuietStartDraft) {
|
||||
normalizeLocalHourMinute(notificationQuietStartDraft)
|
||||
}
|
||||
val normalizedQuietEndDraft = remember(notificationQuietEndDraft) {
|
||||
normalizeLocalHourMinute(notificationQuietEndDraft)
|
||||
}
|
||||
val quietHoursDraftValid = normalizedQuietStartDraft != null && normalizedQuietEndDraft != null
|
||||
val selectedPackagesSummary = remember(notificationForwardingMode, notificationForwardingPackages) {
|
||||
when (notificationForwardingMode) {
|
||||
NotificationPackageFilterMode.Allowlist ->
|
||||
if (notificationForwardingPackages.isEmpty()) {
|
||||
"Selected: none — allowlist mode forwards nothing until you add apps."
|
||||
} else {
|
||||
"Selected: ${notificationForwardingPackages.size} app(s) allowed."
|
||||
}
|
||||
NotificationPackageFilterMode.Blocklist ->
|
||||
if (notificationForwardingPackages.isEmpty()) {
|
||||
"Selected: none — blocklist mode forwards all apps except OpenClaw."
|
||||
} else {
|
||||
"Selected: ${notificationForwardingPackages.size} app(s) blocked."
|
||||
}
|
||||
}
|
||||
}
|
||||
val quietHoursCanEnable = notificationForwardingEnabled && quietHoursDraftValid
|
||||
val quietHoursDraftDirty =
|
||||
notificationForwardingQuietStart != (normalizedQuietStartDraft ?: notificationQuietStartDraft.trim()) ||
|
||||
notificationForwardingQuietEnd != (normalizedQuietEndDraft ?: notificationQuietEndDraft.trim())
|
||||
val quietHoursSaveEnabled = notificationForwardingEnabled && quietHoursDraftValid && quietHoursDraftDirty
|
||||
|
||||
val listState = rememberLazyListState()
|
||||
val deviceModel =
|
||||
@@ -226,16 +175,6 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
remember {
|
||||
mutableStateOf(isNotificationListenerEnabled(context))
|
||||
}
|
||||
val notificationForwardingAvailable = notificationForwardingEnabled && notificationListenerEnabled
|
||||
val notificationForwardingControlsAlpha = if (notificationForwardingAvailable) 1f else 0.6f
|
||||
|
||||
var notificationPickerExpanded by remember { mutableStateOf(false) }
|
||||
var notificationAppSearch by remember { mutableStateOf("") }
|
||||
var notificationShowSystemApps by remember { mutableStateOf(false) }
|
||||
var installedNotificationApps by
|
||||
remember(context, notificationForwardingPackages) {
|
||||
mutableStateOf(queryInstalledApps(context, notificationForwardingPackages))
|
||||
}
|
||||
|
||||
var photosPermissionGranted by
|
||||
remember {
|
||||
@@ -310,19 +249,16 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
remember {
|
||||
mutableStateOf(
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) ==
|
||||
PackageManager.PERMISSION_GRANTED ||
|
||||
PackageManager.PERMISSION_GRANTED &&
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) ==
|
||||
PackageManager.PERMISSION_GRANTED,
|
||||
)
|
||||
}
|
||||
val smsPermissionLauncher =
|
||||
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||
smsPermissionGranted =
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
||
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { perms ->
|
||||
val sendOk = perms[Manifest.permission.SEND_SMS] == true
|
||||
val readOk = perms[Manifest.permission.READ_SMS] == true
|
||||
smsPermissionGranted = sendOk && readOk
|
||||
viewModel.refreshGatewayConnection()
|
||||
}
|
||||
|
||||
@@ -335,7 +271,6 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
notificationsPermissionGranted = hasNotificationsPermission(context)
|
||||
notificationListenerEnabled = isNotificationListenerEnabled(context)
|
||||
installedNotificationApps = queryInstalledApps(context, notificationForwardingPackages)
|
||||
photosPermissionGranted =
|
||||
ContextCompat.checkSelfPermission(context, photosPermission) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
@@ -358,8 +293,7 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
smsPermissionGranted =
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
||
|
||||
PackageManager.PERMISSION_GRANTED &&
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
@@ -417,20 +351,6 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
}
|
||||
}
|
||||
|
||||
val normalizedAppSearch = notificationAppSearch.trim().lowercase()
|
||||
val filteredNotificationApps =
|
||||
remember(installedNotificationApps, normalizedAppSearch, notificationShowSystemApps) {
|
||||
installedNotificationApps
|
||||
.asSequence()
|
||||
.filter { app -> notificationShowSystemApps || !app.isSystemApp }
|
||||
.filter { app ->
|
||||
normalizedAppSearch.isEmpty() ||
|
||||
app.label.lowercase().contains(normalizedAppSearch) ||
|
||||
app.packageName.lowercase().contains(normalizedAppSearch)
|
||||
}
|
||||
.toList()
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
@@ -571,12 +491,9 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = listItemColors,
|
||||
headlineContent = { Text("Notification Listener Access", style = mobileHeadline) },
|
||||
headlineContent = { Text("Notification Listener", style = mobileHeadline) },
|
||||
supportingContent = {
|
||||
Text(
|
||||
"Required for `notifications.list`, `notifications.actions`, and forwarded notification events.",
|
||||
style = mobileCallout,
|
||||
)
|
||||
Text("Read and interact with notifications.", style = mobileCallout)
|
||||
},
|
||||
trailingContent = {
|
||||
Button(
|
||||
@@ -613,11 +530,7 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text(
|
||||
if (smsPermissionGranted) {
|
||||
"Manage"
|
||||
} else {
|
||||
"Grant"
|
||||
},
|
||||
if (smsPermissionGranted) "Manage" else "Grant",
|
||||
style = mobileCallout.copy(fontWeight = FontWeight.Bold),
|
||||
)
|
||||
}
|
||||
@@ -626,297 +539,6 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
ListItem(
|
||||
modifier = Modifier.settingsRowModifier(),
|
||||
colors = listItemColors,
|
||||
headlineContent = { Text("Forward Notification Events", style = mobileHeadline) },
|
||||
supportingContent = {
|
||||
Text(
|
||||
if (notificationListenerEnabled) {
|
||||
"Forward listener events into gateway node events. Off by default until you enable it."
|
||||
} else {
|
||||
"Notification listener access is off, so no notification events can be forwarded yet."
|
||||
},
|
||||
style = mobileCallout,
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
Switch(
|
||||
checked = notificationForwardingEnabled,
|
||||
onCheckedChange = viewModel::setNotificationForwardingEnabled,
|
||||
enabled = notificationListenerEnabled,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
item {
|
||||
Text(
|
||||
if (notificationListenerEnabled) {
|
||||
"Forwarding is available when enabled below."
|
||||
} else {
|
||||
"Forwarding controls stay disabled until Notification Listener Access is enabled in system Settings."
|
||||
},
|
||||
style = mobileCallout,
|
||||
color = mobileTextSecondary,
|
||||
)
|
||||
}
|
||||
item {
|
||||
Column(
|
||||
modifier = Modifier.settingsRowModifier().alpha(notificationForwardingControlsAlpha),
|
||||
verticalArrangement = Arrangement.spacedBy(0.dp),
|
||||
) {
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = listItemColors,
|
||||
headlineContent = { Text("Package Filter: Allowlist", style = mobileHeadline) },
|
||||
supportingContent = {
|
||||
Text("Only listed package IDs are forwarded.", style = mobileCallout)
|
||||
},
|
||||
trailingContent = {
|
||||
RadioButton(
|
||||
selected = notificationForwardingMode == NotificationPackageFilterMode.Allowlist,
|
||||
onClick = {
|
||||
viewModel.setNotificationForwardingMode(NotificationPackageFilterMode.Allowlist)
|
||||
},
|
||||
enabled = notificationForwardingAvailable,
|
||||
)
|
||||
},
|
||||
)
|
||||
HorizontalDivider(color = mobileBorder)
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = listItemColors,
|
||||
headlineContent = { Text("Package Filter: Blocklist", style = mobileHeadline) },
|
||||
supportingContent = {
|
||||
Text("All packages except listed IDs are forwarded.", style = mobileCallout)
|
||||
},
|
||||
trailingContent = {
|
||||
RadioButton(
|
||||
selected = notificationForwardingMode == NotificationPackageFilterMode.Blocklist,
|
||||
onClick = {
|
||||
viewModel.setNotificationForwardingMode(NotificationPackageFilterMode.Blocklist)
|
||||
},
|
||||
enabled = notificationForwardingAvailable,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
item {
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Button(
|
||||
onClick = { notificationPickerExpanded = !notificationPickerExpanded },
|
||||
enabled = notificationForwardingAvailable,
|
||||
colors = settingsPrimaryButtonColors(),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text(
|
||||
if (notificationPickerExpanded) "Close App Picker" else "Open App Picker",
|
||||
style = mobileCallout.copy(fontWeight = FontWeight.Bold),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Text(
|
||||
selectedPackagesSummary,
|
||||
style = mobileCallout,
|
||||
color = mobileTextSecondary,
|
||||
)
|
||||
}
|
||||
if (notificationPickerExpanded) {
|
||||
item {
|
||||
OutlinedTextField(
|
||||
value = notificationAppSearch,
|
||||
onValueChange = { notificationAppSearch = it },
|
||||
label = {
|
||||
Text("Search apps", style = mobileCaption1, color = mobileTextSecondary)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = mobileBody.copy(color = mobileText),
|
||||
colors = settingsTextFieldColors(),
|
||||
enabled = notificationForwardingAvailable,
|
||||
)
|
||||
}
|
||||
item {
|
||||
ListItem(
|
||||
modifier = Modifier.settingsRowModifier().alpha(notificationForwardingControlsAlpha),
|
||||
colors = listItemColors,
|
||||
headlineContent = { Text("Show System Apps", style = mobileHeadline) },
|
||||
supportingContent = {
|
||||
Text("Include Android/system packages in results.", style = mobileCallout)
|
||||
},
|
||||
trailingContent = {
|
||||
Switch(
|
||||
checked = notificationShowSystemApps,
|
||||
onCheckedChange = { notificationShowSystemApps = it },
|
||||
enabled = notificationForwardingAvailable,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
items(filteredNotificationApps, key = { it.packageName }) { app ->
|
||||
ListItem(
|
||||
modifier = Modifier.settingsRowModifier().alpha(notificationForwardingControlsAlpha),
|
||||
colors = listItemColors,
|
||||
headlineContent = { Text(app.label, style = mobileHeadline) },
|
||||
supportingContent = { Text(app.packageName, style = mobileCallout) },
|
||||
trailingContent = {
|
||||
Switch(
|
||||
checked = notificationForwardingPackages.contains(app.packageName),
|
||||
onCheckedChange = { checked ->
|
||||
val next = notificationForwardingPackages.toMutableSet()
|
||||
if (checked) {
|
||||
next.add(app.packageName)
|
||||
} else {
|
||||
next.remove(app.packageName)
|
||||
}
|
||||
viewModel.setNotificationForwardingPackagesCsv(next.sorted().joinToString(","))
|
||||
},
|
||||
enabled = notificationForwardingAvailable,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
item {
|
||||
ListItem(
|
||||
modifier = Modifier.settingsRowModifier().alpha(notificationForwardingControlsAlpha),
|
||||
colors = listItemColors,
|
||||
headlineContent = { Text("Quiet Hours", style = mobileHeadline) },
|
||||
supportingContent = {
|
||||
Text("Suppress forwarding during a local time window.", style = mobileCallout)
|
||||
},
|
||||
trailingContent = {
|
||||
Switch(
|
||||
checked = notificationForwardingQuietHoursEnabled,
|
||||
onCheckedChange = {
|
||||
if (!quietHoursCanEnable && it) return@Switch
|
||||
viewModel.setNotificationForwardingQuietHours(
|
||||
enabled = it,
|
||||
start = notificationQuietStartDraft,
|
||||
end = notificationQuietEndDraft,
|
||||
)
|
||||
},
|
||||
enabled = if (notificationForwardingQuietHoursEnabled) notificationForwardingAvailable else quietHoursCanEnable,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
item {
|
||||
OutlinedTextField(
|
||||
value = notificationQuietStartDraft,
|
||||
onValueChange = { notificationQuietStartDraft = it },
|
||||
label = { Text("Quiet Start (HH:mm)", style = mobileCaption1, color = mobileTextSecondary) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = mobileBody.copy(color = mobileText),
|
||||
colors = settingsTextFieldColors(),
|
||||
enabled = notificationForwardingAvailable,
|
||||
isError = notificationForwardingAvailable && normalizedQuietStartDraft == null,
|
||||
supportingText = {
|
||||
if (notificationForwardingAvailable && normalizedQuietStartDraft == null) {
|
||||
Text("Use 24-hour HH:mm format, for example 22:00.", style = mobileCaption1, color = mobileDanger)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
item {
|
||||
OutlinedTextField(
|
||||
value = notificationQuietEndDraft,
|
||||
onValueChange = { notificationQuietEndDraft = it },
|
||||
label = { Text("Quiet End (HH:mm)", style = mobileCaption1, color = mobileTextSecondary) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = mobileBody.copy(color = mobileText),
|
||||
colors = settingsTextFieldColors(),
|
||||
enabled = notificationForwardingAvailable,
|
||||
isError = notificationForwardingAvailable && normalizedQuietEndDraft == null,
|
||||
supportingText = {
|
||||
if (notificationForwardingAvailable && normalizedQuietEndDraft == null) {
|
||||
Text("Use 24-hour HH:mm format, for example 07:00.", style = mobileCaption1, color = mobileDanger)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
item {
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Button(
|
||||
onClick = {
|
||||
viewModel.setNotificationForwardingQuietHours(
|
||||
enabled = notificationForwardingQuietHoursEnabled,
|
||||
start = notificationQuietStartDraft,
|
||||
end = notificationQuietEndDraft,
|
||||
)
|
||||
},
|
||||
enabled = quietHoursSaveEnabled,
|
||||
colors = settingsPrimaryButtonColors(),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text("Save Quiet Hours", style = mobileCallout.copy(fontWeight = FontWeight.Bold))
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
OutlinedTextField(
|
||||
value = notificationRateDraft,
|
||||
onValueChange = { notificationRateDraft = it.filter { c -> c.isDigit() } },
|
||||
label = { Text("Max Events / Minute", style = mobileCaption1, color = mobileTextSecondary) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = mobileBody.copy(color = mobileText),
|
||||
colors = settingsTextFieldColors(),
|
||||
enabled = notificationForwardingAvailable,
|
||||
)
|
||||
}
|
||||
item {
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Button(
|
||||
onClick = {
|
||||
val parsed = notificationRateDraft.toIntOrNull() ?: notificationForwardingMaxEventsPerMinute
|
||||
viewModel.setNotificationForwardingMaxEventsPerMinute(parsed)
|
||||
},
|
||||
enabled = notificationForwardingAvailable,
|
||||
colors = settingsPrimaryButtonColors(),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text("Save Rate", style = mobileCallout.copy(fontWeight = FontWeight.Bold))
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
OutlinedTextField(
|
||||
value = notificationSessionKeyDraft,
|
||||
onValueChange = { notificationSessionKeyDraft = it },
|
||||
label = {
|
||||
Text(
|
||||
"Route Session Key (optional)",
|
||||
style = mobileCaption1,
|
||||
color = mobileTextSecondary,
|
||||
)
|
||||
},
|
||||
placeholder = {
|
||||
Text("Blank keeps notification events on this device's default notification route. Set a key only to pin forwarding into a different session.", style = mobileCaption1, color = mobileTextSecondary)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = mobileBody.copy(color = mobileText),
|
||||
colors = settingsTextFieldColors(),
|
||||
enabled = notificationForwardingAvailable,
|
||||
)
|
||||
}
|
||||
item {
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Button(
|
||||
onClick = {
|
||||
viewModel.setNotificationForwardingSessionKey(notificationSessionKeyDraft.trim().ifEmpty { null })
|
||||
},
|
||||
enabled = notificationForwardingAvailable,
|
||||
colors = settingsPrimaryButtonColors(),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text("Save Session Route", style = mobileCallout.copy(fontWeight = FontWeight.Bold))
|
||||
}
|
||||
}
|
||||
}
|
||||
item { HorizontalDivider(color = mobileBorder) }
|
||||
|
||||
// ── Data Access ──
|
||||
item {
|
||||
@@ -1152,78 +774,6 @@ fun SettingsSheet(viewModel: MainViewModel) {
|
||||
}
|
||||
}
|
||||
|
||||
data class InstalledApp(
|
||||
val label: String,
|
||||
val packageName: String,
|
||||
val isSystemApp: Boolean,
|
||||
)
|
||||
|
||||
private fun queryInstalledApps(
|
||||
context: Context,
|
||||
configuredPackages: Set<String>,
|
||||
): List<InstalledApp> {
|
||||
val packageManager = context.packageManager
|
||||
val launcherIntent = Intent(Intent.ACTION_MAIN).apply { addCategory(Intent.CATEGORY_LAUNCHER) }
|
||||
|
||||
val launcherPackages =
|
||||
packageManager
|
||||
.queryIntentActivities(launcherIntent, PackageManager.MATCH_ALL)
|
||||
.asSequence()
|
||||
.mapNotNull { it.activityInfo?.packageName?.trim()?.takeIf(String::isNotEmpty) }
|
||||
.toMutableSet()
|
||||
|
||||
val recentNotificationPackages =
|
||||
DeviceNotificationListenerService
|
||||
.recentPackages(context)
|
||||
.asSequence()
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.toList()
|
||||
|
||||
val candidatePackages =
|
||||
resolveNotificationCandidatePackages(
|
||||
launcherPackages = launcherPackages,
|
||||
recentPackages = recentNotificationPackages,
|
||||
configuredPackages = configuredPackages,
|
||||
appPackageName = context.packageName,
|
||||
)
|
||||
|
||||
return candidatePackages
|
||||
.asSequence()
|
||||
.mapNotNull { packageName ->
|
||||
runCatching {
|
||||
val appInfo = packageManager.getApplicationInfo(packageName, 0)
|
||||
val label = packageManager.getApplicationLabel(appInfo)?.toString()?.trim().orEmpty()
|
||||
InstalledApp(
|
||||
label = if (label.isEmpty()) packageName else label,
|
||||
packageName = packageName,
|
||||
isSystemApp = (appInfo.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM) != 0,
|
||||
)
|
||||
}.getOrNull()
|
||||
}
|
||||
.sortedWith(compareBy<InstalledApp> { it.label.lowercase() }.thenBy { it.packageName })
|
||||
.toList()
|
||||
}
|
||||
|
||||
internal fun resolveNotificationCandidatePackages(
|
||||
launcherPackages: Set<String>,
|
||||
recentPackages: List<String>,
|
||||
configuredPackages: Set<String>,
|
||||
appPackageName: String,
|
||||
): Set<String> {
|
||||
val blockedPackage = appPackageName.trim()
|
||||
return sequenceOf(
|
||||
configuredPackages.asSequence(),
|
||||
launcherPackages.asSequence(),
|
||||
recentPackages.asSequence(),
|
||||
)
|
||||
.flatten()
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() && it != blockedPackage }
|
||||
.toSet()
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun settingsTextFieldColors() =
|
||||
OutlinedTextFieldDefaults.colors(
|
||||
@@ -1292,5 +842,5 @@ private fun isNotificationListenerEnabled(context: Context): Boolean {
|
||||
private fun hasMotionCapabilities(context: Context): Boolean {
|
||||
val sensorManager = context.getSystemService(SensorManager::class.java) ?: return false
|
||||
return sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null ||
|
||||
sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) != null
|
||||
sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) != null
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ fun ChatSheetContent(viewModel: MainViewModel) {
|
||||
val pendingToolCalls by viewModel.chatPendingToolCalls.collectAsState()
|
||||
val sessions by viewModel.chatSessions.collectAsState()
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
LaunchedEffect(mainSessionKey) {
|
||||
viewModel.loadChat(mainSessionKey)
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,6 @@ class MicCaptureManager(
|
||||
private const val speechMinSessionMs = 30_000L
|
||||
private const val speechCompleteSilenceMs = 1_500L
|
||||
private const val speechPossibleSilenceMs = 900L
|
||||
private const val transcriptIdleFlushMs = 1_600L
|
||||
private const val maxConversationEntries = 40
|
||||
private const val pendingRunTimeoutMs = 45_000L
|
||||
}
|
||||
@@ -88,7 +87,8 @@ class MicCaptureManager(
|
||||
val isSending: StateFlow<Boolean> = _isSending
|
||||
|
||||
private val messageQueue = ArrayDeque<String>()
|
||||
private var flushedPartialTranscript: String? = null
|
||||
private val sessionSegments = mutableListOf<String>()
|
||||
private var lastFinalSegment: String? = null
|
||||
private var pendingRunId: String? = null
|
||||
private var pendingAssistantEntryId: String? = null
|
||||
private var gatewayConnected = false
|
||||
@@ -96,7 +96,6 @@ class MicCaptureManager(
|
||||
private var recognizer: SpeechRecognizer? = null
|
||||
private var restartJob: Job? = null
|
||||
private var drainJob: Job? = null
|
||||
private var transcriptFlushJob: Job? = null
|
||||
private var pendingRunTimeoutJob: Job? = null
|
||||
private var stopRequested = false
|
||||
|
||||
@@ -116,9 +115,10 @@ class MicCaptureManager(
|
||||
stop()
|
||||
// Capture any partial transcript that didn't get a final result from the recognizer
|
||||
val partial = _liveTranscript.value?.trim().orEmpty()
|
||||
if (partial.isNotEmpty()) {
|
||||
queueRecognizedMessage(partial)
|
||||
if (partial.isNotEmpty() && sessionSegments.isEmpty()) {
|
||||
sessionSegments.add(partial)
|
||||
}
|
||||
flushSessionToQueue()
|
||||
drainJob = null
|
||||
_micCooldown.value = false
|
||||
sendQueuedIfIdle()
|
||||
@@ -132,11 +132,6 @@ class MicCaptureManager(
|
||||
sendQueuedIfIdle()
|
||||
return
|
||||
}
|
||||
pendingRunTimeoutJob?.cancel()
|
||||
pendingRunTimeoutJob = null
|
||||
pendingRunId = null
|
||||
pendingAssistantEntryId = null
|
||||
_isSending.value = false
|
||||
if (messageQueue.isNotEmpty()) {
|
||||
_statusText.value = queuedWaitingStatus()
|
||||
}
|
||||
@@ -215,8 +210,6 @@ class MicCaptureManager(
|
||||
stopRequested = true
|
||||
restartJob?.cancel()
|
||||
restartJob = null
|
||||
transcriptFlushJob?.cancel()
|
||||
transcriptFlushJob = null
|
||||
_isListening.value = false
|
||||
_statusText.value = if (_isSending.value) "Mic off · sending…" else "Mic off"
|
||||
_inputLevel.value = 0f
|
||||
@@ -270,10 +263,17 @@ class MicCaptureManager(
|
||||
}
|
||||
}
|
||||
|
||||
private fun queueRecognizedMessage(text: String) {
|
||||
val message = text.trim()
|
||||
private fun flushSessionToQueue() {
|
||||
// Add sentence-ending punctuation between recognizer segments to avoid run-on text
|
||||
val message = sessionSegments.joinToString(". ") { segment ->
|
||||
val trimmed = segment.trimEnd()
|
||||
if (trimmed.isNotEmpty() && trimmed.last() in ".!?,;:") trimmed else trimmed
|
||||
}.trim().let { if (it.isNotEmpty() && it.last() !in ".!?") "$it." else it }
|
||||
sessionSegments.clear()
|
||||
_liveTranscript.value = null
|
||||
lastFinalSegment = null
|
||||
if (message.isEmpty()) return
|
||||
|
||||
appendConversation(
|
||||
role = VoiceConversationRole.User,
|
||||
text = message,
|
||||
@@ -282,20 +282,6 @@ class MicCaptureManager(
|
||||
publishQueue()
|
||||
}
|
||||
|
||||
private fun scheduleTranscriptFlush(expectedText: String) {
|
||||
transcriptFlushJob?.cancel()
|
||||
transcriptFlushJob =
|
||||
scope.launch {
|
||||
delay(transcriptIdleFlushMs)
|
||||
if (!_micEnabled.value || _isSending.value) return@launch
|
||||
val current = _liveTranscript.value?.trim().orEmpty()
|
||||
if (current.isEmpty() || current != expectedText) return@launch
|
||||
flushedPartialTranscript = current
|
||||
queueRecognizedMessage(current)
|
||||
sendQueuedIfIdle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun publishQueue() {
|
||||
_queuedMessages.value = messageQueue.toList()
|
||||
}
|
||||
@@ -450,12 +436,19 @@ class MicCaptureManager(
|
||||
}
|
||||
}
|
||||
|
||||
private fun onFinalTranscript(text: String) {
|
||||
val trimmed = text.trim()
|
||||
if (trimmed.isEmpty()) return
|
||||
_liveTranscript.value = trimmed
|
||||
if (lastFinalSegment == trimmed) return
|
||||
lastFinalSegment = trimmed
|
||||
sessionSegments.add(trimmed)
|
||||
}
|
||||
|
||||
private fun disableMic(status: String) {
|
||||
stopRequested = true
|
||||
restartJob?.cancel()
|
||||
restartJob = null
|
||||
transcriptFlushJob?.cancel()
|
||||
transcriptFlushJob = null
|
||||
_micEnabled.value = false
|
||||
_isListening.value = false
|
||||
_inputLevel.value = 0f
|
||||
@@ -553,18 +546,11 @@ class MicCaptureManager(
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
transcriptFlushJob?.cancel()
|
||||
transcriptFlushJob = null
|
||||
val text = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION).orEmpty().firstOrNull()
|
||||
if (!text.isNullOrBlank()) {
|
||||
val trimmed = text.trim()
|
||||
if (trimmed != flushedPartialTranscript) {
|
||||
queueRecognizedMessage(trimmed)
|
||||
sendQueuedIfIdle()
|
||||
} else {
|
||||
flushedPartialTranscript = null
|
||||
_liveTranscript.value = null
|
||||
}
|
||||
onFinalTranscript(text)
|
||||
// Don't auto-send on silence — accumulate transcript.
|
||||
// Send happens when mic is toggled off (setMicEnabled(false)).
|
||||
}
|
||||
scheduleRestart()
|
||||
}
|
||||
@@ -572,9 +558,7 @@ class MicCaptureManager(
|
||||
override fun onPartialResults(partialResults: Bundle?) {
|
||||
val text = partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION).orEmpty().firstOrNull()
|
||||
if (!text.isNullOrBlank()) {
|
||||
val trimmed = text.trim()
|
||||
_liveTranscript.value = trimmed
|
||||
scheduleTranscriptFlush(trimmed)
|
||||
_liveTranscript.value = text.trim()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import android.content.pm.PackageManager
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFocusRequest
|
||||
import android.media.AudioManager
|
||||
import android.media.MediaPlayer
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
@@ -14,12 +15,12 @@ import android.os.SystemClock
|
||||
import android.speech.RecognitionListener
|
||||
import android.speech.RecognizerIntent
|
||||
import android.speech.SpeechRecognizer
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import android.speech.tts.TextToSpeech
|
||||
import android.speech.tts.UtteranceProgressListener
|
||||
import androidx.core.content.ContextCompat
|
||||
import ai.openclaw.app.gateway.GatewaySession
|
||||
import java.util.Locale
|
||||
import ai.openclaw.app.isCanonicalMainSessionKey
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlinx.coroutines.CancellationException
|
||||
@@ -85,6 +86,8 @@ class TalkModeManager(
|
||||
private var lastSpokenText: String? = null
|
||||
private var lastInterruptedAtSeconds: Double? = null
|
||||
|
||||
private var currentVoiceId: String? = null
|
||||
private var currentModelId: String? = null
|
||||
// Interrupt-on-speech is disabled by default: starting a SpeechRecognizer during
|
||||
// TTS creates an audio session conflict on some OEMs. Can be enabled via gateway talk config.
|
||||
private var interruptOnSpeech: Boolean = false
|
||||
@@ -101,10 +104,7 @@ class TalkModeManager(
|
||||
private val playbackGeneration = AtomicLong(0L)
|
||||
|
||||
private var ttsJob: Job? = null
|
||||
private val ttsLock = Any()
|
||||
private var textToSpeech: TextToSpeech? = null
|
||||
private var textToSpeechInit: CompletableDeferred<TextToSpeech>? = null
|
||||
@Volatile private var currentUtteranceId: String? = null
|
||||
private var player: MediaPlayer? = null
|
||||
@Volatile private var finalizeInFlight = false
|
||||
private var listenWatchdogJob: Job? = null
|
||||
|
||||
@@ -130,6 +130,7 @@ class TalkModeManager(
|
||||
fun setMainSessionKey(sessionKey: String?) {
|
||||
val trimmed = sessionKey?.trim().orEmpty()
|
||||
if (trimmed.isEmpty()) return
|
||||
if (isCanonicalMainSessionKey(mainSessionKey)) return
|
||||
mainSessionKey = trimmed
|
||||
}
|
||||
|
||||
@@ -338,7 +339,6 @@ class TalkModeManager(
|
||||
recognizer?.destroy()
|
||||
recognizer = null
|
||||
}
|
||||
shutdownTextToSpeech()
|
||||
}
|
||||
|
||||
private fun startListeningInternal(markListening: Boolean) {
|
||||
@@ -646,6 +646,19 @@ class TalkModeManager(
|
||||
val cleaned = parsed.stripped.trim()
|
||||
if (cleaned.isEmpty()) return
|
||||
_lastAssistantText.value = cleaned
|
||||
|
||||
val requestedVoice = directive?.voiceId?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
if (directive?.voiceId != null) {
|
||||
if (directive.once != true) {
|
||||
currentVoiceId = requestedVoice
|
||||
}
|
||||
}
|
||||
if (directive?.modelId != null) {
|
||||
if (directive.once != true) {
|
||||
currentModelId = directive.modelId?.trim()?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
}
|
||||
ensurePlaybackActive(playbackToken)
|
||||
|
||||
_statusText.value = "Speaking…"
|
||||
@@ -656,98 +669,145 @@ class TalkModeManager(
|
||||
|
||||
try {
|
||||
val ttsStarted = SystemClock.elapsedRealtime()
|
||||
speakWithSystemTts(cleaned, directive, playbackToken)
|
||||
Log.d(tag, "system tts ok durMs=${SystemClock.elapsedRealtime() - ttsStarted}")
|
||||
val speech = requestTalkSpeak(cleaned, directive)
|
||||
playGatewaySpeech(speech, playbackToken)
|
||||
Log.d(tag, "talk.speak ok durMs=${SystemClock.elapsedRealtime() - ttsStarted} provider=${speech.provider}")
|
||||
} catch (err: Throwable) {
|
||||
if (isPlaybackCancelled(err, playbackToken)) {
|
||||
Log.d(tag, "assistant speech cancelled")
|
||||
return
|
||||
}
|
||||
_statusText.value = "Speak failed: ${err.message ?: err::class.simpleName}"
|
||||
Log.w(tag, "system tts failed: ${err.message ?: err::class.simpleName}")
|
||||
Log.w(tag, "talk.speak failed: ${err.message ?: err::class.simpleName}")
|
||||
} finally {
|
||||
|
||||
_isSpeaking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun speakWithSystemTts(text: String, directive: TalkDirective?, playbackToken: Long) {
|
||||
ensurePlaybackActive(playbackToken)
|
||||
val engine = ensureTextToSpeech()
|
||||
val utteranceId = UUID.randomUUID().toString()
|
||||
val finished = CompletableDeferred<Unit>()
|
||||
withContext(Dispatchers.Main) {
|
||||
ensurePlaybackActive(playbackToken)
|
||||
synchronized(ttsLock) {
|
||||
currentUtteranceId = utteranceId
|
||||
engine.stop()
|
||||
}
|
||||
val locale =
|
||||
TalkModeRuntime.validatedLanguage(directive?.language)?.let { Locale.forLanguageTag(it) }
|
||||
if (locale != null) {
|
||||
val localeResult = engine.setLanguage(locale)
|
||||
if (
|
||||
localeResult == TextToSpeech.LANG_MISSING_DATA ||
|
||||
localeResult == TextToSpeech.LANG_NOT_SUPPORTED
|
||||
) {
|
||||
throw IllegalStateException("Language unavailable on this device")
|
||||
private data class GatewayTalkSpeech(
|
||||
val audioBase64: String,
|
||||
val provider: String,
|
||||
val outputFormat: String?,
|
||||
val mimeType: String?,
|
||||
val fileExtension: String?,
|
||||
)
|
||||
|
||||
private suspend fun requestTalkSpeak(text: String, directive: TalkDirective?): GatewayTalkSpeech {
|
||||
val modelId =
|
||||
directive?.modelId?.trim()?.takeIf { it.isNotEmpty() } ?: currentModelId?.trim()?.takeIf { it.isNotEmpty() }
|
||||
val voiceId =
|
||||
directive?.voiceId?.trim()?.takeIf { it.isNotEmpty() } ?: currentVoiceId?.trim()?.takeIf { it.isNotEmpty() }
|
||||
val params =
|
||||
buildJsonObject {
|
||||
put("text", JsonPrimitive(text))
|
||||
voiceId?.let { put("voiceId", JsonPrimitive(it)) }
|
||||
modelId?.let { put("modelId", JsonPrimitive(it)) }
|
||||
TalkModeRuntime.resolveSpeed(directive?.speed, directive?.rateWpm)?.let {
|
||||
put("speed", JsonPrimitive(it))
|
||||
}
|
||||
TalkModeRuntime.validatedStability(directive?.stability, modelId)?.let {
|
||||
put("stability", JsonPrimitive(it))
|
||||
}
|
||||
TalkModeRuntime.validatedUnit(directive?.similarity)?.let {
|
||||
put("similarity", JsonPrimitive(it))
|
||||
}
|
||||
TalkModeRuntime.validatedUnit(directive?.style)?.let {
|
||||
put("style", JsonPrimitive(it))
|
||||
}
|
||||
directive?.speakerBoost?.let { put("speakerBoost", JsonPrimitive(it)) }
|
||||
TalkModeRuntime.validatedSeed(directive?.seed)?.let { put("seed", JsonPrimitive(it)) }
|
||||
TalkModeRuntime.validatedNormalize(directive?.normalize)?.let {
|
||||
put("normalize", JsonPrimitive(it))
|
||||
}
|
||||
TalkModeRuntime.validatedLanguage(directive?.language)?.let {
|
||||
put("language", JsonPrimitive(it))
|
||||
}
|
||||
directive?.outputFormat?.trim()?.takeIf { it.isNotEmpty() }?.let {
|
||||
put("outputFormat", JsonPrimitive(it))
|
||||
}
|
||||
}
|
||||
engine.setSpeechRate((TalkModeRuntime.resolveSpeed(directive?.speed, directive?.rateWpm) ?: 1.0).toFloat())
|
||||
engine.setAudioAttributes(
|
||||
val res = session.request("talk.speak", params.toString())
|
||||
val root = json.parseToJsonElement(res).asObjectOrNull() ?: error("talk.speak returned invalid JSON")
|
||||
val audioBase64 = root["audioBase64"].asStringOrNull()?.trim().orEmpty()
|
||||
val provider = root["provider"].asStringOrNull()?.trim().orEmpty()
|
||||
if (audioBase64.isEmpty()) {
|
||||
error("talk.speak missing audioBase64")
|
||||
}
|
||||
if (provider.isEmpty()) {
|
||||
error("talk.speak missing provider")
|
||||
}
|
||||
return GatewayTalkSpeech(
|
||||
audioBase64 = audioBase64,
|
||||
provider = provider,
|
||||
outputFormat = root["outputFormat"].asStringOrNull()?.trim(),
|
||||
mimeType = root["mimeType"].asStringOrNull()?.trim(),
|
||||
fileExtension = root["fileExtension"].asStringOrNull()?.trim(),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun playGatewaySpeech(speech: GatewayTalkSpeech, playbackToken: Long) {
|
||||
ensurePlaybackActive(playbackToken)
|
||||
cleanupPlayer()
|
||||
ensurePlaybackActive(playbackToken)
|
||||
|
||||
val audioBytes =
|
||||
try {
|
||||
Base64.decode(speech.audioBase64, Base64.DEFAULT)
|
||||
} catch (err: IllegalArgumentException) {
|
||||
throw IllegalStateException("talk.speak returned invalid audio", err)
|
||||
}
|
||||
val suffix = resolveGatewayAudioSuffix(speech)
|
||||
val tempFile =
|
||||
withContext(Dispatchers.IO) { File.createTempFile("tts_", suffix, context.cacheDir) }
|
||||
try {
|
||||
withContext(Dispatchers.IO) { tempFile.writeBytes(audioBytes) }
|
||||
val player = MediaPlayer()
|
||||
this.player = player
|
||||
val finished = CompletableDeferred<Unit>()
|
||||
player.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.build(),
|
||||
)
|
||||
engine.setOnUtteranceProgressListener(
|
||||
object : UtteranceProgressListener() {
|
||||
override fun onStart(utteranceId: String?) = Unit
|
||||
|
||||
override fun onDone(utteranceId: String?) {
|
||||
if (utteranceId == currentUtteranceId) {
|
||||
finished.complete(Unit)
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun onError(utteranceId: String?) {
|
||||
if (utteranceId == currentUtteranceId) {
|
||||
finished.completeExceptionally(IllegalStateException("TextToSpeech playback failed"))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(utteranceId: String?, errorCode: Int) {
|
||||
if (utteranceId == currentUtteranceId) {
|
||||
finished.completeExceptionally(IllegalStateException("TextToSpeech playback failed ($errorCode)"))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStop(utteranceId: String?, interrupted: Boolean) {
|
||||
if (utteranceId == currentUtteranceId) {
|
||||
finished.completeExceptionally(CancellationException("assistant speech cancelled"))
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
val result = engine.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId)
|
||||
if (result != TextToSpeech.SUCCESS) {
|
||||
throw IllegalStateException("TextToSpeech start failed")
|
||||
player.setOnCompletionListener { finished.complete(Unit) }
|
||||
player.setOnErrorListener { _, what, extra ->
|
||||
finished.completeExceptionally(IllegalStateException("MediaPlayer error what=$what extra=$extra"))
|
||||
true
|
||||
}
|
||||
}
|
||||
try {
|
||||
player.setDataSource(tempFile.absolutePath)
|
||||
withContext(Dispatchers.IO) { player.prepare() }
|
||||
ensurePlaybackActive(playbackToken)
|
||||
player.start()
|
||||
finished.await()
|
||||
ensurePlaybackActive(playbackToken)
|
||||
} finally {
|
||||
synchronized(ttsLock) {
|
||||
if (currentUtteranceId == utteranceId) {
|
||||
currentUtteranceId = null
|
||||
}
|
||||
}
|
||||
try {
|
||||
cleanupPlayer()
|
||||
} catch (_: Throwable) {}
|
||||
tempFile.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveGatewayAudioSuffix(speech: GatewayTalkSpeech): String {
|
||||
val extension = speech.fileExtension?.trim()
|
||||
if (!extension.isNullOrEmpty()) {
|
||||
return if (extension.startsWith(".")) extension else ".$extension"
|
||||
}
|
||||
val mimeType = speech.mimeType?.trim()?.lowercase()
|
||||
if (mimeType == "audio/mpeg") return ".mp3"
|
||||
if (mimeType == "audio/ogg") return ".ogg"
|
||||
if (mimeType == "audio/wav") return ".wav"
|
||||
if (mimeType == "audio/webm") return ".webm"
|
||||
val outputFormat = speech.outputFormat?.trim()?.lowercase().orEmpty()
|
||||
if (outputFormat == "mp3" || outputFormat.startsWith("mp3_") || outputFormat.endsWith("-mp3")) return ".mp3"
|
||||
if (outputFormat == "opus" || outputFormat.startsWith("opus_")) return ".ogg"
|
||||
if (outputFormat.endsWith("-wav")) return ".wav"
|
||||
if (outputFormat.endsWith("-webm")) return ".webm"
|
||||
return ".audio"
|
||||
}
|
||||
|
||||
fun stopTts() {
|
||||
stopSpeaking(resetInterrupt = true)
|
||||
_isSpeaking.value = false
|
||||
@@ -756,14 +816,15 @@ class TalkModeManager(
|
||||
|
||||
private fun stopSpeaking(resetInterrupt: Boolean = true) {
|
||||
if (!_isSpeaking.value) {
|
||||
stopTextToSpeechPlayback()
|
||||
cleanupPlayer()
|
||||
abandonAudioFocus()
|
||||
return
|
||||
}
|
||||
if (resetInterrupt) {
|
||||
lastInterruptedAtSeconds = null
|
||||
val currentMs = player?.currentPosition?.toDouble() ?: 0.0
|
||||
lastInterruptedAtSeconds = currentMs / 1000.0
|
||||
}
|
||||
stopTextToSpeechPlayback()
|
||||
cleanupPlayer()
|
||||
_isSpeaking.value = false
|
||||
abandonAudioFocus()
|
||||
}
|
||||
@@ -803,80 +864,10 @@ class TalkModeManager(
|
||||
audioFocusRequest = null
|
||||
}
|
||||
|
||||
private suspend fun ensureTextToSpeech(): TextToSpeech {
|
||||
val existing = synchronized(ttsLock) { textToSpeech }
|
||||
if (existing != null) {
|
||||
return existing
|
||||
}
|
||||
val deferred: CompletableDeferred<TextToSpeech>
|
||||
val created: Boolean
|
||||
synchronized(ttsLock) {
|
||||
val ready = textToSpeech
|
||||
if (ready != null) {
|
||||
deferred = CompletableDeferred<TextToSpeech>().also { it.complete(ready) }
|
||||
created = false
|
||||
} else {
|
||||
val pending = textToSpeechInit
|
||||
if (pending != null) {
|
||||
deferred = pending
|
||||
created = false
|
||||
} else {
|
||||
deferred = CompletableDeferred<TextToSpeech>()
|
||||
textToSpeechInit = deferred
|
||||
created = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!created) {
|
||||
return deferred.await()
|
||||
}
|
||||
withContext(Dispatchers.Main) {
|
||||
synchronized(ttsLock) {
|
||||
textToSpeech?.let {
|
||||
textToSpeechInit = null
|
||||
deferred.complete(it)
|
||||
return@withContext
|
||||
}
|
||||
}
|
||||
var engine: TextToSpeech? = null
|
||||
engine = TextToSpeech(context) { status ->
|
||||
if (status == TextToSpeech.SUCCESS) {
|
||||
val initialized = engine ?: run {
|
||||
deferred.completeExceptionally(IllegalStateException("TextToSpeech init failed"))
|
||||
return@TextToSpeech
|
||||
}
|
||||
synchronized(ttsLock) {
|
||||
textToSpeech = initialized
|
||||
textToSpeechInit = null
|
||||
}
|
||||
deferred.complete(initialized)
|
||||
} else {
|
||||
synchronized(ttsLock) {
|
||||
textToSpeechInit = null
|
||||
}
|
||||
engine?.shutdown()
|
||||
deferred.completeExceptionally(IllegalStateException("TextToSpeech init failed ($status)"))
|
||||
}
|
||||
}
|
||||
}
|
||||
return deferred.await()
|
||||
}
|
||||
|
||||
private fun stopTextToSpeechPlayback() {
|
||||
synchronized(ttsLock) {
|
||||
currentUtteranceId = null
|
||||
textToSpeech?.stop()
|
||||
}
|
||||
}
|
||||
|
||||
private fun shutdownTextToSpeech() {
|
||||
synchronized(ttsLock) {
|
||||
currentUtteranceId = null
|
||||
textToSpeech?.stop()
|
||||
textToSpeech?.shutdown()
|
||||
textToSpeech = null
|
||||
textToSpeechInit = null
|
||||
}
|
||||
private fun cleanupPlayer() {
|
||||
player?.stop()
|
||||
player?.release()
|
||||
player = null
|
||||
}
|
||||
|
||||
private fun shouldInterrupt(transcript: String): Boolean {
|
||||
@@ -909,6 +900,9 @@ class TalkModeManager(
|
||||
val res = session.request("talk.config", "{}")
|
||||
val root = json.parseToJsonElement(res).asObjectOrNull()
|
||||
val parsed = TalkModeGatewayConfigParser.parse(root?.get("config").asObjectOrNull())
|
||||
if (!isCanonicalMainSessionKey(mainSessionKey)) {
|
||||
mainSessionKey = parsed.mainSessionKey
|
||||
}
|
||||
silenceWindowMs = parsed.silenceTimeoutMs
|
||||
parsed.interruptOnSpeech?.let { interruptOnSpeech = it }
|
||||
configLoaded = true
|
||||
@@ -937,6 +931,32 @@ class TalkModeManager(
|
||||
return null
|
||||
}
|
||||
|
||||
fun validatedUnit(value: Double?): Double? {
|
||||
if (value == null) return null
|
||||
if (value < 0 || value > 1) return null
|
||||
return value
|
||||
}
|
||||
|
||||
fun validatedStability(value: Double?, modelId: String?): Double? {
|
||||
if (value == null) return null
|
||||
val normalized = modelId?.trim()?.lowercase()
|
||||
if (normalized == "eleven_v3") {
|
||||
return if (value == 0.0 || value == 0.5 || value == 1.0) value else null
|
||||
}
|
||||
return validatedUnit(value)
|
||||
}
|
||||
|
||||
fun validatedSeed(value: Long?): Long? {
|
||||
if (value == null) return null
|
||||
if (value < 0 || value > 4294967295L) return null
|
||||
return value
|
||||
}
|
||||
|
||||
fun validatedNormalize(value: String?): String? {
|
||||
val normalized = value?.trim()?.lowercase() ?: return null
|
||||
return if (normalized in listOf("auto", "on", "off")) normalized else null
|
||||
}
|
||||
|
||||
fun validatedLanguage(value: String?): String? {
|
||||
val normalized = value?.trim()?.lowercase() ?: return null
|
||||
if (normalized.length != 2) return null
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
package ai.openclaw.app
|
||||
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneId
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class NotificationForwardingPolicyTest {
|
||||
@Test
|
||||
fun parseLocalHourMinute_parsesValidValues() {
|
||||
assertEquals(0, parseLocalHourMinute("00:00"))
|
||||
assertEquals(23 * 60 + 59, parseLocalHourMinute("23:59"))
|
||||
assertEquals(7 * 60 + 5, parseLocalHourMinute("07:05"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeLocalHourMinute_acceptsStrict24HourDrafts() {
|
||||
assertEquals("00:00", normalizeLocalHourMinute("00:00"))
|
||||
assertEquals("23:59", normalizeLocalHourMinute("23:59"))
|
||||
assertEquals("07:05", normalizeLocalHourMinute("07:05"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseLocalHourMinute_rejectsInvalidValues() {
|
||||
assertEquals(null, parseLocalHourMinute(""))
|
||||
assertEquals(null, parseLocalHourMinute("24:00"))
|
||||
assertEquals(null, parseLocalHourMinute("12:60"))
|
||||
assertEquals(null, parseLocalHourMinute("abc"))
|
||||
assertEquals(null, parseLocalHourMinute("7:05"))
|
||||
assertEquals(null, parseLocalHourMinute("07:5"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeLocalHourMinute_rejectsNonCanonicalDrafts() {
|
||||
assertEquals(null, normalizeLocalHourMinute(""))
|
||||
assertEquals(null, normalizeLocalHourMinute("7:05"))
|
||||
assertEquals(null, normalizeLocalHourMinute("07:5"))
|
||||
assertEquals(null, normalizeLocalHourMinute("24:00"))
|
||||
assertEquals(null, normalizeLocalHourMinute("12:60"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun allowsPackage_blocklistBlocksConfiguredPackages() {
|
||||
val policy =
|
||||
NotificationForwardingPolicy(
|
||||
enabled = true,
|
||||
mode = NotificationPackageFilterMode.Blocklist,
|
||||
packages = setOf("com.blocked.app"),
|
||||
quietHoursEnabled = false,
|
||||
quietStart = "22:00",
|
||||
quietEnd = "07:00",
|
||||
maxEventsPerMinute = 20,
|
||||
sessionKey = null,
|
||||
)
|
||||
|
||||
assertFalse(policy.allowsPackage("com.blocked.app"))
|
||||
assertTrue(policy.allowsPackage("com.allowed.app"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun allowsPackage_allowlistOnlyAllowsConfiguredPackages() {
|
||||
val policy =
|
||||
NotificationForwardingPolicy(
|
||||
enabled = true,
|
||||
mode = NotificationPackageFilterMode.Allowlist,
|
||||
packages = setOf("com.allowed.app"),
|
||||
quietHoursEnabled = false,
|
||||
quietStart = "22:00",
|
||||
quietEnd = "07:00",
|
||||
maxEventsPerMinute = 20,
|
||||
sessionKey = null,
|
||||
)
|
||||
|
||||
assertTrue(policy.allowsPackage("com.allowed.app"))
|
||||
assertFalse(policy.allowsPackage("com.other.app"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun isWithinQuietHours_handlesWindowCrossingMidnight() {
|
||||
val policy =
|
||||
NotificationForwardingPolicy(
|
||||
enabled = true,
|
||||
mode = NotificationPackageFilterMode.Blocklist,
|
||||
packages = emptySet(),
|
||||
quietHoursEnabled = true,
|
||||
quietStart = "22:00",
|
||||
quietEnd = "07:00",
|
||||
maxEventsPerMinute = 20,
|
||||
sessionKey = null,
|
||||
)
|
||||
|
||||
val zone = ZoneId.of("UTC")
|
||||
val at2330 =
|
||||
LocalDateTime
|
||||
.of(2024, 1, 6, 23, 30)
|
||||
.atZone(zone)
|
||||
.toInstant()
|
||||
.toEpochMilli()
|
||||
val at1200 =
|
||||
LocalDateTime
|
||||
.of(2024, 1, 6, 12, 0)
|
||||
.atZone(zone)
|
||||
.toInstant()
|
||||
.toEpochMilli()
|
||||
|
||||
assertTrue(policy.isWithinQuietHours(nowEpochMs = at2330, zoneId = zone))
|
||||
assertFalse(policy.isWithinQuietHours(nowEpochMs = at1200, zoneId = zone))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun isWithinQuietHours_sameStartEndMeansAlwaysQuiet() {
|
||||
val policy =
|
||||
NotificationForwardingPolicy(
|
||||
enabled = true,
|
||||
mode = NotificationPackageFilterMode.Blocklist,
|
||||
packages = emptySet(),
|
||||
quietHoursEnabled = true,
|
||||
quietStart = "00:00",
|
||||
quietEnd = "00:00",
|
||||
maxEventsPerMinute = 20,
|
||||
sessionKey = null,
|
||||
)
|
||||
|
||||
assertTrue(policy.isWithinQuietHours(nowEpochMs = 1_704_098_400_000L, zoneId = ZoneId.of("UTC")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blocksEventsWhenDisabledOrQuietHoursOrRateLimited() {
|
||||
val disabled =
|
||||
NotificationForwardingPolicy(
|
||||
enabled = false,
|
||||
mode = NotificationPackageFilterMode.Blocklist,
|
||||
packages = emptySet(),
|
||||
quietHoursEnabled = false,
|
||||
quietStart = "22:00",
|
||||
quietEnd = "07:00",
|
||||
maxEventsPerMinute = 20,
|
||||
sessionKey = null,
|
||||
)
|
||||
assertFalse(disabled.enabled && disabled.allowsPackage("com.allowed.app"))
|
||||
|
||||
val quiet =
|
||||
NotificationForwardingPolicy(
|
||||
enabled = true,
|
||||
mode = NotificationPackageFilterMode.Blocklist,
|
||||
packages = emptySet(),
|
||||
quietHoursEnabled = true,
|
||||
quietStart = "22:00",
|
||||
quietEnd = "07:00",
|
||||
maxEventsPerMinute = 20,
|
||||
sessionKey = null,
|
||||
)
|
||||
val zone = ZoneId.of("UTC")
|
||||
val at2330 =
|
||||
LocalDateTime
|
||||
.of(2024, 1, 6, 23, 30)
|
||||
.atZone(zone)
|
||||
.toInstant()
|
||||
.toEpochMilli()
|
||||
assertTrue(quiet.isWithinQuietHours(nowEpochMs = at2330, zoneId = zone))
|
||||
|
||||
val limiter = NotificationBurstLimiter()
|
||||
val minute = 1_704_098_400_000L
|
||||
assertTrue(limiter.allow(nowEpochMs = minute, maxEventsPerMinute = 1))
|
||||
assertFalse(limiter.allow(nowEpochMs = minute + 500L, maxEventsPerMinute = 1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun burstLimiter_blocksEventsAboveLimitInSameMinute() {
|
||||
val limiter = NotificationBurstLimiter()
|
||||
val minute = 1_704_098_400_000L
|
||||
|
||||
assertTrue(limiter.allow(nowEpochMs = minute, maxEventsPerMinute = 2))
|
||||
assertTrue(limiter.allow(nowEpochMs = minute + 1_000L, maxEventsPerMinute = 2))
|
||||
assertFalse(limiter.allow(nowEpochMs = minute + 2_000L, maxEventsPerMinute = 2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun burstLimiter_resetsOnNextMinuteWindow() {
|
||||
val limiter = NotificationBurstLimiter()
|
||||
val minute = 1_704_098_400_000L
|
||||
|
||||
assertTrue(limiter.allow(nowEpochMs = minute, maxEventsPerMinute = 1))
|
||||
assertFalse(limiter.allow(nowEpochMs = minute + 1_000L, maxEventsPerMinute = 1))
|
||||
assertTrue(limiter.allow(nowEpochMs = minute + 60_000L, maxEventsPerMinute = 1))
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package ai.openclaw.app
|
||||
|
||||
import android.content.Context
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class SecurePrefsNotificationForwardingTest {
|
||||
@Test
|
||||
fun setNotificationForwardingQuietHours_rejectsInvalidDraftsWithoutMutatingStoredValues() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val plainPrefs = context.getSharedPreferences("openclaw.node", Context.MODE_PRIVATE)
|
||||
plainPrefs.edit().clear().commit()
|
||||
|
||||
val prefs = SecurePrefs(context)
|
||||
|
||||
assertTrue(
|
||||
prefs.setNotificationForwardingQuietHours(
|
||||
enabled = false,
|
||||
start = "22:00",
|
||||
end = "07:00",
|
||||
),
|
||||
)
|
||||
|
||||
val originalStart = prefs.notificationForwardingQuietStart.value
|
||||
val originalEnd = prefs.notificationForwardingQuietEnd.value
|
||||
val originalEnabled = prefs.notificationForwardingQuietHoursEnabled.value
|
||||
|
||||
assertFalse(
|
||||
prefs.setNotificationForwardingQuietHours(
|
||||
enabled = true,
|
||||
start = "7:00",
|
||||
end = "07:00",
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(originalStart, prefs.notificationForwardingQuietStart.value)
|
||||
assertEquals(originalEnd, prefs.notificationForwardingQuietEnd.value)
|
||||
assertEquals(originalEnabled, prefs.notificationForwardingQuietHoursEnabled.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun setNotificationForwardingQuietHours_persistsValidDraftsAndEnabledState() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val plainPrefs = context.getSharedPreferences("openclaw.node", Context.MODE_PRIVATE)
|
||||
plainPrefs.edit().clear().commit()
|
||||
|
||||
val prefs = SecurePrefs(context)
|
||||
|
||||
assertTrue(
|
||||
prefs.setNotificationForwardingQuietHours(
|
||||
enabled = true,
|
||||
start = "22:30",
|
||||
end = "06:45",
|
||||
),
|
||||
)
|
||||
|
||||
assertTrue(prefs.notificationForwardingQuietHoursEnabled.value)
|
||||
assertEquals("22:30", prefs.notificationForwardingQuietStart.value)
|
||||
assertEquals("06:45", prefs.notificationForwardingQuietEnd.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun setNotificationForwardingQuietHours_disablesWithoutRevalidatingDrafts() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val plainPrefs = context.getSharedPreferences("openclaw.node", Context.MODE_PRIVATE)
|
||||
plainPrefs.edit().clear().commit()
|
||||
|
||||
val prefs = SecurePrefs(context)
|
||||
assertTrue(
|
||||
prefs.setNotificationForwardingQuietHours(
|
||||
enabled = true,
|
||||
start = "22:30",
|
||||
end = "06:45",
|
||||
),
|
||||
)
|
||||
|
||||
assertTrue(
|
||||
prefs.setNotificationForwardingQuietHours(
|
||||
enabled = false,
|
||||
start = "7:00",
|
||||
end = "06:45",
|
||||
),
|
||||
)
|
||||
|
||||
assertFalse(prefs.notificationForwardingQuietHoursEnabled.value)
|
||||
assertEquals("22:30", prefs.notificationForwardingQuietStart.value)
|
||||
assertEquals("06:45", prefs.notificationForwardingQuietEnd.value)
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun getNotificationForwardingPolicy_readsLatestQuietHoursImmediately() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val plainPrefs = context.getSharedPreferences("openclaw.node", Context.MODE_PRIVATE)
|
||||
plainPrefs.edit().clear().commit()
|
||||
|
||||
val prefs = SecurePrefs(context)
|
||||
assertTrue(
|
||||
prefs.setNotificationForwardingQuietHours(
|
||||
enabled = true,
|
||||
start = "21:15",
|
||||
end = "06:10",
|
||||
),
|
||||
)
|
||||
|
||||
val policy = prefs.getNotificationForwardingPolicy(appPackageName = "ai.openclaw.app")
|
||||
|
||||
assertTrue(policy.quietHoursEnabled)
|
||||
assertEquals("21:15", policy.quietStart)
|
||||
assertEquals("06:10", policy.quietEnd)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun notificationForwarding_defaultsDisabledForSaferPosture() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val plainPrefs = context.getSharedPreferences("openclaw.node", Context.MODE_PRIVATE)
|
||||
plainPrefs.edit().clear().commit()
|
||||
|
||||
val prefs = SecurePrefs(context)
|
||||
val policy = prefs.getNotificationForwardingPolicy(appPackageName = "ai.openclaw.app")
|
||||
|
||||
assertFalse(prefs.notificationForwardingEnabled.value)
|
||||
assertFalse(policy.enabled)
|
||||
assertEquals(NotificationPackageFilterMode.Blocklist, policy.mode)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package ai.openclaw.app
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class SessionKeyTest {
|
||||
@Test
|
||||
fun buildNodeMainSessionKeyUsesStableDeviceScopedSuffix() {
|
||||
val key = buildNodeMainSessionKey(deviceId = "1234567890abcdef", agentId = "ops")
|
||||
|
||||
assertEquals("agent:ops:node-1234567890ab", key)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveAgentIdFromMainSessionKeyParsesCanonicalAgentKey() {
|
||||
assertEquals("ops", resolveAgentIdFromMainSessionKey("agent:ops:main"))
|
||||
assertNull(resolveAgentIdFromMainSessionKey("global"))
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package ai.openclaw.app.chat
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ChatControllerSessionPolicyTest {
|
||||
@Test
|
||||
fun applyMainSessionKeyMovesCurrentSessionWhenStillOnDefault() {
|
||||
val state =
|
||||
applyMainSessionKey(
|
||||
currentSessionKey = "main",
|
||||
appliedMainSessionKey = "main",
|
||||
nextMainSessionKey = "agent:ops:node-device",
|
||||
)
|
||||
|
||||
assertEquals("agent:ops:node-device", state.currentSessionKey)
|
||||
assertEquals("agent:ops:node-device", state.appliedMainSessionKey)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun applyMainSessionKeyKeepsUserSelectedSession() {
|
||||
val state =
|
||||
applyMainSessionKey(
|
||||
currentSessionKey = "custom",
|
||||
appliedMainSessionKey = "agent:ops:node-old",
|
||||
nextMainSessionKey = "agent:ops:node-new",
|
||||
)
|
||||
|
||||
assertEquals("custom", state.currentSessionKey)
|
||||
assertEquals("agent:ops:node-new", state.appliedMainSessionKey)
|
||||
}
|
||||
}
|
||||
@@ -173,50 +173,15 @@ class CallLogHandlerTest : NodeHandlerRobolectricTest() {
|
||||
assertTrue(callLogObj.containsKey("number"))
|
||||
assertTrue(callLogObj.containsKey("cachedName"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleCallLogSearch_clampsLimitAndOffsetBeforeSearch() {
|
||||
val source = FakeCallLogDataSource(canRead = true)
|
||||
val handler = CallLogHandler.forTesting(appContext(), source)
|
||||
|
||||
val result = handler.handleCallLogSearch("""{"limit":999,"offset":-5}""")
|
||||
|
||||
assertTrue(result.ok)
|
||||
assertEquals(200, source.lastRequest?.limit)
|
||||
assertEquals(0, source.lastRequest?.offset)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleCallLogSearch_mapsSearchFailuresToUnavailable() {
|
||||
val handler =
|
||||
CallLogHandler.forTesting(
|
||||
appContext(),
|
||||
FakeCallLogDataSource(
|
||||
canRead = true,
|
||||
failure = IllegalStateException("provider down"),
|
||||
),
|
||||
)
|
||||
|
||||
val result = handler.handleCallLogSearch(null)
|
||||
|
||||
assertFalse(result.ok)
|
||||
assertEquals("CALL_LOG_UNAVAILABLE", result.error?.code)
|
||||
assertEquals("CALL_LOG_UNAVAILABLE: provider down", result.error?.message)
|
||||
}
|
||||
}
|
||||
|
||||
private class FakeCallLogDataSource(
|
||||
private val canRead: Boolean,
|
||||
private val searchResults: List<CallLogRecord> = emptyList(),
|
||||
private val failure: Throwable? = null,
|
||||
) : CallLogDataSource {
|
||||
var lastRequest: CallLogSearchRequest? = null
|
||||
|
||||
override fun hasReadPermission(context: Context): Boolean = canRead
|
||||
|
||||
override fun search(context: Context, request: CallLogSearchRequest): List<CallLogRecord> {
|
||||
lastRequest = request
|
||||
failure?.let { throw it }
|
||||
val startIndex = request.offset.coerceAtLeast(0)
|
||||
val endIndex = (startIndex + request.limit).coerceAtMost(searchResults.size)
|
||||
return if (startIndex < searchResults.size) {
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package ai.openclaw.app.node
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class CanvasActionTrustTest {
|
||||
@Test
|
||||
fun acceptsBundledScaffoldAsset() {
|
||||
assertTrue(CanvasActionTrust.isTrustedCanvasActionUrl(CanvasActionTrust.scaffoldAssetUrl, emptyList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun acceptsTrustedA2uiPageOnAdvertisedCanvasHost() {
|
||||
assertTrue(
|
||||
CanvasActionTrust.isTrustedCanvasActionUrl(
|
||||
rawUrl = "https://canvas.example.com:9443/__openclaw__/cap/token/__openclaw__/a2ui/?platform=android",
|
||||
trustedA2uiUrls = listOf("https://canvas.example.com:9443/__openclaw__/cap/token/__openclaw__/a2ui/?platform=android"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsDifferentOriginEvenIfPathMatches() {
|
||||
assertFalse(
|
||||
CanvasActionTrust.isTrustedCanvasActionUrl(
|
||||
rawUrl = "https://evil.example.com:9443/__openclaw__/cap/token/__openclaw__/a2ui/?platform=android",
|
||||
trustedA2uiUrls = listOf("https://canvas.example.com:9443/__openclaw__/cap/token/__openclaw__/a2ui/?platform=android"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsUntrustedCanvasPagePathOnTrustedOrigin() {
|
||||
assertFalse(
|
||||
CanvasActionTrust.isTrustedCanvasActionUrl(
|
||||
rawUrl = "https://canvas.example.com:9443/untrusted/index.html",
|
||||
trustedA2uiUrls = listOf("https://canvas.example.com:9443/__openclaw__/cap/token/__openclaw__/a2ui/?platform=android"),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,10 @@
|
||||
package ai.openclaw.app.node
|
||||
|
||||
import ai.openclaw.app.LocationMode
|
||||
import ai.openclaw.app.SecurePrefs
|
||||
import ai.openclaw.app.VoiceWakeMode
|
||||
import ai.openclaw.app.protocol.OpenClawCallLogCommand
|
||||
import ai.openclaw.app.protocol.OpenClawCameraCommand
|
||||
import ai.openclaw.app.protocol.OpenClawCapability
|
||||
import ai.openclaw.app.protocol.OpenClawLocationCommand
|
||||
import ai.openclaw.app.protocol.OpenClawMotionCommand
|
||||
import ai.openclaw.app.protocol.OpenClawSmsCommand
|
||||
import ai.openclaw.app.gateway.GatewayEndpoint
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ConnectionManagerTest {
|
||||
@Test
|
||||
fun resolveTlsParamsForEndpoint_prefersStoredPinOverAdvertisedFingerprint() {
|
||||
@@ -88,173 +73,4 @@ class ConnectionManagerTest {
|
||||
assertNull(on?.expectedFingerprint)
|
||||
assertEquals(false, on?.allowTOFU)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildNodeConnectOptions_advertisesRequestableSmsSearchWithoutSmsCapability() {
|
||||
val options =
|
||||
newManager(
|
||||
sendSmsAvailable = false,
|
||||
readSmsAvailable = false,
|
||||
smsSearchPossible = true,
|
||||
).buildNodeConnectOptions()
|
||||
|
||||
assertTrue(options.commands.contains(OpenClawSmsCommand.Search.rawValue))
|
||||
assertFalse(options.commands.contains(OpenClawSmsCommand.Send.rawValue))
|
||||
assertFalse(options.caps.contains(OpenClawCapability.Sms.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildNodeConnectOptions_doesNotAdvertiseSmsWhenSearchIsImpossible() {
|
||||
val options =
|
||||
newManager(
|
||||
sendSmsAvailable = false,
|
||||
readSmsAvailable = false,
|
||||
smsSearchPossible = false,
|
||||
).buildNodeConnectOptions()
|
||||
|
||||
assertFalse(options.commands.contains(OpenClawSmsCommand.Search.rawValue))
|
||||
assertFalse(options.commands.contains(OpenClawSmsCommand.Send.rawValue))
|
||||
assertFalse(options.caps.contains(OpenClawCapability.Sms.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildNodeConnectOptions_advertisesSmsCapabilityWhenReadSmsIsAvailable() {
|
||||
val options =
|
||||
newManager(
|
||||
sendSmsAvailable = false,
|
||||
readSmsAvailable = true,
|
||||
smsSearchPossible = true,
|
||||
).buildNodeConnectOptions()
|
||||
|
||||
assertTrue(options.commands.contains(OpenClawSmsCommand.Search.rawValue))
|
||||
assertTrue(options.caps.contains(OpenClawCapability.Sms.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildNodeConnectOptions_advertisesSmsSendWithoutSearchWhenOnlySendIsAvailable() {
|
||||
val options =
|
||||
newManager(
|
||||
sendSmsAvailable = true,
|
||||
readSmsAvailable = false,
|
||||
smsSearchPossible = false,
|
||||
).buildNodeConnectOptions()
|
||||
|
||||
assertTrue(options.commands.contains(OpenClawSmsCommand.Send.rawValue))
|
||||
assertFalse(options.commands.contains(OpenClawSmsCommand.Search.rawValue))
|
||||
assertTrue(options.caps.contains(OpenClawCapability.Sms.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildNodeConnectOptions_advertisesAvailableNonSmsCommandsAndCapabilities() {
|
||||
val options =
|
||||
newManager(
|
||||
cameraEnabled = true,
|
||||
locationMode = LocationMode.WhileUsing,
|
||||
voiceWakeMode = VoiceWakeMode.Always,
|
||||
motionActivityAvailable = true,
|
||||
callLogAvailable = true,
|
||||
hasRecordAudioPermission = true,
|
||||
).buildNodeConnectOptions()
|
||||
|
||||
assertTrue(options.commands.contains(OpenClawCameraCommand.List.rawValue))
|
||||
assertTrue(options.commands.contains(OpenClawLocationCommand.Get.rawValue))
|
||||
assertTrue(options.commands.contains(OpenClawMotionCommand.Activity.rawValue))
|
||||
assertTrue(options.commands.contains(OpenClawCallLogCommand.Search.rawValue))
|
||||
assertTrue(options.caps.contains(OpenClawCapability.Camera.rawValue))
|
||||
assertTrue(options.caps.contains(OpenClawCapability.Location.rawValue))
|
||||
assertTrue(options.caps.contains(OpenClawCapability.Motion.rawValue))
|
||||
assertTrue(options.caps.contains(OpenClawCapability.CallLog.rawValue))
|
||||
assertTrue(options.caps.contains(OpenClawCapability.VoiceWake.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildNodeConnectOptions_omitsVoiceWakeWithoutMicrophonePermission() {
|
||||
val options =
|
||||
newManager(
|
||||
voiceWakeMode = VoiceWakeMode.Always,
|
||||
hasRecordAudioPermission = false,
|
||||
).buildNodeConnectOptions()
|
||||
|
||||
assertFalse(options.caps.contains(OpenClawCapability.VoiceWake.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildNodeConnectOptions_omitsUnavailableCameraLocationAndCallLogSurfaces() {
|
||||
val options =
|
||||
newManager(
|
||||
cameraEnabled = false,
|
||||
locationMode = LocationMode.Off,
|
||||
callLogAvailable = false,
|
||||
).buildNodeConnectOptions()
|
||||
|
||||
assertFalse(options.commands.contains(OpenClawCameraCommand.List.rawValue))
|
||||
assertFalse(options.commands.contains(OpenClawCameraCommand.Snap.rawValue))
|
||||
assertFalse(options.commands.contains(OpenClawCameraCommand.Clip.rawValue))
|
||||
assertFalse(options.commands.contains(OpenClawLocationCommand.Get.rawValue))
|
||||
assertFalse(options.commands.contains(OpenClawCallLogCommand.Search.rawValue))
|
||||
assertFalse(options.caps.contains(OpenClawCapability.Camera.rawValue))
|
||||
assertFalse(options.caps.contains(OpenClawCapability.Location.rawValue))
|
||||
assertFalse(options.caps.contains(OpenClawCapability.CallLog.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildNodeConnectOptions_advertisesOnlyAvailableMotionCommand() {
|
||||
val options =
|
||||
newManager(
|
||||
motionActivityAvailable = false,
|
||||
motionPedometerAvailable = true,
|
||||
).buildNodeConnectOptions()
|
||||
|
||||
assertFalse(options.commands.contains(OpenClawMotionCommand.Activity.rawValue))
|
||||
assertTrue(options.commands.contains(OpenClawMotionCommand.Pedometer.rawValue))
|
||||
assertTrue(options.caps.contains(OpenClawCapability.Motion.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildNodeConnectOptions_omitsMotionSurfaceWhenMotionApisUnavailable() {
|
||||
val options =
|
||||
newManager(
|
||||
motionActivityAvailable = false,
|
||||
motionPedometerAvailable = false,
|
||||
).buildNodeConnectOptions()
|
||||
|
||||
assertFalse(options.commands.contains(OpenClawMotionCommand.Activity.rawValue))
|
||||
assertFalse(options.commands.contains(OpenClawMotionCommand.Pedometer.rawValue))
|
||||
assertFalse(options.caps.contains(OpenClawCapability.Motion.rawValue))
|
||||
}
|
||||
|
||||
private fun newManager(
|
||||
cameraEnabled: Boolean = false,
|
||||
locationMode: LocationMode = LocationMode.Off,
|
||||
voiceWakeMode: VoiceWakeMode = VoiceWakeMode.Off,
|
||||
motionActivityAvailable: Boolean = false,
|
||||
motionPedometerAvailable: Boolean = false,
|
||||
sendSmsAvailable: Boolean = false,
|
||||
readSmsAvailable: Boolean = false,
|
||||
smsSearchPossible: Boolean = false,
|
||||
callLogAvailable: Boolean = false,
|
||||
hasRecordAudioPermission: Boolean = false,
|
||||
): ConnectionManager {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val prefs =
|
||||
SecurePrefs(
|
||||
context,
|
||||
securePrefsOverride = context.getSharedPreferences("connection-manager-test", android.content.Context.MODE_PRIVATE),
|
||||
)
|
||||
|
||||
return ConnectionManager(
|
||||
prefs = prefs,
|
||||
cameraEnabled = { cameraEnabled },
|
||||
locationMode = { locationMode },
|
||||
voiceWakeMode = { voiceWakeMode },
|
||||
motionActivityAvailable = { motionActivityAvailable },
|
||||
motionPedometerAvailable = { motionPedometerAvailable },
|
||||
sendSmsAvailable = { sendSmsAvailable },
|
||||
readSmsAvailable = { readSmsAvailable },
|
||||
smsSearchPossible = { smsSearchPossible },
|
||||
callLogAvailable = { callLogAvailable },
|
||||
hasRecordAudioPermission = { hasRecordAudioPermission },
|
||||
manualTls = { false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,131 +101,9 @@ class DeviceHandlerTest {
|
||||
val status = state.getValue("status").jsonPrimitive.content
|
||||
assertTrue(status == "granted" || status == "denied")
|
||||
state.getValue("promptable").jsonPrimitive.boolean
|
||||
if (key == "sms") {
|
||||
val capabilities = state.getValue("capabilities").jsonObject
|
||||
for (capabilityKey in listOf("send", "read")) {
|
||||
val capability = capabilities.getValue(capabilityKey).jsonObject
|
||||
val capabilityStatus = capability.getValue("status").jsonPrimitive.content
|
||||
assertTrue(capabilityStatus == "granted" || capabilityStatus == "denied")
|
||||
capability.getValue("promptable").jsonPrimitive.boolean
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsTopLevelStatusTreatsSendOnlyPartialGrantAsGranted() {
|
||||
assertTrue(
|
||||
DeviceHandler.hasAnySmsCapability(
|
||||
smsEnabled = true,
|
||||
telephonyAvailable = true,
|
||||
smsSendGranted = true,
|
||||
smsReadGranted = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsTopLevelStatusTreatsReadOnlyPartialGrantAsGranted() {
|
||||
assertTrue(
|
||||
DeviceHandler.hasAnySmsCapability(
|
||||
smsEnabled = true,
|
||||
telephonyAvailable = true,
|
||||
smsSendGranted = false,
|
||||
smsReadGranted = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsTopLevelStatusTreatsNoSmsGrantAsDenied() {
|
||||
assertTrue(
|
||||
!DeviceHandler.hasAnySmsCapability(
|
||||
smsEnabled = true,
|
||||
telephonyAvailable = true,
|
||||
smsSendGranted = false,
|
||||
smsReadGranted = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsTopLevelStatusTreatsDisabledSmsAsDenied() {
|
||||
assertTrue(
|
||||
!DeviceHandler.hasAnySmsCapability(
|
||||
smsEnabled = false,
|
||||
telephonyAvailable = true,
|
||||
smsSendGranted = true,
|
||||
smsReadGranted = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsTopLevelStatusTreatsMissingTelephonyAsDenied() {
|
||||
assertTrue(
|
||||
!DeviceHandler.hasAnySmsCapability(
|
||||
smsEnabled = true,
|
||||
telephonyAvailable = false,
|
||||
smsSendGranted = true,
|
||||
smsReadGranted = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsTopLevelPromptableStaysTrueUntilBothSmsPermissionsAreGranted() {
|
||||
assertTrue(
|
||||
DeviceHandler.isSmsPromptable(
|
||||
smsEnabled = true,
|
||||
telephonyAvailable = true,
|
||||
smsSendGranted = true,
|
||||
smsReadGranted = false,
|
||||
),
|
||||
)
|
||||
assertTrue(
|
||||
!DeviceHandler.isSmsPromptable(
|
||||
smsEnabled = true,
|
||||
telephonyAvailable = true,
|
||||
smsSendGranted = true,
|
||||
smsReadGranted = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsTopLevelPromptableIsFalseWhenSmsCannotExist() {
|
||||
assertTrue(
|
||||
!DeviceHandler.isSmsPromptable(
|
||||
smsEnabled = false,
|
||||
telephonyAvailable = true,
|
||||
smsSendGranted = false,
|
||||
smsReadGranted = false,
|
||||
),
|
||||
)
|
||||
assertTrue(
|
||||
!DeviceHandler.isSmsPromptable(
|
||||
smsEnabled = true,
|
||||
telephonyAvailable = false,
|
||||
smsSendGranted = false,
|
||||
smsReadGranted = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleDevicePermissions_marksCallLogUnpromptableWhenFeatureDisabled() {
|
||||
val handler = DeviceHandler(appContext(), callLogEnabled = false)
|
||||
|
||||
val result = handler.handleDevicePermissions(null)
|
||||
|
||||
assertTrue(result.ok)
|
||||
val payload = parsePayload(result.payloadJson)
|
||||
val callLog = payload.getValue("permissions").jsonObject.getValue("callLog").jsonObject
|
||||
assertEquals("denied", callLog.getValue("status").jsonPrimitive.content)
|
||||
assertTrue(!callLog.getValue("promptable").jsonPrimitive.boolean)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleDeviceHealth_returnsExpectedShape() {
|
||||
val handler = DeviceHandler(appContext())
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
package ai.openclaw.app.node
|
||||
|
||||
import android.content.Context
|
||||
import ai.openclaw.app.NotificationBurstLimiter
|
||||
import ai.openclaw.app.NotificationForwardingPolicy
|
||||
import ai.openclaw.app.NotificationPackageFilterMode
|
||||
import ai.openclaw.app.isWithinQuietHours
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class DeviceNotificationListenerServiceTest {
|
||||
@Test
|
||||
fun recentPackages_migratesLegacyPreferenceKey() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val prefs = context.getSharedPreferences("openclaw.secure", Context.MODE_PRIVATE)
|
||||
prefs.edit()
|
||||
.clear()
|
||||
.putString("notifications.recentPackages", "com.example.one, com.example.two")
|
||||
.commit()
|
||||
|
||||
val packages = DeviceNotificationListenerService.recentPackages(context)
|
||||
|
||||
assertEquals(listOf("com.example.one", "com.example.two"), packages)
|
||||
assertEquals(
|
||||
"com.example.one, com.example.two",
|
||||
prefs.getString("notifications.forwarding.recentPackages", null),
|
||||
)
|
||||
assertFalse(prefs.contains("notifications.recentPackages"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recentPackages_cleansUpLegacyKeyWhenNewKeyAlreadyExists() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val prefs = context.getSharedPreferences("openclaw.secure", Context.MODE_PRIVATE)
|
||||
prefs.edit()
|
||||
.clear()
|
||||
.putString("notifications.forwarding.recentPackages", "com.example.new")
|
||||
.putString("notifications.recentPackages", "com.example.legacy")
|
||||
.commit()
|
||||
|
||||
val packages = DeviceNotificationListenerService.recentPackages(context)
|
||||
|
||||
assertEquals(listOf("com.example.new"), packages)
|
||||
assertNull(prefs.getString("notifications.recentPackages", null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recentPackages_trimsDedupesAndPreservesRecencyOrder() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val prefs = context.getSharedPreferences("openclaw.secure", Context.MODE_PRIVATE)
|
||||
prefs.edit()
|
||||
.clear()
|
||||
.putString(
|
||||
"notifications.forwarding.recentPackages",
|
||||
" com.example.recent , ,com.example.other,com.example.recent, com.example.third ",
|
||||
)
|
||||
.commit()
|
||||
|
||||
val packages = DeviceNotificationListenerService.recentPackages(context)
|
||||
|
||||
assertEquals(
|
||||
listOf("com.example.recent", "com.example.other", "com.example.third"),
|
||||
packages,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun quietHoursAndRateLimitingUseWallClockTimeNotNotificationPostTime() {
|
||||
val zone = java.time.ZoneId.systemDefault()
|
||||
val now = java.time.ZonedDateTime.now(zone)
|
||||
val quietStart = now.minusMinutes(5).toLocalTime().withSecond(0).withNano(0)
|
||||
val quietEnd = now.plusMinutes(5).toLocalTime().withSecond(0).withNano(0)
|
||||
val stalePostTime =
|
||||
now
|
||||
.minusHours(2)
|
||||
.withMinute(0)
|
||||
.withSecond(0)
|
||||
.withNano(0)
|
||||
.toInstant()
|
||||
.toEpochMilli()
|
||||
|
||||
val policy =
|
||||
NotificationForwardingPolicy(
|
||||
enabled = true,
|
||||
mode = NotificationPackageFilterMode.Blocklist,
|
||||
packages = emptySet(),
|
||||
quietHoursEnabled = true,
|
||||
quietStart = "%02d:%02d".format(quietStart.hour, quietStart.minute),
|
||||
quietEnd = "%02d:%02d".format(quietEnd.hour, quietEnd.minute),
|
||||
maxEventsPerMinute = 1,
|
||||
sessionKey = null,
|
||||
)
|
||||
|
||||
assertFalse(policy.isWithinQuietHours(nowEpochMs = stalePostTime, zoneId = zone))
|
||||
assertTrue(policy.isWithinQuietHours(nowEpochMs = System.currentTimeMillis(), zoneId = zone))
|
||||
|
||||
val limiter = NotificationBurstLimiter()
|
||||
assertTrue(limiter.allow(nowEpochMs = stalePostTime, maxEventsPerMinute = 1))
|
||||
assertTrue(limiter.allow(nowEpochMs = System.currentTimeMillis(), maxEventsPerMinute = 1))
|
||||
assertFalse(limiter.allow(nowEpochMs = System.currentTimeMillis(), maxEventsPerMinute = 1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun burstLimiter_capsAnyForwardedNotificationEvent() {
|
||||
val limiter = NotificationBurstLimiter()
|
||||
val nowEpochMs = System.currentTimeMillis()
|
||||
|
||||
assertTrue(limiter.allow(nowEpochMs = nowEpochMs, maxEventsPerMinute = 2))
|
||||
assertTrue(limiter.allow(nowEpochMs = nowEpochMs, maxEventsPerMinute = 2))
|
||||
assertFalse(limiter.allow(nowEpochMs = nowEpochMs, maxEventsPerMinute = 2))
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,6 @@ import ai.openclaw.app.protocol.OpenClawNotificationsCommand
|
||||
import ai.openclaw.app.protocol.OpenClawPhotosCommand
|
||||
import ai.openclaw.app.protocol.OpenClawSmsCommand
|
||||
import ai.openclaw.app.protocol.OpenClawSystemCommand
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -89,7 +86,6 @@ class InvokeCommandRegistryTest {
|
||||
locationEnabled = true,
|
||||
sendSmsAvailable = true,
|
||||
readSmsAvailable = true,
|
||||
smsSearchPossible = true,
|
||||
callLogAvailable = true,
|
||||
voiceWakeEnabled = true,
|
||||
motionActivityAvailable = true,
|
||||
@@ -117,7 +113,6 @@ class InvokeCommandRegistryTest {
|
||||
locationEnabled = true,
|
||||
sendSmsAvailable = true,
|
||||
readSmsAvailable = true,
|
||||
smsSearchPossible = true,
|
||||
callLogAvailable = true,
|
||||
motionActivityAvailable = true,
|
||||
motionPedometerAvailable = true,
|
||||
@@ -137,7 +132,6 @@ class InvokeCommandRegistryTest {
|
||||
locationEnabled = false,
|
||||
sendSmsAvailable = false,
|
||||
readSmsAvailable = false,
|
||||
smsSearchPossible = false,
|
||||
callLogAvailable = false,
|
||||
voiceWakeEnabled = false,
|
||||
motionActivityAvailable = true,
|
||||
@@ -154,22 +148,17 @@ class InvokeCommandRegistryTest {
|
||||
fun advertisedCommands_splitsSmsSendAndSearchAvailability() {
|
||||
val readOnlyCommands =
|
||||
InvokeCommandRegistry.advertisedCommands(
|
||||
defaultFlags(readSmsAvailable = true, smsSearchPossible = true),
|
||||
defaultFlags(readSmsAvailable = true),
|
||||
)
|
||||
val sendOnlyCommands =
|
||||
InvokeCommandRegistry.advertisedCommands(
|
||||
defaultFlags(sendSmsAvailable = true),
|
||||
)
|
||||
val requestableSearchCommands =
|
||||
InvokeCommandRegistry.advertisedCommands(
|
||||
defaultFlags(smsSearchPossible = true),
|
||||
)
|
||||
|
||||
assertTrue(readOnlyCommands.contains(OpenClawSmsCommand.Search.rawValue))
|
||||
assertFalse(readOnlyCommands.contains(OpenClawSmsCommand.Send.rawValue))
|
||||
assertTrue(sendOnlyCommands.contains(OpenClawSmsCommand.Send.rawValue))
|
||||
assertFalse(sendOnlyCommands.contains(OpenClawSmsCommand.Search.rawValue))
|
||||
assertTrue(requestableSearchCommands.contains(OpenClawSmsCommand.Search.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -182,14 +171,9 @@ class InvokeCommandRegistryTest {
|
||||
InvokeCommandRegistry.advertisedCapabilities(
|
||||
defaultFlags(sendSmsAvailable = true),
|
||||
)
|
||||
val requestableSearchCapabilities =
|
||||
InvokeCommandRegistry.advertisedCapabilities(
|
||||
defaultFlags(smsSearchPossible = true),
|
||||
)
|
||||
|
||||
assertTrue(readOnlyCapabilities.contains(OpenClawCapability.Sms.rawValue))
|
||||
assertTrue(sendOnlyCapabilities.contains(OpenClawCapability.Sms.rawValue))
|
||||
assertFalse(requestableSearchCapabilities.contains(OpenClawCapability.Sms.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -206,37 +190,11 @@ class InvokeCommandRegistryTest {
|
||||
assertFalse(capabilities.contains(OpenClawCapability.CallLog.rawValue))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun advertisedCapabilities_includesVoiceWakeWithoutAdvertisingCommands() {
|
||||
val capabilities = InvokeCommandRegistry.advertisedCapabilities(defaultFlags(voiceWakeEnabled = true))
|
||||
val commands = InvokeCommandRegistry.advertisedCommands(defaultFlags(voiceWakeEnabled = true))
|
||||
|
||||
assertTrue(capabilities.contains(OpenClawCapability.VoiceWake.rawValue))
|
||||
assertFalse(commands.any { it.contains("voice", ignoreCase = true) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun find_returnsForegroundMetadataForCameraCommands() {
|
||||
val list = InvokeCommandRegistry.find(OpenClawCameraCommand.List.rawValue)
|
||||
val location = InvokeCommandRegistry.find(OpenClawLocationCommand.Get.rawValue)
|
||||
|
||||
assertNotNull(list)
|
||||
assertEquals(true, list?.requiresForeground)
|
||||
assertNotNull(location)
|
||||
assertEquals(false, location?.requiresForeground)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun find_returnsNullForUnknownCommand() {
|
||||
assertNull(InvokeCommandRegistry.find("not.real"))
|
||||
}
|
||||
|
||||
private fun defaultFlags(
|
||||
cameraEnabled: Boolean = false,
|
||||
locationEnabled: Boolean = false,
|
||||
sendSmsAvailable: Boolean = false,
|
||||
readSmsAvailable: Boolean = false,
|
||||
smsSearchPossible: Boolean = false,
|
||||
callLogAvailable: Boolean = false,
|
||||
voiceWakeEnabled: Boolean = false,
|
||||
motionActivityAvailable: Boolean = false,
|
||||
@@ -248,7 +206,6 @@ class InvokeCommandRegistryTest {
|
||||
locationEnabled = locationEnabled,
|
||||
sendSmsAvailable = sendSmsAvailable,
|
||||
readSmsAvailable = readSmsAvailable,
|
||||
smsSearchPossible = smsSearchPossible,
|
||||
callLogAvailable = callLogAvailable,
|
||||
voiceWakeEnabled = voiceWakeEnabled,
|
||||
motionActivityAvailable = motionActivityAvailable,
|
||||
|
||||
@@ -1,368 +0,0 @@
|
||||
package ai.openclaw.app.node
|
||||
|
||||
import ai.openclaw.app.gateway.DeviceIdentityStore
|
||||
import ai.openclaw.app.gateway.GatewaySession
|
||||
import ai.openclaw.app.protocol.OpenClawCallLogCommand
|
||||
import ai.openclaw.app.protocol.OpenClawCameraCommand
|
||||
import ai.openclaw.app.protocol.OpenClawLocationCommand
|
||||
import ai.openclaw.app.protocol.OpenClawMotionCommand
|
||||
import ai.openclaw.app.protocol.OpenClawSmsCommand
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class InvokeDispatcherTest {
|
||||
@Test
|
||||
fun classifySmsSearchAvailability_returnsAvailable_whenReadSmsIsAvailable() {
|
||||
assertEquals(
|
||||
SmsSearchAvailabilityReason.Available,
|
||||
classifySmsSearchAvailability(
|
||||
readSmsAvailable = true,
|
||||
smsFeatureEnabled = true,
|
||||
smsTelephonyAvailable = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun classifySmsSearchAvailability_returnsUnavailable_whenSmsFeatureDisabled() {
|
||||
assertEquals(
|
||||
SmsSearchAvailabilityReason.Unavailable,
|
||||
classifySmsSearchAvailability(
|
||||
readSmsAvailable = false,
|
||||
smsFeatureEnabled = false,
|
||||
smsTelephonyAvailable = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun classifySmsSearchAvailability_returnsUnavailable_whenTelephonyUnavailable() {
|
||||
assertEquals(
|
||||
SmsSearchAvailabilityReason.Unavailable,
|
||||
classifySmsSearchAvailability(
|
||||
readSmsAvailable = false,
|
||||
smsFeatureEnabled = true,
|
||||
smsTelephonyAvailable = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun classifySmsSearchAvailability_returnsPermissionRequired_whenOnlyReadSmsPermissionIsMissing() {
|
||||
assertEquals(
|
||||
SmsSearchAvailabilityReason.PermissionRequired,
|
||||
classifySmsSearchAvailability(
|
||||
readSmsAvailable = false,
|
||||
smsFeatureEnabled = true,
|
||||
smsTelephonyAvailable = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsSearchAvailabilityError_returnsNull_whenReadSmsPermissionIsRequestable() {
|
||||
assertNull(
|
||||
smsSearchAvailabilityError(
|
||||
readSmsAvailable = false,
|
||||
smsFeatureEnabled = true,
|
||||
smsTelephonyAvailable = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsSearchAvailabilityError_returnsUnavailable_whenSmsSearchIsImpossible() {
|
||||
val result =
|
||||
smsSearchAvailabilityError(
|
||||
readSmsAvailable = false,
|
||||
smsFeatureEnabled = false,
|
||||
smsTelephonyAvailable = true,
|
||||
)
|
||||
|
||||
assertEquals("SMS_UNAVAILABLE", result?.error?.code)
|
||||
assertEquals("SMS_UNAVAILABLE: SMS not available on this device", result?.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_allowsRequestableSmsSearchToReachHandler() =
|
||||
runTest {
|
||||
val result =
|
||||
newDispatcher(
|
||||
readSmsAvailable = false,
|
||||
smsFeatureEnabled = true,
|
||||
smsTelephonyAvailable = true,
|
||||
).handleInvoke(OpenClawSmsCommand.Search.rawValue, "not-json")
|
||||
|
||||
assertEquals("SMS_PERMISSION_REQUIRED", result.error?.code)
|
||||
assertEquals("grant READ_SMS permission", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_blocksSmsSearchWhenFeatureIsUnavailable() =
|
||||
runTest {
|
||||
val result =
|
||||
newDispatcher(
|
||||
readSmsAvailable = false,
|
||||
smsFeatureEnabled = false,
|
||||
smsTelephonyAvailable = true,
|
||||
).handleInvoke(OpenClawSmsCommand.Search.rawValue, "not-json")
|
||||
|
||||
assertEquals("SMS_UNAVAILABLE", result.error?.code)
|
||||
assertEquals("SMS_UNAVAILABLE: SMS not available on this device", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_allowsAvailableSmsSendToReachHandler() =
|
||||
runTest {
|
||||
val result =
|
||||
newDispatcher(
|
||||
sendSmsAvailable = true,
|
||||
smsFeatureEnabled = true,
|
||||
smsTelephonyAvailable = true,
|
||||
).handleInvoke(OpenClawSmsCommand.Send.rawValue, """{"to":"+15551234567","message":"hi"}""")
|
||||
|
||||
assertEquals("SMS_PERMISSION_REQUIRED", result.error?.code)
|
||||
assertEquals("grant SMS permission", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_blocksSmsSendWhenUnavailable() =
|
||||
runTest {
|
||||
val result =
|
||||
newDispatcher(
|
||||
sendSmsAvailable = false,
|
||||
smsFeatureEnabled = true,
|
||||
smsTelephonyAvailable = true,
|
||||
).handleInvoke(OpenClawSmsCommand.Send.rawValue, """{"to":"+15551234567","message":"hi"}""")
|
||||
|
||||
assertEquals("SMS_UNAVAILABLE", result.error?.code)
|
||||
assertEquals("SMS_UNAVAILABLE: SMS not available on this device", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_blocksCameraCommandsWhenCameraDisabled() =
|
||||
runTest {
|
||||
val result = newDispatcher(cameraEnabled = false).handleInvoke(OpenClawCameraCommand.List.rawValue, null)
|
||||
|
||||
assertEquals("CAMERA_DISABLED", result.error?.code)
|
||||
assertEquals("CAMERA_DISABLED: enable Camera in Settings", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_blocksLocationCommandWhenLocationDisabled() =
|
||||
runTest {
|
||||
val result = newDispatcher(locationEnabled = false).handleInvoke(OpenClawLocationCommand.Get.rawValue, null)
|
||||
|
||||
assertEquals("LOCATION_DISABLED", result.error?.code)
|
||||
assertEquals("LOCATION_DISABLED: enable Location in Settings", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_blocksMotionActivityWhenUnavailable() =
|
||||
runTest {
|
||||
val result =
|
||||
newDispatcher(motionActivityAvailable = false)
|
||||
.handleInvoke(OpenClawMotionCommand.Activity.rawValue, null)
|
||||
|
||||
assertEquals("MOTION_UNAVAILABLE", result.error?.code)
|
||||
assertEquals("MOTION_UNAVAILABLE: accelerometer not available", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_blocksMotionPedometerWhenUnavailable() =
|
||||
runTest {
|
||||
val result =
|
||||
newDispatcher(motionPedometerAvailable = false)
|
||||
.handleInvoke(OpenClawMotionCommand.Pedometer.rawValue, null)
|
||||
|
||||
assertEquals("PEDOMETER_UNAVAILABLE", result.error?.code)
|
||||
assertEquals("PEDOMETER_UNAVAILABLE: step counter not available", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_blocksCallLogWhenUnavailable() =
|
||||
runTest {
|
||||
val result =
|
||||
newDispatcher(callLogAvailable = false).handleInvoke(OpenClawCallLogCommand.Search.rawValue, null)
|
||||
|
||||
assertEquals("CALL_LOG_UNAVAILABLE", result.error?.code)
|
||||
assertEquals("CALL_LOG_UNAVAILABLE: call log not available on this build", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleInvoke_treatsDebugCommandsAsUnknownOutsideDebugBuilds() =
|
||||
runTest {
|
||||
val result = newDispatcher(debugBuild = false).handleInvoke("debug.logs", null)
|
||||
|
||||
assertEquals("INVALID_REQUEST", result.error?.code)
|
||||
assertEquals("INVALID_REQUEST: unknown command", result.error?.message)
|
||||
}
|
||||
|
||||
private fun newDispatcher(
|
||||
cameraEnabled: Boolean = false,
|
||||
locationEnabled: Boolean = false,
|
||||
sendSmsAvailable: Boolean = false,
|
||||
readSmsAvailable: Boolean = false,
|
||||
smsFeatureEnabled: Boolean = true,
|
||||
smsTelephonyAvailable: Boolean = true,
|
||||
callLogAvailable: Boolean = false,
|
||||
debugBuild: Boolean = false,
|
||||
motionActivityAvailable: Boolean = false,
|
||||
motionPedometerAvailable: Boolean = false,
|
||||
): InvokeDispatcher {
|
||||
val appContext = RuntimeEnvironment.getApplication()
|
||||
shadowOf(appContext.packageManager).setSystemFeature(PackageManager.FEATURE_TELEPHONY, smsTelephonyAvailable)
|
||||
val canvas = CanvasController()
|
||||
return InvokeDispatcher(
|
||||
canvas = canvas,
|
||||
cameraHandler = newCameraHandler(appContext),
|
||||
locationHandler =
|
||||
LocationHandler.forTesting(
|
||||
appContext = appContext,
|
||||
dataSource = InvokeDispatcherFakeLocationDataSource(),
|
||||
),
|
||||
deviceHandler = DeviceHandler(appContext),
|
||||
notificationsHandler =
|
||||
NotificationsHandler.forTesting(
|
||||
appContext = appContext,
|
||||
stateProvider = InvokeDispatcherFakeNotificationsStateProvider(),
|
||||
),
|
||||
systemHandler = SystemHandler.forTesting(InvokeDispatcherFakeSystemNotificationPoster()),
|
||||
photosHandler = PhotosHandler.forTesting(appContext, InvokeDispatcherFakePhotosDataSource()),
|
||||
contactsHandler = ContactsHandler.forTesting(appContext, InvokeDispatcherFakeContactsDataSource()),
|
||||
calendarHandler = CalendarHandler.forTesting(appContext, InvokeDispatcherFakeCalendarDataSource()),
|
||||
motionHandler = MotionHandler.forTesting(appContext, InvokeDispatcherFakeMotionDataSource()),
|
||||
smsHandler = SmsHandler(SmsManager(appContext)),
|
||||
a2uiHandler =
|
||||
A2UIHandler(
|
||||
canvas = canvas,
|
||||
json = Json { ignoreUnknownKeys = true },
|
||||
getNodeCanvasHostUrl = { null },
|
||||
getOperatorCanvasHostUrl = { null },
|
||||
),
|
||||
debugHandler = DebugHandler(appContext, DeviceIdentityStore(appContext)),
|
||||
callLogHandler = CallLogHandler.forTesting(appContext, InvokeDispatcherFakeCallLogDataSource()),
|
||||
isForeground = { true },
|
||||
cameraEnabled = { cameraEnabled },
|
||||
locationEnabled = { locationEnabled },
|
||||
sendSmsAvailable = { sendSmsAvailable },
|
||||
readSmsAvailable = { readSmsAvailable },
|
||||
smsFeatureEnabled = { smsFeatureEnabled },
|
||||
smsTelephonyAvailable = { smsTelephonyAvailable },
|
||||
callLogAvailable = { callLogAvailable },
|
||||
debugBuild = { debugBuild },
|
||||
refreshNodeCanvasCapability = { false },
|
||||
onCanvasA2uiPush = {},
|
||||
onCanvasA2uiReset = {},
|
||||
motionActivityAvailable = { motionActivityAvailable },
|
||||
motionPedometerAvailable = { motionPedometerAvailable },
|
||||
)
|
||||
}
|
||||
|
||||
private fun newCameraHandler(appContext: Context): CameraHandler {
|
||||
return CameraHandler(
|
||||
appContext = appContext,
|
||||
camera = CameraCaptureManager(appContext),
|
||||
externalAudioCaptureActive = MutableStateFlow(false),
|
||||
showCameraHud = { _, _, _ -> },
|
||||
triggerCameraFlash = {},
|
||||
invokeErrorFromThrowable = { err -> "UNAVAILABLE" to (err.message ?: "camera failed") },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private class InvokeDispatcherFakeLocationDataSource : LocationDataSource {
|
||||
override fun hasFinePermission(context: Context): Boolean = false
|
||||
|
||||
override fun hasCoarsePermission(context: Context): Boolean = false
|
||||
|
||||
override suspend fun fetchLocation(
|
||||
desiredProviders: List<String>,
|
||||
maxAgeMs: Long?,
|
||||
timeoutMs: Long,
|
||||
isPrecise: Boolean,
|
||||
): LocationCaptureManager.Payload {
|
||||
error("unused in InvokeDispatcherTest")
|
||||
}
|
||||
}
|
||||
|
||||
private class InvokeDispatcherFakeNotificationsStateProvider : NotificationsStateProvider {
|
||||
override fun readSnapshot(context: Context): DeviceNotificationSnapshot {
|
||||
return DeviceNotificationSnapshot(enabled = false, connected = false, notifications = emptyList())
|
||||
}
|
||||
|
||||
override fun requestServiceRebind(context: Context) = Unit
|
||||
|
||||
override fun executeAction(context: Context, request: NotificationActionRequest): NotificationActionResult {
|
||||
return NotificationActionResult(ok = true, code = null, message = null)
|
||||
}
|
||||
}
|
||||
|
||||
private class InvokeDispatcherFakeSystemNotificationPoster : SystemNotificationPoster {
|
||||
override fun isAuthorized(): Boolean = true
|
||||
|
||||
override fun post(request: SystemNotifyRequest) = Unit
|
||||
}
|
||||
|
||||
private class InvokeDispatcherFakePhotosDataSource : PhotosDataSource {
|
||||
override fun hasPermission(context: Context): Boolean = true
|
||||
|
||||
override fun latest(context: Context, request: PhotosLatestRequest): List<EncodedPhotoPayload> = emptyList()
|
||||
}
|
||||
|
||||
private class InvokeDispatcherFakeContactsDataSource : ContactsDataSource {
|
||||
override fun hasReadPermission(context: Context): Boolean = true
|
||||
|
||||
override fun hasWritePermission(context: Context): Boolean = true
|
||||
|
||||
override fun search(context: Context, request: ContactsSearchRequest): List<ContactRecord> = emptyList()
|
||||
|
||||
override fun add(context: Context, request: ContactsAddRequest): ContactRecord {
|
||||
error("unused in InvokeDispatcherTest")
|
||||
}
|
||||
}
|
||||
|
||||
private class InvokeDispatcherFakeCalendarDataSource : CalendarDataSource {
|
||||
override fun hasReadPermission(context: Context): Boolean = true
|
||||
|
||||
override fun hasWritePermission(context: Context): Boolean = true
|
||||
|
||||
override fun events(context: Context, request: CalendarEventsRequest): List<CalendarEventRecord> = emptyList()
|
||||
|
||||
override fun add(context: Context, request: CalendarAddRequest): CalendarEventRecord {
|
||||
error("unused in InvokeDispatcherTest")
|
||||
}
|
||||
}
|
||||
|
||||
private class InvokeDispatcherFakeMotionDataSource : MotionDataSource {
|
||||
override fun isActivityAvailable(context: Context): Boolean = false
|
||||
|
||||
override fun isPedometerAvailable(context: Context): Boolean = false
|
||||
|
||||
override fun hasPermission(context: Context): Boolean = true
|
||||
|
||||
override suspend fun activity(context: Context, request: MotionActivityRequest): MotionActivityRecord {
|
||||
error("unused in InvokeDispatcherTest")
|
||||
}
|
||||
|
||||
override suspend fun pedometer(context: Context, request: MotionPedometerRequest): PedometerRecord {
|
||||
error("unused in InvokeDispatcherTest")
|
||||
}
|
||||
}
|
||||
|
||||
private class InvokeDispatcherFakeCallLogDataSource : CallLogDataSource {
|
||||
override fun hasReadPermission(context: Context): Boolean = true
|
||||
|
||||
override fun search(context: Context, request: CallLogSearchRequest): List<CallLogRecord> = emptyList()
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
package ai.openclaw.app.node
|
||||
|
||||
import android.content.Context
|
||||
import android.location.LocationManager
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -67,110 +65,12 @@ class LocationHandlerTest : NodeHandlerRobolectricTest() {
|
||||
assertTrue(granted.hasFineLocationPermission())
|
||||
assertFalse(granted.hasCoarseLocationPermission())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleLocationGet_usesPreciseGpsFirstWhenFinePermissionAndPreciseEnabled() =
|
||||
runTest {
|
||||
val source =
|
||||
FakeLocationDataSource(
|
||||
fineGranted = true,
|
||||
coarseGranted = true,
|
||||
payload = LocationCaptureManager.Payload("""{"ok":true}"""),
|
||||
)
|
||||
val handler =
|
||||
LocationHandler.forTesting(
|
||||
appContext = appContext(),
|
||||
dataSource = source,
|
||||
locationPreciseEnabled = { true },
|
||||
)
|
||||
|
||||
val result = handler.handleLocationGet("""{"desiredAccuracy":"precise","maxAgeMs":1234,"timeoutMs":2000}""")
|
||||
|
||||
assertTrue(result.ok)
|
||||
assertEquals(listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER), source.lastDesiredProviders)
|
||||
assertEquals(1234L, source.lastMaxAgeMs)
|
||||
assertEquals(2000L, source.lastTimeoutMs)
|
||||
assertTrue(source.lastIsPrecise)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleLocationGet_fallsBackToBalancedWhenPreciseUnavailable() =
|
||||
runTest {
|
||||
val source =
|
||||
FakeLocationDataSource(
|
||||
fineGranted = false,
|
||||
coarseGranted = true,
|
||||
payload = LocationCaptureManager.Payload("""{"ok":true}"""),
|
||||
)
|
||||
val handler =
|
||||
LocationHandler.forTesting(
|
||||
appContext = appContext(),
|
||||
dataSource = source,
|
||||
locationPreciseEnabled = { true },
|
||||
)
|
||||
|
||||
val result = handler.handleLocationGet("""{"desiredAccuracy":"precise"}""")
|
||||
|
||||
assertTrue(result.ok)
|
||||
assertEquals(listOf(LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER), source.lastDesiredProviders)
|
||||
assertFalse(source.lastIsPrecise)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleLocationGet_mapsTimeoutToLocationTimeout() =
|
||||
runTest {
|
||||
val handler =
|
||||
LocationHandler.forTesting(
|
||||
appContext = appContext(),
|
||||
dataSource =
|
||||
FakeLocationDataSource(
|
||||
fineGranted = true,
|
||||
coarseGranted = true,
|
||||
timeout = true,
|
||||
),
|
||||
)
|
||||
|
||||
val result = handler.handleLocationGet(null)
|
||||
|
||||
assertFalse(result.ok)
|
||||
assertEquals("LOCATION_TIMEOUT", result.error?.code)
|
||||
assertEquals("LOCATION_TIMEOUT: no fix in time", result.error?.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleLocationGet_mapsOtherFailuresToLocationUnavailable() =
|
||||
runTest {
|
||||
val handler =
|
||||
LocationHandler.forTesting(
|
||||
appContext = appContext(),
|
||||
dataSource =
|
||||
FakeLocationDataSource(
|
||||
fineGranted = true,
|
||||
coarseGranted = true,
|
||||
failure = IllegalStateException("gps offline"),
|
||||
),
|
||||
)
|
||||
|
||||
val result = handler.handleLocationGet(null)
|
||||
|
||||
assertFalse(result.ok)
|
||||
assertEquals("LOCATION_UNAVAILABLE", result.error?.code)
|
||||
assertEquals("gps offline", result.error?.message)
|
||||
}
|
||||
}
|
||||
|
||||
private class FakeLocationDataSource(
|
||||
private val fineGranted: Boolean,
|
||||
private val coarseGranted: Boolean,
|
||||
private val payload: LocationCaptureManager.Payload? = null,
|
||||
private val failure: Throwable? = null,
|
||||
private val timeout: Boolean = false,
|
||||
) : LocationDataSource {
|
||||
var lastDesiredProviders: List<String> = emptyList()
|
||||
var lastMaxAgeMs: Long? = null
|
||||
var lastTimeoutMs: Long? = null
|
||||
var lastIsPrecise: Boolean = false
|
||||
|
||||
override fun hasFinePermission(context: Context): Boolean = fineGranted
|
||||
|
||||
override fun hasCoarsePermission(context: Context): Boolean = coarseGranted
|
||||
@@ -181,16 +81,8 @@ private class FakeLocationDataSource(
|
||||
timeoutMs: Long,
|
||||
isPrecise: Boolean,
|
||||
): LocationCaptureManager.Payload {
|
||||
lastDesiredProviders = desiredProviders
|
||||
lastMaxAgeMs = maxAgeMs
|
||||
lastTimeoutMs = timeoutMs
|
||||
lastIsPrecise = isPrecise
|
||||
if (timeout) {
|
||||
kotlinx.coroutines.withTimeout(1) {
|
||||
kotlinx.coroutines.delay(5)
|
||||
}
|
||||
}
|
||||
failure?.let { throw it }
|
||||
return payload ?: LocationCaptureManager.Payload(Json.encodeToString(mapOf("ok" to true)))
|
||||
throw IllegalStateException(
|
||||
"LocationHandlerTest: fetchLocation must not run in this scenario",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,46 +140,6 @@ class NotificationsHandlerTest {
|
||||
assertEquals(0, provider.actionRequests)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun notificationsActions_rejectsMissingKey() =
|
||||
runTest {
|
||||
val provider =
|
||||
FakeNotificationsStateProvider(
|
||||
DeviceNotificationSnapshot(
|
||||
enabled = true,
|
||||
connected = true,
|
||||
notifications = listOf(sampleEntry("n3")),
|
||||
),
|
||||
)
|
||||
val handler = NotificationsHandler.forTesting(appContext = appContext(), stateProvider = provider)
|
||||
|
||||
val result = handler.handleNotificationsActions("""{"action":"open"}""")
|
||||
|
||||
assertFalse(result.ok)
|
||||
assertEquals("INVALID_REQUEST", result.error?.code)
|
||||
assertEquals(0, provider.actionRequests)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun notificationsActions_rejectsInvalidAction() =
|
||||
runTest {
|
||||
val provider =
|
||||
FakeNotificationsStateProvider(
|
||||
DeviceNotificationSnapshot(
|
||||
enabled = true,
|
||||
connected = true,
|
||||
notifications = listOf(sampleEntry("n3")),
|
||||
),
|
||||
)
|
||||
val handler = NotificationsHandler.forTesting(appContext = appContext(), stateProvider = provider)
|
||||
|
||||
val result = handler.handleNotificationsActions("""{"key":"n3","action":"archive"}""")
|
||||
|
||||
assertFalse(result.ok)
|
||||
assertEquals("INVALID_REQUEST", result.error?.code)
|
||||
assertEquals(0, provider.actionRequests)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun notificationsActions_propagatesProviderError() =
|
||||
runTest {
|
||||
@@ -207,29 +167,6 @@ class NotificationsHandlerTest {
|
||||
assertEquals(1, provider.actionRequests)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun notificationsActions_fallsBackWhenProviderOmitsErrorDetails() =
|
||||
runTest {
|
||||
val provider =
|
||||
FakeNotificationsStateProvider(
|
||||
DeviceNotificationSnapshot(
|
||||
enabled = true,
|
||||
connected = true,
|
||||
notifications = listOf(sampleEntry("n4")),
|
||||
),
|
||||
).also {
|
||||
it.actionResult = NotificationActionResult(ok = false)
|
||||
}
|
||||
val handler = NotificationsHandler.forTesting(appContext = appContext(), stateProvider = provider)
|
||||
|
||||
val result = handler.handleNotificationsActions("""{"key":"n4","action":"open"}""")
|
||||
|
||||
assertFalse(result.ok)
|
||||
assertEquals("UNAVAILABLE", result.error?.code)
|
||||
assertEquals("notification action failed", result.error?.message)
|
||||
assertEquals(1, provider.actionRequests)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun notificationsActions_requestsRebindWhenEnabledButDisconnected() =
|
||||
runTest {
|
||||
|
||||
@@ -1,39 +1,15 @@
|
||||
package ai.openclaw.app.node
|
||||
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SmsManagerTest {
|
||||
private val json = SmsManager.JsonConfig
|
||||
|
||||
private fun smsMessage(
|
||||
id: Long,
|
||||
date: Long,
|
||||
status: Int = 0,
|
||||
body: String? = "msg-$id",
|
||||
transportType: String? = null,
|
||||
): SmsManager.SmsMessage =
|
||||
SmsManager.SmsMessage(
|
||||
id = id,
|
||||
threadId = 1L,
|
||||
address = "+15551234567",
|
||||
person = null,
|
||||
date = date,
|
||||
dateSent = date,
|
||||
read = true,
|
||||
type = 1,
|
||||
body = body,
|
||||
status = status,
|
||||
transportType = transportType,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun parseParamsRejectsEmptyPayload() {
|
||||
val result = SmsManager.parseParams("", json)
|
||||
@@ -85,73 +61,6 @@ class SmsManagerTest {
|
||||
assertEquals("Hello", ok.params.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsDefaultsWhenPayloadEmpty() {
|
||||
val result = SmsManager.parseQueryParams(null, json)
|
||||
assertTrue(result is SmsManager.QueryParseResult.Ok)
|
||||
val ok = result as SmsManager.QueryParseResult.Ok
|
||||
assertEquals(25, ok.params.limit)
|
||||
assertEquals(0, ok.params.offset)
|
||||
assertEquals(null, ok.params.startTime)
|
||||
assertEquals(null, ok.params.endTime)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsRejectsInvalidJson() {
|
||||
val result = SmsManager.parseQueryParams("not-json", json)
|
||||
assertTrue(result is SmsManager.QueryParseResult.Error)
|
||||
val error = result as SmsManager.QueryParseResult.Error
|
||||
assertEquals("INVALID_REQUEST: expected JSON object", error.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsRejectsInvertedTimeRange() {
|
||||
val result = SmsManager.parseQueryParams("{\"startTime\":200,\"endTime\":100}", json)
|
||||
assertTrue(result is SmsManager.QueryParseResult.Error)
|
||||
val error = result as SmsManager.QueryParseResult.Error
|
||||
assertEquals("INVALID_REQUEST: startTime must be less than or equal to endTime", error.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsClampsLimitAndOffset() {
|
||||
val result = SmsManager.parseQueryParams("{\"limit\":999,\"offset\":-5}", json)
|
||||
assertTrue(result is SmsManager.QueryParseResult.Ok)
|
||||
val ok = result as SmsManager.QueryParseResult.Ok
|
||||
assertEquals(200, ok.params.limit)
|
||||
assertEquals(0, ok.params.offset)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsParsesAllSupportedFields() {
|
||||
val result = SmsManager.parseQueryParams(
|
||||
"""
|
||||
{
|
||||
"startTime": 100,
|
||||
"endTime": 200,
|
||||
"contactName": " Leah ",
|
||||
"phoneNumber": " +1555 ",
|
||||
"keyword": " ping ",
|
||||
"type": 1,
|
||||
"isRead": true,
|
||||
"limit": 10,
|
||||
"offset": 2
|
||||
}
|
||||
""".trimIndent(),
|
||||
json,
|
||||
)
|
||||
assertTrue(result is SmsManager.QueryParseResult.Ok)
|
||||
val ok = result as SmsManager.QueryParseResult.Ok
|
||||
assertEquals(100L, ok.params.startTime)
|
||||
assertEquals(200L, ok.params.endTime)
|
||||
assertEquals("Leah", ok.params.contactName)
|
||||
assertEquals("+1555", ok.params.phoneNumber)
|
||||
assertEquals("ping", ok.params.keyword)
|
||||
assertEquals(1, ok.params.type)
|
||||
assertEquals(true, ok.params.isRead)
|
||||
assertEquals(10, ok.params.limit)
|
||||
assertEquals(2, ok.params.offset)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildPayloadJsonEscapesFields() {
|
||||
val payload = SmsManager.buildPayloadJson(
|
||||
@@ -166,69 +75,6 @@ class SmsManagerTest {
|
||||
assertEquals("SMS_SEND_FAILED: \"nope\"", parsed["error"]?.jsonPrimitive?.content)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildQueryPayloadJsonIncludesCountAndMessages() {
|
||||
val payload = SmsManager.buildQueryPayloadJson(
|
||||
json = json,
|
||||
ok = true,
|
||||
messages = listOf(
|
||||
SmsManager.SmsMessage(
|
||||
id = 1L,
|
||||
threadId = 2L,
|
||||
address = "+1555",
|
||||
person = null,
|
||||
date = 123L,
|
||||
dateSent = 124L,
|
||||
read = true,
|
||||
type = 1,
|
||||
body = "hello",
|
||||
status = 0,
|
||||
)
|
||||
),
|
||||
)
|
||||
val parsed = json.parseToJsonElement(payload).jsonObject
|
||||
assertEquals("true", parsed["ok"]?.jsonPrimitive?.content)
|
||||
assertEquals(1, parsed["count"]?.jsonPrimitive?.content?.toInt())
|
||||
val messages = parsed["messages"]?.jsonArray
|
||||
assertEquals(1, messages?.size)
|
||||
assertEquals("hello", messages?.get(0)?.jsonObject?.get("body")?.jsonPrimitive?.content)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildQueryPayloadJsonIncludesErrorOnFailure() {
|
||||
val payload = SmsManager.buildQueryPayloadJson(
|
||||
json = json,
|
||||
ok = false,
|
||||
messages = emptyList(),
|
||||
error = "SMS_QUERY_FAILED: nope",
|
||||
)
|
||||
val parsed = json.parseToJsonElement(payload).jsonObject
|
||||
assertEquals("false", parsed["ok"]?.jsonPrimitive?.content)
|
||||
assertEquals(0, parsed["count"]?.jsonPrimitive?.content?.toInt())
|
||||
assertEquals("SMS_QUERY_FAILED: nope", parsed["error"]?.jsonPrimitive?.content)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildQueryPayloadJsonIncludesMmsMetadataWhenProvided() {
|
||||
val payload = SmsManager.buildQueryPayloadJson(
|
||||
json = json,
|
||||
ok = true,
|
||||
messages = listOf(smsMessage(id = 1L, date = 1000L)),
|
||||
queryMetadata =
|
||||
SmsManager.QueryMetadata(
|
||||
mmsRequested = true,
|
||||
mmsEligible = true,
|
||||
mmsAttempted = true,
|
||||
mmsIncluded = false,
|
||||
),
|
||||
)
|
||||
val parsed = json.parseToJsonElement(payload).jsonObject
|
||||
assertEquals("true", parsed["mmsRequested"]?.jsonPrimitive?.content)
|
||||
assertEquals("true", parsed["mmsEligible"]?.jsonPrimitive?.content)
|
||||
assertEquals("true", parsed["mmsAttempted"]?.jsonPrimitive?.content)
|
||||
assertEquals("false", parsed["mmsIncluded"]?.jsonPrimitive?.content)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildSendPlanUsesMultipartWhenMultipleParts() {
|
||||
val plan = SmsManager.buildSendPlan("hello") { listOf("a", "b") }
|
||||
@@ -252,6 +98,14 @@ class SmsManagerTest {
|
||||
assertEquals(0, ok.params.offset)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsRejectsInvalidJson() {
|
||||
val result = SmsManager.parseQueryParams("not-json", json)
|
||||
assertTrue(result is SmsManager.QueryParseResult.Error)
|
||||
val error = result as SmsManager.QueryParseResult.Error
|
||||
assertEquals("INVALID_REQUEST: expected JSON object", error.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsRejectsNonObjectJson() {
|
||||
val result = SmsManager.parseQueryParams("[]", json)
|
||||
@@ -325,749 +179,4 @@ class SmsManagerTest {
|
||||
val ok = result as SmsManager.QueryParseResult.Ok
|
||||
assertEquals(true, ok.params.isRead)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsIncludeMmsDefaultsFalse() {
|
||||
val result = SmsManager.parseQueryParams("{}", json)
|
||||
assertTrue(result is SmsManager.QueryParseResult.Ok)
|
||||
val ok = result as SmsManager.QueryParseResult.Ok
|
||||
assertFalse(ok.params.includeMms)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsParsesIncludeMmsTrue() {
|
||||
val result = SmsManager.parseQueryParams("{\"includeMms\":true}", json)
|
||||
assertTrue(result is SmsManager.QueryParseResult.Ok)
|
||||
val ok = result as SmsManager.QueryParseResult.Ok
|
||||
assertTrue(ok.params.includeMms)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseQueryParamsParsesConversationReviewTrue() {
|
||||
val result = SmsManager.parseQueryParams("{\"conversationReview\":true}", json)
|
||||
assertTrue(result is SmsManager.QueryParseResult.Ok)
|
||||
val ok = result as SmsManager.QueryParseResult.Ok
|
||||
assertTrue(ok.params.conversationReview)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toByPhoneLookupNumberStripsFormattingToDigits() {
|
||||
assertEquals("12107588120", SmsManager.toByPhoneLookupNumber("+1 (210) 758-8120"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizePhoneNumberOrNullReturnsNullForFormattingOnlyInput() {
|
||||
assertNull(SmsManager.normalizePhoneNumberOrNull("() - "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizePhoneNumberOrNullReturnsNullForPlusOnlyInput() {
|
||||
assertNull(SmsManager.normalizePhoneNumberOrNull(" + "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizePhoneNumberOrNullKeepsUsableNormalizedNumber() {
|
||||
assertEquals("+15551234567", SmsManager.normalizePhoneNumberOrNull(" +1 (555) 123-4567 "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sanitizeContactPhoneNumberOrNullDropsFormattingOnlyInput() {
|
||||
assertNull(SmsManager.sanitizeContactPhoneNumberOrNull(" () - "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sanitizeContactPhoneNumberOrNullDropsPlusOnlyInput() {
|
||||
assertNull(SmsManager.sanitizeContactPhoneNumberOrNull(" + "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sanitizeContactPhoneNumberOrNullKeepsUsableNormalizedNumber() {
|
||||
assertEquals("+15551234567", SmsManager.sanitizeContactPhoneNumberOrNull(" +1 (555) 123-4567 "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sanitizeContactPhoneNumberOrNullDropsPercentWildcardInput() {
|
||||
assertNull(SmsManager.sanitizeContactPhoneNumberOrNull("1%2"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sanitizeContactPhoneNumberOrNullDropsUnderscoreWildcardInput() {
|
||||
assertNull(SmsManager.sanitizeContactPhoneNumberOrNull("1_2"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldPromptForContactNameSearchPermissionTrueForContactNameOnlyWithoutContactsAccess() {
|
||||
assertTrue(
|
||||
SmsManager.shouldPromptForContactNameSearchPermission(
|
||||
contactName = "Alice",
|
||||
phoneNumber = null,
|
||||
hasReadContactsPermission = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldPromptForContactNameSearchPermissionFalseWhenExplicitPhoneFallbackExists() {
|
||||
assertFalse(
|
||||
SmsManager.shouldPromptForContactNameSearchPermission(
|
||||
contactName = "Alice",
|
||||
phoneNumber = "+15551234567",
|
||||
hasReadContactsPermission = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldPromptForContactNameSearchPermissionFalseWhenContactsAlreadyGranted() {
|
||||
assertFalse(
|
||||
SmsManager.shouldPromptForContactNameSearchPermission(
|
||||
contactName = "Alice",
|
||||
phoneNumber = null,
|
||||
hasReadContactsPermission = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun escapeSqlLikeLiteralEscapesPercentUnderscoreAndBackslash() {
|
||||
assertEquals("\\%a\\_b\\\\c", SmsManager.escapeSqlLikeLiteral("%a_b\\c"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun escapeSqlLikeLiteralLeavesOrdinaryTextUnchanged() {
|
||||
assertEquals("Leah", SmsManager.escapeSqlLikeLiteral("Leah"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildContactNameLikeSelectionUsesSingleBackslashEscapeLiteral() {
|
||||
assertEquals(
|
||||
"display_name LIKE ? ESCAPE '\\'",
|
||||
SmsManager.buildContactNameLikeSelection(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildContactNameLikeArgEscapesWildcardsAndBackslash() {
|
||||
assertEquals("%\\%a\\_b\\\\c%", SmsManager.buildContactNameLikeArg("%a_b\\c"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildKeywordLikeSelectionUsesSingleBackslashEscapeLiteral() {
|
||||
assertEquals(
|
||||
"body LIKE ? ESCAPE '\\'",
|
||||
SmsManager.buildKeywordLikeSelection(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildKeywordLikeArgEscapesWildcardsAndBackslash() {
|
||||
assertEquals("%\\%a\\_b\\\\c%", SmsManager.buildKeywordLikeArg("%a_b\\c"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildMixedByPhoneProjectionMatchesExpectedStatusAwareShape() {
|
||||
assertArrayEquals(
|
||||
arrayOf(
|
||||
"_id",
|
||||
"thread_id",
|
||||
"transport_type",
|
||||
"address",
|
||||
"date",
|
||||
"date_sent",
|
||||
"read",
|
||||
"type",
|
||||
"body",
|
||||
"status",
|
||||
),
|
||||
SmsManager.buildMixedByPhoneProjection(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun compareByPhoneCandidateOrderUsesDateThenIdDescending() {
|
||||
val newer = smsMessage(id = 1L, date = 2000L)
|
||||
val older = smsMessage(id = 2L, date = 1000L)
|
||||
val sameDateHigherId = smsMessage(id = 9L, date = 1500L)
|
||||
val sameDateLowerId = smsMessage(id = 3L, date = 1500L)
|
||||
|
||||
assertTrue(SmsManager.compareByPhoneCandidateOrder(newer, older) < 0)
|
||||
assertTrue(SmsManager.compareByPhoneCandidateOrder(sameDateHigherId, sameDateLowerId) < 0)
|
||||
assertTrue(SmsManager.compareByPhoneCandidateOrder(sameDateLowerId, sameDateHigherId) > 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun upsertTopDateCandidatesKeepsDescendingOrderAndBounds() {
|
||||
val candidates = mutableListOf<Pair<String, SmsManager.SmsMessage>>()
|
||||
val max = 2
|
||||
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:1", smsMessage(id = 1L, date = 1700L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:2", smsMessage(id = 2L, date = 2000L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:3", smsMessage(id = 3L, date = 1500L), max)
|
||||
|
||||
assertEquals(listOf(2L, 1L), candidates.map { it.second.id })
|
||||
assertEquals(listOf(2000L, 1700L), candidates.map { it.second.date })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun upsertTopDateCandidatesSupportsDefaultMixedPathBoundedWindow() {
|
||||
val params = SmsManager.QueryParams(limit = 3, offset = 2, includeMms = true, phoneNumber = "+15551234567")
|
||||
val candidates = mutableListOf<Pair<String, SmsManager.SmsMessage>>()
|
||||
val max = params.offset + params.limit
|
||||
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:1", smsMessage(id = 1L, date = 1000L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:2", smsMessage(id = 2L, date = 2000L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:3", smsMessage(id = 3L, date = 3000L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:4", smsMessage(id = 4L, date = 4000L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:5", smsMessage(id = 5L, date = 5000L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:6", smsMessage(id = 6L, date = 6000L), max)
|
||||
|
||||
assertEquals(5, candidates.size)
|
||||
assertEquals(listOf(6L, 5L, 4L, 3L, 2L), candidates.map { it.second.id })
|
||||
assertEquals(listOf(4000L, 3000L, 2000L), SmsManager.pageByPhoneCandidates(candidates.map { it.second }, params).map { it.date })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun upsertTopDateCandidatesDedupesBySourceAwareIdentityAndKeepsBestOrdering() {
|
||||
val candidates = mutableListOf<Pair<String, SmsManager.SmsMessage>>()
|
||||
val max = 5
|
||||
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:1987", smsMessage(id = 1987L, date = 1773950752506L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:1986", smsMessage(id = 1986L, date = 1773899354039L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:1985", smsMessage(id = 1985L, date = 1773872989602L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:1981", smsMessage(id = 1981L, date = 1773790733566L), max)
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:1976", smsMessage(id = 1976L, date = 1773784153770L), max)
|
||||
|
||||
// same source-aware identity should replace, not duplicate
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:1986", smsMessage(id = 1986L, date = 1773899354039L), max)
|
||||
// different source-aware identity with same raw id must be preserved
|
||||
SmsManager.upsertTopDateCandidates(candidates, "mms:1986", smsMessage(id = 1986L, date = 1773899354038L), max)
|
||||
|
||||
assertEquals(5, candidates.size)
|
||||
assertEquals(2, candidates.count { it.second.id == 1986L })
|
||||
assertEquals(listOf("sms:1987", "sms:1986", "mms:1986", "sms:1985", "sms:1981"), candidates.map { it.first })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun materializeByPhoneCandidateDedupesBySourceAwareIdentity() {
|
||||
val candidates = linkedMapOf<String, SmsManager.SmsMessage>()
|
||||
|
||||
SmsManager.materializeByPhoneCandidate(candidates, "sms:1", smsMessage(id = 1L, date = 1000L))
|
||||
SmsManager.materializeByPhoneCandidate(candidates, "sms:1", smsMessage(id = 1L, date = 2000L))
|
||||
SmsManager.materializeByPhoneCandidate(candidates, "mms:1", smsMessage(id = 1L, date = 1500L))
|
||||
|
||||
assertEquals(2, candidates.size)
|
||||
assertEquals(2000L, candidates["sms:1"]?.date)
|
||||
assertEquals(1500L, candidates["mms:1"]?.date)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun collectMixedByPhoneCandidateUsesBoundedCollectorWhenReviewModeDisabled() {
|
||||
val topCandidates = mutableListOf<Pair<String, SmsManager.SmsMessage>>()
|
||||
val materializedCandidates = linkedMapOf<String, SmsManager.SmsMessage>()
|
||||
|
||||
SmsManager.collectMixedByPhoneCandidate(
|
||||
topCandidates = topCandidates,
|
||||
materializedCandidates = materializedCandidates,
|
||||
identityKey = "sms:1",
|
||||
message = smsMessage(id = 1L, date = 1000L),
|
||||
maxCandidates = 1,
|
||||
reviewMode = false,
|
||||
)
|
||||
SmsManager.collectMixedByPhoneCandidate(
|
||||
topCandidates = topCandidates,
|
||||
materializedCandidates = materializedCandidates,
|
||||
identityKey = "mms:2",
|
||||
message = smsMessage(id = 2L, date = 2000L, transportType = "mms"),
|
||||
maxCandidates = 1,
|
||||
reviewMode = false,
|
||||
)
|
||||
|
||||
assertEquals(listOf(2L), topCandidates.map { it.second.id })
|
||||
assertTrue(materializedCandidates.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun collectMixedByPhoneCandidateMaterializesFullSetWhenReviewModeEnabled() {
|
||||
val topCandidates = mutableListOf<Pair<String, SmsManager.SmsMessage>>()
|
||||
val materializedCandidates = linkedMapOf<String, SmsManager.SmsMessage>()
|
||||
|
||||
SmsManager.collectMixedByPhoneCandidate(
|
||||
topCandidates = topCandidates,
|
||||
materializedCandidates = materializedCandidates,
|
||||
identityKey = "sms:1",
|
||||
message = smsMessage(id = 1L, date = 1000L),
|
||||
maxCandidates = 1,
|
||||
reviewMode = true,
|
||||
)
|
||||
SmsManager.collectMixedByPhoneCandidate(
|
||||
topCandidates = topCandidates,
|
||||
materializedCandidates = materializedCandidates,
|
||||
identityKey = "mms:2",
|
||||
message = smsMessage(id = 2L, date = 2000L, transportType = "mms"),
|
||||
maxCandidates = 1,
|
||||
reviewMode = true,
|
||||
)
|
||||
|
||||
assertTrue(topCandidates.isEmpty())
|
||||
assertEquals(listOf(1L, 2L), materializedCandidates.values.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pageMixedByPhoneCandidatesLetsReviewModeSurfaceOlderRowsBeyondBoundedDefaultWindow() {
|
||||
val params =
|
||||
SmsManager.QueryParams(
|
||||
limit = 2,
|
||||
offset = 2,
|
||||
includeMms = true,
|
||||
phoneNumber = "+15551234567",
|
||||
conversationReview = true,
|
||||
)
|
||||
val topCandidates = listOf(
|
||||
"sms:9" to smsMessage(id = 9L, date = 9000L),
|
||||
"sms:8" to smsMessage(id = 8L, date = 8000L),
|
||||
"sms:7" to smsMessage(id = 7L, date = 7000L),
|
||||
)
|
||||
val materializedCandidates =
|
||||
linkedMapOf(
|
||||
"sms:9" to smsMessage(id = 9L, date = 9000L),
|
||||
"sms:8" to smsMessage(id = 8L, date = 8000L),
|
||||
"sms:7" to smsMessage(id = 7L, date = 7000L),
|
||||
"mms:6" to smsMessage(id = 6L, date = 6000L, transportType = "mms"),
|
||||
)
|
||||
|
||||
val defaultPage =
|
||||
SmsManager.pageMixedByPhoneCandidates(
|
||||
topCandidates = topCandidates,
|
||||
materializedCandidates = materializedCandidates,
|
||||
params = params.copy(conversationReview = false),
|
||||
reviewMode = false,
|
||||
)
|
||||
val reviewPage =
|
||||
SmsManager.pageMixedByPhoneCandidates(
|
||||
topCandidates = topCandidates,
|
||||
materializedCandidates = materializedCandidates,
|
||||
params = params,
|
||||
reviewMode = true,
|
||||
)
|
||||
|
||||
assertEquals(listOf(7L), defaultPage.map { it.id })
|
||||
assertEquals(listOf(7L, 6L), reviewPage.map { it.id })
|
||||
assertEquals(4, materializedCandidates.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pageByPhoneCandidatesHonorsDeepOffsetAfterStableSort() {
|
||||
val params = SmsManager.QueryParams(limit = 5, offset = 5, includeMms = true)
|
||||
val candidates = listOf(
|
||||
smsMessage(id = 1399L, date = 1741112335720L),
|
||||
smsMessage(id = 1976L, date = 1773784153770L),
|
||||
smsMessage(id = 1981L, date = 1773790733566L),
|
||||
smsMessage(id = 1985L, date = 1773872989602L),
|
||||
smsMessage(id = 1986L, date = 1773899354039L),
|
||||
smsMessage(id = 1987L, date = 1773950752506L),
|
||||
)
|
||||
|
||||
assertEquals(listOf(1399L), SmsManager.pageByPhoneCandidates(candidates, params).map { it.id })
|
||||
assertTrue(SmsManager.pageByPhoneCandidates(candidates, params.copy(offset = 10)).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun upsertTopDateCandidatesNoOpWhenMaxIsZero() {
|
||||
val candidates = mutableListOf<Pair<String, SmsManager.SmsMessage>>()
|
||||
SmsManager.upsertTopDateCandidates(candidates, "sms:1", smsMessage(id = 1L, date = 2000L), 0)
|
||||
assertTrue(candidates.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildMixedRowIdentityUsesTransportTypeAndRowId() {
|
||||
assertEquals("sms:7", SmsManager.buildMixedRowIdentity(7L, "sms"))
|
||||
assertEquals("mms:7", SmsManager.buildMixedRowIdentity(7L, "mms"))
|
||||
assertEquals("unknown:7", SmsManager.buildMixedRowIdentity(7L, null))
|
||||
assertEquals("unknown:7", SmsManager.buildMixedRowIdentity(7L, ""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeProviderDateMillisConvertsSecondsToMillis() {
|
||||
assertEquals(1773944910000L, SmsManager.normalizeProviderDateMillis(1773944910L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeProviderDateMillisKeepsMillisUnchanged() {
|
||||
assertEquals(1773944910123L, SmsManager.normalizeProviderDateMillis(1773944910123L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeProviderDateMillisKeepsHistoricMillisUnchanged() {
|
||||
assertEquals(946684800000L, SmsManager.normalizeProviderDateMillis(946684800000L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveMixedByPhoneRowStatusPreservesRealSmsStatus() {
|
||||
assertEquals(64, SmsManager.resolveMixedByPhoneRowStatus("sms", 64))
|
||||
assertEquals(32, SmsManager.resolveMixedByPhoneRowStatus(null, 32))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveMixedByPhoneRowStatusKeepsMmsOnSentinelValue() {
|
||||
assertEquals(-1, SmsManager.resolveMixedByPhoneRowStatus("mms", 64))
|
||||
assertEquals(-1, SmsManager.resolveMixedByPhoneRowStatus("MMS", null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveMixedByPhoneRowStatusFallsBackToZeroWhenSmsStatusMissing() {
|
||||
assertEquals(0, SmsManager.resolveMixedByPhoneRowStatus("sms", null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveMixedByPhoneRowAddressPreservesProviderAddressWhenPresent() {
|
||||
assertEquals(
|
||||
"+12107588120",
|
||||
SmsManager.resolveMixedByPhoneRowAddress("+12107588120", "12107588120"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveMixedByPhoneRowAddressFallsBackToLookupNumberWhenProviderAddressMissing() {
|
||||
assertEquals(
|
||||
"12107588120",
|
||||
SmsManager.resolveMixedByPhoneRowAddress(null, "12107588120"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveMixedByPhoneRowAddressCanPreserveLookupNumberWhenProviderAlreadyReturnsIt() {
|
||||
assertEquals(
|
||||
"12107588120",
|
||||
SmsManager.resolveMixedByPhoneRowAddress("12107588120", "12107588120"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveMixedByPhoneRowAddressPreservesNonMatchingProviderAddress() {
|
||||
assertEquals(
|
||||
"+13105550123",
|
||||
SmsManager.resolveMixedByPhoneRowAddress("+13105550123", "12107588120"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveMixedByPhoneRowAddressPrefersResolvedMmsParticipantAddress() {
|
||||
assertEquals(
|
||||
"+13105550123",
|
||||
SmsManager.resolveMixedByPhoneRowAddress("insert-address-token", "12107588120", "+13105550123"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun selectPreferredMmsAddressPrefersType137AddressThatDoesNotMatchLookup() {
|
||||
assertEquals(
|
||||
"+13105550123",
|
||||
SmsManager.selectPreferredMmsAddress(
|
||||
listOf(
|
||||
"+12107588120" to 151,
|
||||
"+13105550123" to 137,
|
||||
"+12107588120" to 130,
|
||||
),
|
||||
"12107588120",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun selectPreferredMmsAddressFallsBackToFirstNormalizedAddressWhenOnlyLookupMatchesExist() {
|
||||
assertEquals(
|
||||
"+12107588120",
|
||||
SmsManager.selectPreferredMmsAddress(
|
||||
listOf(
|
||||
"insert-address-token" to 137,
|
||||
"+12107588120" to 151,
|
||||
),
|
||||
"12107588120",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun isExplicitPhoneInputInvalidTrueWhenCallerSuppliesOnlyFormatting() {
|
||||
val normalized = SmsManager.normalizePhoneNumberOrNull(" + ")
|
||||
assertTrue(SmsManager.isExplicitPhoneInputInvalid(" + ", normalized))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hasSqlLikeWildcardDetectsPercentAndUnderscore() {
|
||||
assertTrue(SmsManager.hasSqlLikeWildcard("+1555%1234"))
|
||||
assertTrue(SmsManager.hasSqlLikeWildcard("+1555_1234"))
|
||||
assertFalse(SmsManager.hasSqlLikeWildcard("+15551234"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun isExplicitPhoneInputInvalidRejectsLikeWildcardPhoneFilter() {
|
||||
assertTrue(SmsManager.isExplicitPhoneInputInvalid("+1555%1234", "+1555%1234"))
|
||||
assertTrue(SmsManager.isExplicitPhoneInputInvalid("+1555_1234", "+1555_1234"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun isExplicitPhoneInputInvalidFalseWhenPhoneWasOmitted() {
|
||||
assertFalse(SmsManager.isExplicitPhoneInputInvalid(null, null))
|
||||
assertFalse(SmsManager.isExplicitPhoneInputInvalid(" ", null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mapMmsMsgBoxToSearchTypeCoversSearchRelevantMmsBoxes() {
|
||||
assertEquals(1, SmsManager.mapMmsMsgBoxToSearchType(1))
|
||||
assertEquals(2, SmsManager.mapMmsMsgBoxToSearchType(2))
|
||||
assertEquals(3, SmsManager.mapMmsMsgBoxToSearchType(3))
|
||||
assertEquals(4, SmsManager.mapMmsMsgBoxToSearchType(4))
|
||||
assertEquals(5, SmsManager.mapMmsMsgBoxToSearchType(5))
|
||||
assertEquals(6, SmsManager.mapMmsMsgBoxToSearchType(6))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mapMmsMsgBoxToSearchTypeLeavesUnsupportedBoxesUnmapped() {
|
||||
assertNull(SmsManager.mapMmsMsgBoxToSearchType(0))
|
||||
assertNull(SmsManager.mapMmsMsgBoxToSearchType(99))
|
||||
assertNull(SmsManager.mapMmsMsgBoxToSearchType(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldUseConversationReviewByPhoneModeOnlyForMixedByPhoneReviewPulls() {
|
||||
val active =
|
||||
SmsManager.QueryParams(
|
||||
limit = 5,
|
||||
offset = 0,
|
||||
isRead = null,
|
||||
contactName = null,
|
||||
phoneNumber = "+12107588120",
|
||||
keyword = null,
|
||||
startTime = null,
|
||||
endTime = null,
|
||||
includeMms = true,
|
||||
conversationReview = true,
|
||||
)
|
||||
val disabledByMode = active.copy(conversationReview = false)
|
||||
val disabledByMms = active.copy(includeMms = false)
|
||||
val disabledByPhone = active.copy(phoneNumber = null)
|
||||
|
||||
assertTrue(SmsManager.shouldUseConversationReviewByPhoneMode(active))
|
||||
assertFalse(SmsManager.shouldUseConversationReviewByPhoneMode(disabledByMode))
|
||||
assertFalse(SmsManager.shouldUseConversationReviewByPhoneMode(disabledByMms))
|
||||
assertFalse(SmsManager.shouldUseConversationReviewByPhoneMode(disabledByPhone))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun effectiveSearchParamsRaisesConversationReviewLimitFloor() {
|
||||
val params =
|
||||
SmsManager.QueryParams(
|
||||
limit = 5,
|
||||
offset = 0,
|
||||
isRead = null,
|
||||
contactName = null,
|
||||
phoneNumber = "+12107588120",
|
||||
keyword = null,
|
||||
startTime = null,
|
||||
endTime = null,
|
||||
includeMms = true,
|
||||
conversationReview = true,
|
||||
)
|
||||
|
||||
assertEquals(25, SmsManager.effectiveSearchParams(params).limit)
|
||||
assertEquals(40, SmsManager.effectiveSearchParams(params.copy(limit = 40)).limit)
|
||||
assertEquals(5, SmsManager.effectiveSearchParams(params.copy(conversationReview = false)).limit)
|
||||
|
||||
val singleResolvedContact = params.copy(phoneNumber = null, contactName = "Leah")
|
||||
assertEquals(25, SmsManager.effectiveSearchParams(singleResolvedContact, listOf("15551234567")).limit)
|
||||
assertEquals(5, SmsManager.effectiveSearchParams(singleResolvedContact, listOf("15551234567", "15557654321")).limit)
|
||||
assertEquals(
|
||||
SmsManager.effectiveSearchParams(params).limit,
|
||||
SmsManager.effectiveSearchParams(singleResolvedContact, listOf("15551234567")).limit,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveSearchParamsCarriesSingleResolvedContactIntoReviewMode() {
|
||||
val params =
|
||||
SmsManager.QueryParams(
|
||||
limit = 5,
|
||||
offset = 0,
|
||||
isRead = null,
|
||||
contactName = "Leah",
|
||||
phoneNumber = null,
|
||||
keyword = null,
|
||||
startTime = null,
|
||||
endTime = null,
|
||||
includeMms = true,
|
||||
conversationReview = true,
|
||||
)
|
||||
|
||||
val beforeResolution = SmsManager.resolveSearchParams(params, normalizedPhoneNumber = null)
|
||||
val singleResolved =
|
||||
SmsManager.resolveSearchParams(
|
||||
params,
|
||||
normalizedPhoneNumber = null,
|
||||
resolvedPhoneNumbers = listOf("15551234567"),
|
||||
)
|
||||
val multiResolved =
|
||||
SmsManager.resolveSearchParams(
|
||||
params,
|
||||
normalizedPhoneNumber = null,
|
||||
resolvedPhoneNumbers = listOf("15551234567", "15557654321"),
|
||||
)
|
||||
val explicit =
|
||||
SmsManager.resolveSearchParams(
|
||||
params.copy(contactName = null, phoneNumber = "+12107588120"),
|
||||
normalizedPhoneNumber = "12107588120",
|
||||
)
|
||||
val nonReview =
|
||||
SmsManager.resolveSearchParams(
|
||||
params.copy(conversationReview = false),
|
||||
normalizedPhoneNumber = null,
|
||||
resolvedPhoneNumbers = listOf("15551234567"),
|
||||
)
|
||||
|
||||
assertEquals(5, beforeResolution.limit)
|
||||
assertEquals(25, singleResolved.limit)
|
||||
assertEquals("15551234567", singleResolved.phoneNumber)
|
||||
assertTrue(SmsManager.shouldUseConversationReviewByPhoneMode(singleResolved))
|
||||
assertEquals(5, multiResolved.limit)
|
||||
assertNull(multiResolved.phoneNumber)
|
||||
assertFalse(SmsManager.shouldUseConversationReviewByPhoneMode(multiResolved))
|
||||
assertEquals(25, explicit.limit)
|
||||
assertEquals("12107588120", explicit.phoneNumber)
|
||||
assertEquals(5, nonReview.limit)
|
||||
assertEquals("15551234567", nonReview.phoneNumber)
|
||||
assertFalse(SmsManager.shouldUseConversationReviewByPhoneMode(nonReview))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun canonicalizeMixedPathPhoneFiltersDedupesEquivalentExplicitAndContactNumbers() {
|
||||
assertEquals(
|
||||
listOf("15551234567"),
|
||||
SmsManager.canonicalizeMixedPathPhoneFilters(listOf("+15551234567", "15551234567")),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun canonicalizeMixedPathPhoneFiltersDropsBlankByPhoneValues() {
|
||||
assertEquals(
|
||||
listOf("15551234567"),
|
||||
SmsManager.canonicalizeMixedPathPhoneFilters(listOf("+15551234567", "+", " ")),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildQueryMetadataUsesCanonicalizedSingleMixedFilterAsEligible() {
|
||||
val params = SmsManager.QueryParams(includeMms = true, phoneNumber = "+15551234567")
|
||||
val canonical = SmsManager.canonicalizeMixedPathPhoneFilters(listOf("+15551234567", "15551234567"))
|
||||
|
||||
val metadata = SmsManager.buildQueryMetadata(params, canonical, emptyList())
|
||||
|
||||
assertTrue(metadata.mmsEligible)
|
||||
assertTrue(metadata.mmsAttempted)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun requestedMixedByPhoneCandidateWindowAddsOffsetAndLimitSafely() {
|
||||
val params = SmsManager.QueryParams(includeMms = true, phoneNumber = "+15551234567", limit = 200, offset = 300)
|
||||
assertEquals(500L, SmsManager.requestedMixedByPhoneCandidateWindow(params))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exceedsMixedByPhoneCandidateWindowFalseAtSupportedBoundary() {
|
||||
val params = SmsManager.QueryParams(includeMms = true, phoneNumber = "+15551234567", limit = 200, offset = 300)
|
||||
assertFalse(SmsManager.exceedsMixedByPhoneCandidateWindow(params, listOf("+15551234567")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exceedsMixedByPhoneCandidateWindowTrueWhenSingleNumberMixedWindowTooLarge() {
|
||||
val params = SmsManager.QueryParams(includeMms = true, phoneNumber = "+15551234567", limit = 200, offset = 301)
|
||||
assertTrue(SmsManager.exceedsMixedByPhoneCandidateWindow(params, listOf("+15551234567")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exceedsMixedByPhoneCandidateWindowFalseForSmsOnlyQueries() {
|
||||
val params = SmsManager.QueryParams(includeMms = false, phoneNumber = "+15551234567", limit = 200, offset = 50000)
|
||||
assertFalse(SmsManager.exceedsMixedByPhoneCandidateWindow(params, listOf("+15551234567")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exceedsMixedByPhoneCandidateWindowFalseWhenMultiplePhoneNumbersDisableMixedByPhonePath() {
|
||||
val params = SmsManager.QueryParams(includeMms = true, phoneNumber = null, limit = 200, offset = 50000)
|
||||
assertFalse(SmsManager.exceedsMixedByPhoneCandidateWindow(params, listOf("+15551234567", "+15557654321")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mixedByPhoneWindowErrorMentionsSupportedWindow() {
|
||||
assertEquals(
|
||||
"INVALID_REQUEST: includeMms offset+limit exceeds supported window (500)",
|
||||
SmsManager.mixedByPhoneWindowError(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildQueryMetadataMarksIneligibleWhenIncludeMmsNotRequested() {
|
||||
val params = SmsManager.QueryParams(includeMms = false)
|
||||
|
||||
val metadata = SmsManager.buildQueryMetadata(params, emptyList(), emptyList())
|
||||
|
||||
assertFalse(metadata.mmsRequested)
|
||||
assertFalse(metadata.mmsEligible)
|
||||
assertFalse(metadata.mmsAttempted)
|
||||
assertFalse(metadata.mmsIncluded)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildQueryMetadataMarksEligibleAttemptedButNotIncludedForSingleNumberFallback() {
|
||||
val params = SmsManager.QueryParams(includeMms = true, phoneNumber = "+15551234567")
|
||||
val messages = listOf(smsMessage(id = 1L, date = 1000L))
|
||||
|
||||
val metadata = SmsManager.buildQueryMetadata(params, listOf("+15551234567"), messages)
|
||||
|
||||
assertTrue(metadata.mmsRequested)
|
||||
assertTrue(metadata.mmsEligible)
|
||||
assertTrue(metadata.mmsAttempted)
|
||||
assertFalse(metadata.mmsIncluded)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun isMmsTransportRowTrueOnlyForMmsTransport() {
|
||||
assertTrue(SmsManager.isMmsTransportRow(smsMessage(id = 1L, date = 1000L, transportType = "mms")))
|
||||
assertFalse(SmsManager.isMmsTransportRow(smsMessage(id = 2L, date = 1000L, transportType = "sms")))
|
||||
assertFalse(SmsManager.isMmsTransportRow(smsMessage(id = 3L, date = 1000L, transportType = null)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldHydrateMmsByPhoneRowTrueOnlyForMmsTransportWithBlankBodyOrZeroType() {
|
||||
assertTrue(SmsManager.shouldHydrateMmsByPhoneRow("mms", null, 1))
|
||||
assertTrue(SmsManager.shouldHydrateMmsByPhoneRow("mms", "", 1))
|
||||
assertTrue(SmsManager.shouldHydrateMmsByPhoneRow("mms", "body", 0))
|
||||
assertFalse(SmsManager.shouldHydrateMmsByPhoneRow("sms", null, 0))
|
||||
assertFalse(SmsManager.shouldHydrateMmsByPhoneRow(null, null, 0))
|
||||
assertFalse(SmsManager.shouldHydrateMmsByPhoneRow("mms", "body", 1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildQueryMetadataDoesNotTreatSmsStatusSentinelAsMmsInclusion() {
|
||||
val params = SmsManager.QueryParams(includeMms = true, phoneNumber = "+15551234567")
|
||||
val smsLikeMessage = smsMessage(id = 7L, date = 1000L, status = -1, transportType = "sms")
|
||||
|
||||
val metadata = SmsManager.buildQueryMetadata(params, listOf("15551234567"), listOf(smsLikeMessage))
|
||||
|
||||
assertTrue(metadata.mmsRequested)
|
||||
assertTrue(metadata.mmsEligible)
|
||||
assertTrue(metadata.mmsAttempted)
|
||||
assertFalse(metadata.mmsIncluded)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildQueryMetadataMarksIncludedWhenMixedQueryYieldsMmsTransportRow() {
|
||||
val params = SmsManager.QueryParams(includeMms = true, phoneNumber = "+15551234567")
|
||||
val mmsTransportMessage = smsMessage(id = 7L, date = 1000L, status = 0, body = null, transportType = "mms")
|
||||
|
||||
val metadata = SmsManager.buildQueryMetadata(params, listOf("15551234567"), listOf(mmsTransportMessage))
|
||||
|
||||
assertTrue(metadata.mmsRequested)
|
||||
assertTrue(metadata.mmsEligible)
|
||||
assertTrue(metadata.mmsAttempted)
|
||||
assertTrue(metadata.mmsIncluded)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,16 +26,6 @@ class SystemHandlerTest {
|
||||
assertEquals("INVALID_REQUEST", result.error?.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleSystemNotify_rejectsInvalidRequestObject() {
|
||||
val handler = SystemHandler.forTesting(poster = FakePoster(authorized = true))
|
||||
|
||||
val result = handler.handleSystemNotify("""{"title":"OpenClaw"}""")
|
||||
|
||||
assertFalse(result.ok)
|
||||
assertEquals("INVALID_REQUEST", result.error?.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleSystemNotify_postsNotification() {
|
||||
val poster = FakePoster(authorized = true)
|
||||
@@ -47,23 +37,6 @@ class SystemHandlerTest {
|
||||
assertEquals(1, poster.posts)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleSystemNotify_trimsAndPassesOptionalFields() {
|
||||
val poster = FakePoster(authorized = true)
|
||||
val handler = SystemHandler.forTesting(poster = poster)
|
||||
|
||||
val result =
|
||||
handler.handleSystemNotify(
|
||||
"""{"title":" OpenClaw ","body":" done ","priority":" passive ","sound":" silent "}""",
|
||||
)
|
||||
|
||||
assertTrue(result.ok)
|
||||
assertEquals("OpenClaw", poster.lastRequest?.title)
|
||||
assertEquals("done", poster.lastRequest?.body)
|
||||
assertEquals("passive", poster.lastRequest?.priority)
|
||||
assertEquals("silent", poster.lastRequest?.sound)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handleSystemNotify_returnsUnauthorizedWhenPostFailsPermission() {
|
||||
val handler = SystemHandler.forTesting(poster = ThrowingPoster(authorized = true, error = SecurityException("denied")))
|
||||
@@ -82,7 +55,6 @@ class SystemHandlerTest {
|
||||
|
||||
assertFalse(result.ok)
|
||||
assertEquals("UNAVAILABLE", result.error?.code)
|
||||
assertEquals("NOTIFICATION_FAILED: boom", result.error?.message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,14 +63,11 @@ private class FakePoster(
|
||||
) : SystemNotificationPoster {
|
||||
var posts: Int = 0
|
||||
private set
|
||||
var lastRequest: SystemNotifyRequest? = null
|
||||
private set
|
||||
|
||||
override fun isAuthorized(): Boolean = authorized
|
||||
|
||||
override fun post(request: SystemNotifyRequest) {
|
||||
posts += 1
|
||||
lastRequest = request
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,18 +46,4 @@ class OpenClawCanvasA2UIActionTest {
|
||||
js,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun jsDispatchA2uiStatusQuotesControlCharacters() {
|
||||
val js =
|
||||
OpenClawCanvasA2UIAction.jsDispatchA2UIActionStatus(
|
||||
actionId = "a1\n\u2028\"",
|
||||
ok = false,
|
||||
error = "parse failed\n\t\u2029\\",
|
||||
)
|
||||
assertEquals(
|
||||
"window.dispatchEvent(new CustomEvent('openclaw:a2ui-action-status', { detail: { id: \"a1\\n\\u2028\\\"\", ok: false, error: \"parse failed\\n\\t\\u2029\\\\\" } }));",
|
||||
js,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,15 +86,13 @@ class OpenClawProtocolConstantsTest {
|
||||
assertEquals("motion.pedometer", OpenClawMotionCommand.Pedometer.rawValue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsCommandsUseStableStrings() {
|
||||
assertEquals("sms.send", OpenClawSmsCommand.Send.rawValue)
|
||||
assertEquals("sms.search", OpenClawSmsCommand.Search.rawValue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun callLogCommandsUseStableStrings() {
|
||||
assertEquals("callLog.search", OpenClawCallLogCommand.Search.rawValue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smsCommandsUseStableStrings() {
|
||||
assertEquals("sms.search", OpenClawSmsCommand.Search.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,86 +4,8 @@ import java.util.Base64
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class GatewayConfigResolverTest {
|
||||
@Test
|
||||
fun parseGatewayEndpointUsesDefaultTlsPortForBareWssUrls() {
|
||||
val parsed = parseGatewayEndpoint("wss://gateway.example")
|
||||
|
||||
assertEquals(
|
||||
GatewayEndpointConfig(
|
||||
host = "gateway.example",
|
||||
port = 443,
|
||||
tls = true,
|
||||
displayUrl = "https://gateway.example",
|
||||
),
|
||||
parsed,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseGatewayEndpointUsesDefaultCleartextPortForBareWsUrls() {
|
||||
val parsed = parseGatewayEndpoint("ws://gateway.example")
|
||||
|
||||
assertEquals(
|
||||
GatewayEndpointConfig(
|
||||
host = "gateway.example",
|
||||
port = 18789,
|
||||
tls = false,
|
||||
displayUrl = "http://gateway.example:18789",
|
||||
),
|
||||
parsed,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseGatewayEndpointOmitsExplicitDefaultTlsPortFromDisplayUrl() {
|
||||
val parsed = parseGatewayEndpoint("https://gateway.example:443")
|
||||
|
||||
assertEquals(
|
||||
GatewayEndpointConfig(
|
||||
host = "gateway.example",
|
||||
port = 443,
|
||||
tls = true,
|
||||
displayUrl = "https://gateway.example",
|
||||
),
|
||||
parsed,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseGatewayEndpointKeepsExplicitNonDefaultPortInDisplayUrl() {
|
||||
val parsed = parseGatewayEndpoint("http://gateway.example:8080")
|
||||
|
||||
assertEquals(
|
||||
GatewayEndpointConfig(
|
||||
host = "gateway.example",
|
||||
port = 8080,
|
||||
tls = false,
|
||||
displayUrl = "http://gateway.example:8080",
|
||||
),
|
||||
parsed,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseGatewayEndpointKeepsExplicitCleartextPort80InDisplayUrl() {
|
||||
val parsed = parseGatewayEndpoint("http://gateway.example:80")
|
||||
|
||||
assertEquals(
|
||||
GatewayEndpointConfig(
|
||||
host = "gateway.example",
|
||||
port = 80,
|
||||
tls = false,
|
||||
displayUrl = "http://gateway.example:80",
|
||||
),
|
||||
parsed,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveScannedSetupCodeAcceptsRawSetupCode() {
|
||||
val setupCode =
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package ai.openclaw.app.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SettingsSheetNotificationAppsTest {
|
||||
@Test
|
||||
fun resolveNotificationCandidatePackages_keepsConfiguredPackagesVisible() {
|
||||
val packages =
|
||||
resolveNotificationCandidatePackages(
|
||||
launcherPackages = setOf("com.example.launcher"),
|
||||
recentPackages = listOf("com.example.recent", "com.example.launcher"),
|
||||
configuredPackages = setOf("com.example.configured"),
|
||||
appPackageName = "ai.openclaw.app",
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
setOf("com.example.launcher", "com.example.recent", "com.example.configured"),
|
||||
packages,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolveNotificationCandidatePackages_filtersBlankAndSelfPackages() {
|
||||
val packages =
|
||||
resolveNotificationCandidatePackages(
|
||||
launcherPackages = setOf(" ", "ai.openclaw.app"),
|
||||
recentPackages = listOf("com.example.recent", " "),
|
||||
configuredPackages = setOf("ai.openclaw.app", "com.example.configured"),
|
||||
appPackageName = "ai.openclaw.app",
|
||||
)
|
||||
|
||||
assertEquals(setOf("com.example.recent", "com.example.configured"), packages)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
// Shared iOS version defaults.
|
||||
// Generated overrides live in build/Version.xcconfig (git-ignored).
|
||||
|
||||
OPENCLAW_GATEWAY_VERSION = 2026.3.30
|
||||
OPENCLAW_MARKETING_VERSION = 2026.3.30
|
||||
OPENCLAW_BUILD_VERSION = 2026033000
|
||||
OPENCLAW_GATEWAY_VERSION = 2026.3.14
|
||||
OPENCLAW_MARKETING_VERSION = 2026.3.14
|
||||
OPENCLAW_BUILD_VERSION = 202603140
|
||||
|
||||
#include? "../build/Version.xcconfig"
|
||||
|
||||
@@ -65,9 +65,9 @@ Release behavior:
|
||||
- Beta release also switches the app to `OpenClawPushTransport=relay`, `OpenClawPushDistribution=official`, and `OpenClawPushAPNsEnvironment=production`.
|
||||
- The beta flow does not modify `apps/ios/.local-signing.xcconfig` or `apps/ios/LocalSigning.xcconfig`.
|
||||
- Root `package.json.version` is the only version source for iOS.
|
||||
- A root version like `2026.3.30-beta.1` becomes:
|
||||
- `CFBundleShortVersionString = 2026.3.30`
|
||||
- `CFBundleVersion = next TestFlight build number for 2026.3.30`
|
||||
- A root version like `2026.3.13-beta.1` becomes:
|
||||
- `CFBundleShortVersionString = 2026.3.13`
|
||||
- `CFBundleVersion = next TestFlight build number for 2026.3.13`
|
||||
|
||||
Required env for beta builds:
|
||||
|
||||
|
||||
@@ -46,13 +46,6 @@ struct IOSGatewayChatTransport: OpenClawChatTransport, Sendable {
|
||||
_ = try await self.gateway.request(method: "sessions.reset", paramsJSON: json, timeoutSeconds: 10)
|
||||
}
|
||||
|
||||
func compactSession(sessionKey: String) async throws {
|
||||
struct Params: Codable { var key: String }
|
||||
let data = try JSONEncoder().encode(Params(key: sessionKey))
|
||||
let json = String(data: data, encoding: .utf8)
|
||||
_ = try await self.gateway.request(method: "sessions.compact", paramsJSON: json, timeoutSeconds: 10)
|
||||
}
|
||||
|
||||
func requestHistory(sessionKey: String) async throws -> OpenClawChatHistoryPayload {
|
||||
struct Params: Codable { var sessionKey: String }
|
||||
let data = try JSONEncoder().encode(Params(sessionKey: sessionKey))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
@preconcurrency import ActivityKit
|
||||
import ActivityKit
|
||||
import Foundation
|
||||
import os
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ def normalize_release_version(raw_value)
|
||||
version = raw_value.to_s.strip.sub(/\Av/, "")
|
||||
UI.user_error!("Missing root package.json version.") unless env_present?(version)
|
||||
unless version.match?(/\A\d+\.\d+\.\d+(?:[.-]?beta[.-]\d+)?\z/i)
|
||||
UI.user_error!("Invalid package.json version '#{raw_value}'. Expected YYYY.M.D or YYYY.M.D-beta.N.")
|
||||
UI.user_error!("Invalid package.json version '#{raw_value}'. Expected 2026.3.13 or 2026.3.13-beta.1.")
|
||||
end
|
||||
|
||||
version
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
"location" : "https://github.com/steipete/Peekaboo.git",
|
||||
"state" : {
|
||||
"branch" : "main",
|
||||
"revision" : "8659b70d386d02f831e277386b3216023ccc707e"
|
||||
"revision" : "bace59f90bb276f1c6fb613acfda3935ec4a7a90"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -96,8 +96,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/swiftlang/swift-subprocess.git",
|
||||
"state" : {
|
||||
"revision" : "13d087685b95d64d6aac9b94500d347bbe84c39b",
|
||||
"version" : "0.4.0"
|
||||
"revision" : "ba5888ad7758cbcbe7abebac37860b1652af2d9c",
|
||||
"version" : "0.3.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -16,9 +16,9 @@ let package = Package(
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/orchetect/MenuBarExtraAccess", exact: "1.2.2"),
|
||||
.package(url: "https://github.com/swiftlang/swift-subprocess.git", from: "0.4.0"),
|
||||
.package(url: "https://github.com/apple/swift-log.git", from: "1.10.1"),
|
||||
.package(url: "https://github.com/sparkle-project/Sparkle", from: "2.9.0"),
|
||||
.package(url: "https://github.com/swiftlang/swift-subprocess.git", from: "0.1.0"),
|
||||
.package(url: "https://github.com/apple/swift-log.git", from: "1.8.0"),
|
||||
.package(url: "https://github.com/sparkle-project/Sparkle", from: "2.8.1"),
|
||||
.package(url: "https://github.com/steipete/Peekaboo.git", branch: "main"),
|
||||
.package(path: "../shared/OpenClawKit"),
|
||||
.package(path: "../../Swabble"),
|
||||
|
||||
@@ -783,7 +783,7 @@ extension AppState {
|
||||
remoteToken: String,
|
||||
remoteTokenDirty: Bool) -> [String: Any]
|
||||
{
|
||||
self.updatedRemoteGatewayConfig(
|
||||
Self.updatedRemoteGatewayConfig(
|
||||
current: current,
|
||||
transport: transport,
|
||||
remoteUrl: remoteUrl,
|
||||
@@ -804,7 +804,7 @@ extension AppState {
|
||||
remoteToken: String,
|
||||
remoteTokenDirty: Bool) -> [String: Any]
|
||||
{
|
||||
self.syncedGatewayRoot(
|
||||
Self.syncedGatewayRoot(
|
||||
currentRoot: currentRoot,
|
||||
connectionMode: connectionMode,
|
||||
remoteTransport: remoteTransport,
|
||||
|
||||
@@ -8,8 +8,8 @@ final class CanvasA2UIActionMessageHandler: NSObject, WKScriptMessageHandler {
|
||||
static let messageName = "openclawCanvasA2UIAction"
|
||||
static let allMessageNames = [messageName]
|
||||
|
||||
/// Compatibility helper for debug/test shims. Runtime dispatch remains
|
||||
/// limited to in-app canvas schemes in `didReceive`.
|
||||
// Compatibility helper for debug/test shims. Runtime dispatch remains
|
||||
// limited to in-app canvas schemes in `didReceive`.
|
||||
static func isLocalNetworkCanvasURL(_ url: URL) -> Bool {
|
||||
guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else {
|
||||
return false
|
||||
|
||||
@@ -57,7 +57,8 @@ final class CanvasWindowController: NSWindowController, WKNavigationDelegate, NS
|
||||
let allowedSchemesJSON = (
|
||||
try? String(
|
||||
data: JSONSerialization.data(withJSONObject: CanvasScheme.allSchemes),
|
||||
encoding: .utf8)) ?? "[]"
|
||||
encoding: .utf8)
|
||||
) ?? "[]"
|
||||
let bridgeScript = """
|
||||
(() => {
|
||||
try {
|
||||
|
||||
@@ -73,7 +73,7 @@ extension ConfigSettings {
|
||||
|
||||
private var sidebar: some View {
|
||||
SettingsSidebarScroll {
|
||||
LazyVStack(alignment: .leading, spacing: 4) {
|
||||
LazyVStack(alignment: .leading, spacing: 8) {
|
||||
if self.sections.isEmpty {
|
||||
Text("No config sections available.")
|
||||
.font(.caption)
|
||||
@@ -82,7 +82,7 @@ extension ConfigSettings {
|
||||
.padding(.vertical, 4)
|
||||
} else {
|
||||
ForEach(self.sections) { section in
|
||||
self.sidebarSection(section)
|
||||
self.sidebarRow(section)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,7 @@ extension ConfigSettings {
|
||||
}
|
||||
self.actionRow
|
||||
self.sectionHeader(section)
|
||||
self.subsectionNav(section)
|
||||
self.sectionForm(section)
|
||||
if self.store.configDirty, !self.isNixMode {
|
||||
Text("Unsaved changes")
|
||||
@@ -181,76 +182,78 @@ extension ConfigSettings {
|
||||
.buttonStyle(.bordered)
|
||||
}
|
||||
|
||||
private func sidebarSection(_ section: ConfigSection) -> some View {
|
||||
let isExpanded = self.activeSectionKey == section.key
|
||||
let subsections = isExpanded ? self.resolveSubsections(for: section) : []
|
||||
|
||||
return VStack(alignment: .leading, spacing: 2) {
|
||||
Button {
|
||||
self.selectSection(section)
|
||||
} label: {
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "chevron.right")
|
||||
.font(.caption2.weight(.semibold))
|
||||
.foregroundStyle(.tertiary)
|
||||
.rotationEffect(.degrees(isExpanded ? 90 : 0))
|
||||
Text(section.label)
|
||||
.lineLimit(1)
|
||||
}
|
||||
.padding(.vertical, 5)
|
||||
.padding(.horizontal, 8)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(isExpanded && subsections.isEmpty
|
||||
? Color.accentColor.opacity(0.18)
|
||||
: Color.clear)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.contentShape(Rectangle())
|
||||
|
||||
if isExpanded, !subsections.isEmpty {
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
self.sidebarSubRow(title: "All", key: nil, sectionKey: section.key)
|
||||
ForEach(subsections) { sub in
|
||||
self.sidebarSubRow(title: sub.label, key: sub.key, sectionKey: section.key)
|
||||
}
|
||||
}
|
||||
.padding(.leading, 20)
|
||||
.transition(.opacity.combined(with: .move(edge: .top)))
|
||||
}
|
||||
}
|
||||
.animation(.easeInOut(duration: 0.18), value: isExpanded)
|
||||
}
|
||||
|
||||
private func sidebarSubRow(title: String, key: String?, sectionKey: String) -> some View {
|
||||
let isSelected: Bool = {
|
||||
guard self.activeSectionKey == sectionKey else { return false }
|
||||
if let key { return self.activeSubsection == .key(key) }
|
||||
return self.activeSubsection == .all
|
||||
}()
|
||||
|
||||
private func sidebarRow(_ section: ConfigSection) -> some View {
|
||||
let isSelected = self.activeSectionKey == section.key
|
||||
return Button {
|
||||
if let key {
|
||||
self.activeSubsection = .key(key)
|
||||
} else {
|
||||
self.activeSubsection = .all
|
||||
}
|
||||
self.selectSection(section)
|
||||
} label: {
|
||||
Text(title)
|
||||
.font(.callout)
|
||||
.lineLimit(1)
|
||||
.padding(.vertical, 4)
|
||||
.padding(.horizontal, 8)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(isSelected ? Color.accentColor.opacity(0.18) : Color.clear)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 7, style: .continuous))
|
||||
.contentShape(Rectangle())
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(section.label)
|
||||
if let help = section.help {
|
||||
Text(help)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(2)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 6)
|
||||
.padding(.horizontal, 8)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(isSelected ? Color.accentColor.opacity(0.18) : Color.clear)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
|
||||
.background(Color.clear)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.buttonStyle(.plain)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func subsectionNav(_ section: ConfigSection) -> some View {
|
||||
let subsections = self.resolveSubsections(for: section)
|
||||
if subsections.isEmpty {
|
||||
EmptyView()
|
||||
} else {
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
HStack(spacing: 8) {
|
||||
self.subsectionButton(
|
||||
title: "All",
|
||||
isSelected: self.activeSubsection == .all)
|
||||
{
|
||||
self.activeSubsection = .all
|
||||
}
|
||||
ForEach(subsections) { subsection in
|
||||
self.subsectionButton(
|
||||
title: subsection.label,
|
||||
isSelected: self.activeSubsection == .key(subsection.key))
|
||||
{
|
||||
self.activeSubsection = .key(subsection.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func subsectionButton(
|
||||
title: String,
|
||||
isSelected: Bool,
|
||||
action: @escaping () -> Void) -> some View
|
||||
{
|
||||
Button(action: action) {
|
||||
Text(title)
|
||||
.font(.callout.weight(.semibold))
|
||||
.foregroundStyle(isSelected ? Color.accentColor : .primary)
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 6)
|
||||
.background(isSelected ? Color.accentColor.opacity(0.18) : Color(nsColor: .controlBackgroundColor))
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
|
||||
private func sectionForm(_ section: ConfigSection) -> some View {
|
||||
let subsection = self.activeSubsection
|
||||
let defaultPath: ConfigPath = [.key(section.key)]
|
||||
|
||||
@@ -17,10 +17,10 @@ extension CronJobEditor {
|
||||
self.enabled = job.enabled
|
||||
self.deleteAfterRun = job.deleteAfterRun ?? false
|
||||
switch job.parsedSessionTarget {
|
||||
case let .predefined(target):
|
||||
case .predefined(let target):
|
||||
self.sessionTarget = target
|
||||
self.preservedSessionTargetRaw = nil
|
||||
case let .session(id):
|
||||
case .session(let id):
|
||||
self.sessionTarget = .isolated
|
||||
self.preservedSessionTargetRaw = "session:\(id)"
|
||||
}
|
||||
@@ -265,10 +265,7 @@ extension CronJobEditor {
|
||||
}
|
||||
|
||||
var effectiveSessionTargetRaw: String {
|
||||
if self.sessionTarget == .isolated,
|
||||
let preserved = self.preservedSessionTargetRaw?.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||
!preserved.isEmpty
|
||||
{
|
||||
if self.sessionTarget == .isolated, let preserved = self.preservedSessionTargetRaw?.trimmingCharacters(in: .whitespacesAndNewlines), !preserved.isEmpty {
|
||||
return preserved
|
||||
}
|
||||
return self.sessionTarget.rawValue
|
||||
|
||||
@@ -16,10 +16,10 @@ enum CronCustomSessionTarget: Codable, Equatable {
|
||||
|
||||
var rawValue: String {
|
||||
switch self {
|
||||
case let .predefined(target):
|
||||
target.rawValue
|
||||
case let .session(id):
|
||||
"session:\(id)"
|
||||
case .predefined(let target):
|
||||
return target.rawValue
|
||||
case .session(let id):
|
||||
return "session:\(id)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,10 +328,10 @@ struct CronJob: Identifiable, Codable, Equatable {
|
||||
/// predefined enum.
|
||||
var sessionTarget: CronSessionTarget {
|
||||
switch self.parsedSessionTarget {
|
||||
case let .predefined(target):
|
||||
target
|
||||
case .predefined(let target):
|
||||
return target
|
||||
case .session:
|
||||
.isolated
|
||||
return .isolated
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,20 +342,20 @@ struct CronJob: Identifiable, Codable, Equatable {
|
||||
var transcriptSessionKey: String? {
|
||||
switch self.parsedSessionTarget {
|
||||
case .predefined(.main):
|
||||
nil
|
||||
return nil
|
||||
case .predefined(.isolated), .predefined(.current):
|
||||
"cron:\(self.id)"
|
||||
case let .session(id):
|
||||
id
|
||||
return "cron:\(self.id)"
|
||||
case .session(let id):
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
var supportsAnnounceDelivery: Bool {
|
||||
switch self.parsedSessionTarget {
|
||||
case .predefined(.main):
|
||||
false
|
||||
return false
|
||||
case .predefined(.isolated), .predefined(.current), .session:
|
||||
true
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -768,8 +768,10 @@ struct DebugSettings: View {
|
||||
}
|
||||
|
||||
private func loadSessionStorePath() {
|
||||
let parsed = OpenClawConfigFile.loadDict()
|
||||
let url = self.configURL()
|
||||
guard
|
||||
let data = try? Data(contentsOf: url),
|
||||
let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let session = parsed["session"] as? [String: Any],
|
||||
let path = session["store"] as? String
|
||||
else {
|
||||
@@ -781,14 +783,28 @@ struct DebugSettings: View {
|
||||
|
||||
private func saveSessionStorePath() {
|
||||
let trimmed = self.sessionStorePath.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
var root = OpenClawConfigFile.loadDict()
|
||||
var root: [String: Any] = [:]
|
||||
let url = self.configURL()
|
||||
if let data = try? Data(contentsOf: url),
|
||||
let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
|
||||
{
|
||||
root = parsed
|
||||
}
|
||||
|
||||
var session = root["session"] as? [String: Any] ?? [:]
|
||||
session["store"] = trimmed.isEmpty ? SessionLoader.defaultStorePath : trimmed
|
||||
root["session"] = session
|
||||
|
||||
OpenClawConfigFile.saveDict(root)
|
||||
self.sessionStoreSaveError = nil
|
||||
do {
|
||||
let data = try JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys])
|
||||
try FileManager().createDirectory(
|
||||
at: url.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true)
|
||||
try data.write(to: url, options: [.atomic])
|
||||
self.sessionStoreSaveError = nil
|
||||
} catch {
|
||||
self.sessionStoreSaveError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private var bindingOverride: Binding<String> {
|
||||
@@ -812,6 +828,10 @@ struct DebugSettings: View {
|
||||
private var canRestartGateway: Bool {
|
||||
self.state.connectionMode == .local
|
||||
}
|
||||
|
||||
private func configURL() -> URL {
|
||||
OpenClawPaths.configURL
|
||||
}
|
||||
}
|
||||
|
||||
extension DebugSettings {
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
enum ExecApprovalCommandDisplaySanitizer {
|
||||
private static let invisibleCodePoints: Set<UInt32> = [
|
||||
0x115F,
|
||||
0x1160,
|
||||
0x3164,
|
||||
0xFFA0,
|
||||
]
|
||||
|
||||
static func sanitize(_ text: String) -> String {
|
||||
var sanitized = ""
|
||||
sanitized.reserveCapacity(text.count)
|
||||
for scalar in text.unicodeScalars {
|
||||
if self.shouldEscape(scalar) {
|
||||
sanitized.append(self.escape(scalar))
|
||||
} else {
|
||||
sanitized.append(String(scalar))
|
||||
}
|
||||
}
|
||||
return sanitized
|
||||
}
|
||||
|
||||
private static func shouldEscape(_ scalar: UnicodeScalar) -> Bool {
|
||||
scalar.properties.generalCategory == .format || self.invisibleCodePoints.contains(scalar.value)
|
||||
}
|
||||
|
||||
private static func escape(_ scalar: UnicodeScalar) -> String {
|
||||
"\\u{\(String(scalar.value, radix: 16, uppercase: true))}"
|
||||
}
|
||||
}
|
||||
@@ -89,11 +89,11 @@ final class ExecApprovalsGatewayPrompter {
|
||||
private static func shouldAsk(security: ExecSecurity, ask: ExecAsk) -> Bool {
|
||||
switch ask {
|
||||
case .always:
|
||||
true
|
||||
return true
|
||||
case .onMiss:
|
||||
security == .allowlist
|
||||
return security == .allowlist
|
||||
case .off:
|
||||
false
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,21 +113,21 @@ final class ExecApprovalsGatewayPrompter {
|
||||
let mode = AppStateStore.shared.connectionMode
|
||||
let activeSession = WebChatManager.shared.activeSessionKey?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let requestSession = request.request.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
|
||||
|
||||
// Read-only resolve to avoid disk writes on the MainActor
|
||||
let approvals = ExecApprovalsStore.resolveReadOnly(agentId: request.request.agentId)
|
||||
let security = approvals.agent.security
|
||||
let ask = approvals.agent.ask
|
||||
|
||||
|
||||
let shouldAsk = Self.shouldAsk(security: security, ask: ask)
|
||||
|
||||
|
||||
let canPresent = shouldAsk && Self.shouldPresent(
|
||||
mode: mode,
|
||||
activeSession: activeSession,
|
||||
requestSession: requestSession,
|
||||
lastInputSeconds: Self.lastInputSeconds(),
|
||||
thresholdSeconds: 120)
|
||||
|
||||
|
||||
return PresentationDecision(
|
||||
shouldAsk: shouldAsk,
|
||||
canPresent: canPresent,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user