From 420073d25d92d951dc6438540c3c59e57746e6c7 Mon Sep 17 00:00:00 2001 From: himanshu Date: Tue, 12 May 2026 10:32:13 +0530 Subject: [PATCH 1/5] Auto-enable channels.helloagent on first plugin import `openclaw channels login --channel helloagent` previously failed with "Unsupported channel: helloagent" on a fresh install. OpenClaw's CLI resolver only knows third-party channels via either the bundled official catalog (we're not in it) or `cfg.channels.` (the "configured-channels" loader scope). Without a cfg entry the resolver short-circuits before the plugin code ever runs, so users had to manually run `openclaw config set channels.helloagent.enabled true` before their first login. Add `ensureHelloAgentChannelEnabled()` and call it as a top-level side effect from setup-entry.ts and index.ts. OpenClaw imports setup-entry during `applyPluginAutoEnable`, which runs before the channel resolver, so we get a chance to: 1. Persist `channels.helloagent.enabled = true` to disk via an atomic temp-file rename with a `.bak` backup. Idempotent; respects an existing `enabled: false` so a user opt-out is never overwritten. 2. Mutate the in-memory runtime config snapshot returned by `getRuntimeConfig()` so the current invocation sees the new entry immediately. Without this, the disk write would only take effect on the *next* invocation (openclaw caches cfg per-process and never re-reads from disk during a single command). Both steps are best-effort and wrapped in try/catch; failures degrade the UX (user has to re-run once) but never break the plugin import. The in-memory patch uses `createRequire` to dynamically load `openclaw/plugin-sdk/runtime-config-snapshot` so an older openclaw that doesn't expose this SDK surface still imports cleanly. Verified end-to-end on a clean slate: plugins uninstall helloagent # no cfg entry, no install record plugins install # installed; cfg still untouched channels login --channel helloagent # resolves; prompts for ha_* token config get channels.helloagent # { "enabled": true } now persisted Co-Authored-By: Claude Opus 4.7 (1M context) --- index.ts | 5 ++ setup-entry.ts | 7 ++ src/core/auto-enable-channel.ts | 138 ++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+) create mode 100644 src/core/auto-enable-channel.ts diff --git a/index.ts b/index.ts index c1c7c9c..0937665 100644 --- a/index.ts +++ b/index.ts @@ -15,8 +15,13 @@ import { defineChannelPluginEntry } from "openclaw/plugin-sdk/channel-core"; import * as accountCache from "./src/core/account-cache.js"; import { stopAccount } from "./src/channel/monitor.js"; import { helloAgentPlugin } from "./src/channel/plugin.js"; +import { ensureHelloAgentChannelEnabled } from "./src/core/auto-enable-channel.js"; import { haLogger } from "./src/core/ha-logger.js"; +// See setup-entry.ts: same side effect, mirrored here so that whichever +// entry openclaw imports first auto-enables the channel. +ensureHelloAgentChannelEnabled(); + const log = haLogger("plugin"); function wireAutoTeardownOnCredsRemoval(): void { diff --git a/setup-entry.ts b/setup-entry.ts index e549c48..9c08cfd 100644 --- a/setup-entry.ts +++ b/setup-entry.ts @@ -8,7 +8,14 @@ */ import { defineSetupPluginEntry } from "openclaw/plugin-sdk/channel-core"; +import { ensureHelloAgentChannelEnabled } from "./src/core/auto-enable-channel.js"; import { helloAgentPlugin } from "./src/channel/plugin.js"; +// Auto-enable the channel on first import so `openclaw channels login +// --channel helloagent` resolves immediately after `plugins install`, +// without forcing the user to run `openclaw config set +// channels.helloagent.enabled true` first. See auto-enable-channel.ts. +ensureHelloAgentChannelEnabled(); + export const plugin = helloAgentPlugin; export default defineSetupPluginEntry(helloAgentPlugin); diff --git a/src/core/auto-enable-channel.ts b/src/core/auto-enable-channel.ts new file mode 100644 index 0000000..209d30a --- /dev/null +++ b/src/core/auto-enable-channel.ts @@ -0,0 +1,138 @@ +/** + * Ensure `cfg.channels.helloagent` exists in the user's openclaw config so + * that `openclaw channels login --channel helloagent` resolves the channel + * via OpenClaw's "configured-channels" plugin loader scope. + * + * Background: OpenClaw's CLI channel resolver only auto-loads plugins whose + * channel id is either (a) in the bundled official catalog, (b) in a local + * external catalog file, or (c) referenced under `cfg.channels.` (the + * "configured-channels" scope). HelloAgent is third-party so it isn't in + * the bundled catalog; without (c) the resolver throws "Unsupported channel: + * helloagent" before our plugin code ever runs. + * + * This helper runs as an import-time side effect from `setup-entry.ts` and + * `index.ts`. OpenClaw imports `setup-entry` early in its plugin + * auto-enable scan, which gives us a chance to: + * + * 1. Persist `cfg.channels.helloagent.enabled = true` to disk so all + * subsequent invocations resolve cleanly. Idempotent and respects an + * existing `enabled: false` (user opt-out). + * 2. Mutate the in-memory runtime config snapshot used by the current + * invocation, so the very first `channels login` after `plugins + * install` succeeds without forcing the user to retry. + * + * Both steps are best-effort: any error is swallowed so import never throws. + */ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const CHANNEL_ID = "helloagent"; + +function resolveCfgPath(env: NodeJS.ProcessEnv = process.env): string { + const explicit = env.OPENCLAW_CONFIG_PATH?.trim(); + if (explicit) return explicit; + const stateDir = env.OPENCLAW_STATE_DIR?.trim() || path.join(os.homedir(), ".openclaw"); + return path.join(stateDir, "openclaw.json"); +} + +function isPlainObject(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} + +/** + * Returns true iff cfg already records an explicit decision for our channel + * (enabled or disabled). We never overwrite a user's explicit setting. + */ +function channelAlreadyDecided(cfg: Record): boolean { + const channels = isPlainObject(cfg.channels) ? cfg.channels : null; + if (!channels) return false; + const entry = channels[CHANNEL_ID]; + if (!isPlainObject(entry)) return false; + return Object.prototype.hasOwnProperty.call(entry, "enabled"); +} + +function patchCfgInPlace(cfg: Record): void { + const channels = isPlainObject(cfg.channels) ? { ...cfg.channels } : {}; + const existing = isPlainObject(channels[CHANNEL_ID]) ? channels[CHANNEL_ID] : {}; + channels[CHANNEL_ID] = { ...existing, enabled: true }; + cfg.channels = channels; +} + +function patchOnDiskCfg(): void { + const cfgPath = resolveCfgPath(); + let raw = ""; + try { + raw = fs.readFileSync(cfgPath, "utf-8"); + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "ENOENT") return; + } + let cfg: Record; + try { + cfg = raw.trim() ? (JSON.parse(raw) as Record) : {}; + } catch { + // Corrupt cfg: don't touch it. + return; + } + if (channelAlreadyDecided(cfg)) return; + patchCfgInPlace(cfg); + try { + fs.mkdirSync(path.dirname(cfgPath), { recursive: true }); + if (raw) { + try { + fs.writeFileSync(`${cfgPath}.bak`, raw); + } catch { + // Backup failure shouldn't block the patch. + } + } + const tmp = `${cfgPath}.tmp.${process.pid}.${Date.now()}`; + fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2) + "\n"); + fs.renameSync(tmp, cfgPath); + } catch { + // Disk write failure: in-memory patch (below) may still recover this run. + } +} + +/** + * Mutate the in-memory runtime config snapshot. Required because openclaw's + * channel-login flow reads the config once at the start of the command via + * `getRuntimeConfig()` and never re-reads from disk; without this, the disk + * patch above would only take effect on the *next* invocation. + * + * Uses dynamic `createRequire` so import failure (e.g. on an older openclaw + * that doesn't export this SDK surface) doesn't break the plugin. + */ +function patchInMemoryCfg(): void { + let getRuntimeConfig: (() => Record | null | undefined) | undefined; + try { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { createRequire } = require("node:module") as typeof import("node:module"); + const requireFromHere = createRequire(import.meta.url); + const mod = requireFromHere("openclaw/plugin-sdk/runtime-config-snapshot") as { + getRuntimeConfig?: () => Record | null | undefined; + }; + getRuntimeConfig = mod.getRuntimeConfig; + } catch { + return; + } + const cfg = getRuntimeConfig?.(); + if (!cfg || !isPlainObject(cfg)) return; + if (channelAlreadyDecided(cfg)) return; + patchCfgInPlace(cfg); +} + +let attempted = false; +export function ensureHelloAgentChannelEnabled(): void { + if (attempted) return; + attempted = true; + try { + patchOnDiskCfg(); + } catch { + // ignore + } + try { + patchInMemoryCfg(); + } catch { + // ignore + } +} From 4bceaf680a2b480d88fec741893e874dce192b43 Mon Sep 17 00:00:00 2001 From: himanshu Date: Tue, 12 May 2026 10:33:50 +0530 Subject: [PATCH 2/5] README: align install/login flow with auto-enable + add troubleshooting - Replace `npm install` (would install as a project dep, wrong for end users) with `openclaw plugins install`, the supported entry point. - Note that `channels.helloagent.enabled` is now set automatically on first import, so login no longer requires a prior `config set`. - Drop the now-defunct `config set` step from the run-from-source recipe. - Add a Troubleshooting section covering the most common failure modes: Unsupported channel, empty stdin, gateway not picking up creds, expired tokens, corp proxies, verbose logs. Co-Authored-By: Claude Opus 4.7 (1M context) --- README.md | 165 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 108 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 211625e..384dfa3 100644 --- a/README.md +++ b/README.md @@ -5,25 +5,29 @@ [![npm](https://img.shields.io/npm/v/@helloagentai/openclaw.svg)](https://www.npmjs.com/package/@helloagentai/openclaw) [![License](https://img.shields.io/npm/l/@helloagentai/openclaw.svg)](LICENSE) -Connects an OpenClaw assistant to the [HelloAgent](https://app.helloagent.cc) network. Peers DM your assistant over a long-lived relay WebSocket; inbound messages are dispatched as streams and replies are sent back chunk-by-chunk on the same connection. - -Built on [`@helloagentai/sdk`](https://www.npmjs.com/package/@helloagentai/sdk). +Connects an OpenClaw assistant to the [HelloAgent](https://app.helloagent.cc) network over a long-lived relay WebSocket. Built on [`@helloagentai/sdk`](https://www.npmjs.com/package/@helloagentai/sdk). ## Install ```bash -npm install @helloagentai/openclaw +openclaw plugins install @helloagentai/openclaw ``` -OpenClaw discovers the plugin automatically on the next gateway boot. +This installs the plugin into your OpenClaw install (`~/.openclaw/npm/node_modules/...`) and registers it with the gateway. The next CLI invocation auto-enables the `helloagent` channel in your `openclaw.json`, so you can go straight to the login step below. -## Pair an agent +## Log in ```bash openclaw channels login --channel helloagent ``` -The default flow prompts for an `ha_*` token — create one at [app.helloagent.cc/app/agents/new](https://app.helloagent.cc/app/agents/new) and paste it. To switch flows, set `HELLOAGENT_PAIR_MODE`: +The default flow prompts for an `ha_*` token — create one at [app.helloagent.cc/app/agents/new](https://app.helloagent.cc/app/agents/new) and paste it at the prompt. Credentials are written to `~/.openclaw/credentials/helloagent/`. + +If the gateway is already running, login fires a `channels.start` RPC and the channel comes up live. Otherwise it starts on the next `openclaw gateway run`. + +### Alternate pairing modes + +Set `HELLOAGENT_PAIR_MODE` to switch flows: | Mode | Use when… | |---|---| @@ -31,16 +35,14 @@ The default flow prompts for an `ha_*` token — create one at [app.helloagent.c | `oauth` | A browser is available — opens a loopback OAuth + PKCE flow | | `device` | Headless machine — prints a code to enter on another device | -A successful pair writes `channels.helloagent.enabled = true` to your `openclaw.json`, so the channel appears in `openclaw channels list` and starts automatically on the next gateway boot. - ## Usage ```bash -openclaw channels list # show channel + account status -openclaw channels logout --channel helloagent # remove credentials +openclaw channels list # show channel + account status +openclaw channels logout --channel helloagent # remove credentials ``` -DM policy is configured per-account through `openclaw config`: +DM policy is configured per-account: ```bash openclaw config set channels.helloagent.dmPolicy allowlist @@ -54,16 +56,102 @@ openclaw config set channels.helloagent.allowFrom.0 alice | `allow-all` | Any HelloAgent peer can DM (a warning is logged) | | `deny-all` | Inbound DMs are dropped | -## Uninstalling +## Multiple accounts + +Each named account has its own `creds.json` and cfg block: + +```json +{ + "channels": { + "helloagent": { + "accounts": { + "work": { "enabled": true, "dmPolicy": "allowlist", "allowFrom": ["alice"] }, + "personal": { "enabled": true, "dmPolicy": "allow-all" } + } + } + } +} +``` -`openclaw plugins uninstall helloagent` removes the cfg entry, install record, and load path — but it does **not** wipe credentials. Log out each account first so the live WebSocket session is torn down and the `creds.json` files are deleted: +Pair them with `--account`: + +```bash +openclaw channels login --channel helloagent --account work +``` + +## Troubleshooting + +### `Channel login failed: Error: Unsupported channel: helloagent` + +OpenClaw doesn't have `channels.helloagent` in your config yet. Recent versions of this plugin set that flag automatically on import, so this usually means you're on an older build. Fix it with one command: + +```bash +openclaw config set channels.helloagent.enabled true +openclaw channels login --channel helloagent +``` + +If the error persists, confirm the plugin is installed and enabled: + +```bash +openclaw plugins list | grep -i helloagent # should show "enabled" +openclaw plugins doctor # should report no issues +``` + +### `Channel login failed: Error: helloagent: no token received on stdin` + +You pressed Enter without typing the token, or stdin was piped from an empty source. Re-run interactively and paste your `ha_*` token at the prompt: + +```bash +openclaw channels login --channel helloagent +``` + +Or pipe the token directly: + +```bash +echo "$HA_TOKEN" | openclaw channels login --channel helloagent +``` + +### Login succeeds but messages don't arrive + +Check the channel status: + +```bash +openclaw channels status --channel helloagent --probe +``` + +If the account shows as not connected and you have a gateway already running, restart it so it picks up the new credentials: + +```bash +openclaw gateway restart +``` + +Then verify with `openclaw channels logs --channel helloagent` that the WebSocket reaches `connected`. + +### Token rejected or expired + +Tokens are one-shot — once paired, the original `ha_*` value is consumed. Generate a new one at [app.helloagent.cc/app/agents/new](https://app.helloagent.cc/app/agents/new) and re-run the login. + +### Behind a corporate proxy + +Set `HTTPS_PROXY` and `HTTP_PROXY` in the environment that runs the gateway (not just the CLI) — the relay WebSocket runs inside the gateway process. + +### Verbose logs + +```bash +HELLOAGENT_DEBUG=1 openclaw channels login --channel helloagent +HELLOAGENT_DEBUG=1 openclaw gateway run +``` + +## Uninstall + +`openclaw plugins uninstall helloagent` removes the cfg entry, install record, and load path — but it does **not** wipe credentials. Log out each account first so the live WebSocket is torn down and `creds.json` is deleted: ```bash openclaw channels logout --channel helloagent # repeat per --account if you have several openclaw plugins uninstall helloagent ``` -Or, if you've already uninstalled and want to scrub leftover tokens: +If you've already uninstalled and want to scrub leftover tokens: ```bash rm -rf ~/.openclaw/credentials/helloagent @@ -81,29 +169,6 @@ rm -rf ~/.openclaw/credentials/helloagent | Reactions, typing, edit, delete | no | | Threads / groups | no | -## Multiple accounts - -Each named account has its own `creds.json` and cfg block: - -```json -{ - "channels": { - "helloagent": { - "accounts": { - "work": { "enabled": true, "dmPolicy": "allowlist", "allowFrom": ["alice"] }, - "personal": { "enabled": true, "dmPolicy": "allow-all" } - } - } - } -} -``` - -Pair them with `--account`: - -```bash -openclaw channels login --channel helloagent --account work -``` - ## Environment variables | Variable | Default | Purpose | @@ -127,31 +192,17 @@ npm run build npm run test:smoke ``` -### Running from source - -To make your local OpenClaw CLI load this repo instead of a published version: +To run this checkout against your local OpenClaw CLI: ```bash -# 1. Build npm run build - -# 2. Remove any prior install of the same plugin id (safe; --keep-files leaves source alone) -openclaw plugins uninstall helloagent --force --keep-files - -# 3. Link this directory as the plugin source +openclaw plugins uninstall helloagent --force --keep-files # safe if not installed openclaw plugins install . --link - -# 4. Restart the gateway so it picks up the new plugin -openclaw gateway restart - -# 5. Enable the channel (a fresh install starts disabled) -openclaw config set channels.helloagent.enabled true - -# 6. Pair -openclaw channels login --channel helloagent +openclaw gateway restart # if the gateway is running +openclaw channels login --channel helloagent # cfg auto-enables on import ``` -After editing source, rebuild and either restart the gateway or clear OpenClaw's compile cache: +After editing source, rebuild and clear OpenClaw's compile cache so the next gateway run picks up the change: ```bash npm run build From d298444237d3c4e0e7e411cd1544f189c9f9cab9 Mon Sep 17 00:00:00 2001 From: himanshu Date: Tue, 12 May 2026 10:40:17 +0530 Subject: [PATCH 3/5] README: collapse to a single get-started block, drop alternate flows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace separate Install / Log in / Alternate-modes sections with one Get-started block: install → restart gateway (if running) → login. Single copy-pasteable recipe. - Drop the oauth / device pairing-mode docs — the import-token flow covers every supported environment, and the alternates have been a source of "which one do I run?" confusion. The env vars and code paths still exist for power users; they're just no longer surfaced. - Trim the env-var table to the variables that actually affect the documented import flow. Co-Authored-By: Claude Opus 4.7 (1M context) --- README.md | 35 ++++++++++------------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 384dfa3..d8658ff 100644 --- a/README.md +++ b/README.md @@ -7,33 +7,21 @@ Connects an OpenClaw assistant to the [HelloAgent](https://app.helloagent.cc) network over a long-lived relay WebSocket. Built on [`@helloagentai/sdk`](https://www.npmjs.com/package/@helloagentai/sdk). -## Install +## Get started -```bash -openclaw plugins install @helloagentai/openclaw -``` - -This installs the plugin into your OpenClaw install (`~/.openclaw/npm/node_modules/...`) and registers it with the gateway. The next CLI invocation auto-enables the `helloagent` channel in your `openclaw.json`, so you can go straight to the login step below. - -## Log in +1. Create an agent at [app.helloagent.cc/app/agents/new](https://app.helloagent.cc/app/agents/new) and copy the `ha_*` token it shows. +2. Run: ```bash +openclaw plugins install @helloagentai/openclaw +openclaw gateway restart openclaw channels login --channel helloagent +# paste the ha_* token at the prompt ``` -The default flow prompts for an `ha_*` token — create one at [app.helloagent.cc/app/agents/new](https://app.helloagent.cc/app/agents/new) and paste it at the prompt. Credentials are written to `~/.openclaw/credentials/helloagent/`. - -If the gateway is already running, login fires a `channels.start` RPC and the channel comes up live. Otherwise it starts on the next `openclaw gateway run`. - -### Alternate pairing modes +That's it. The plugin auto-enables `channels.helloagent` in your `openclaw.json` on first import, so login works without any prior `config set`. Credentials are written to `~/.openclaw/credentials/helloagent/`, and the running gateway picks the channel up immediately. -Set `HELLOAGENT_PAIR_MODE` to switch flows: - -| Mode | Use when… | -|---|---| -| `import` (default) | You can paste an `ha_*` token | -| `oauth` | A browser is available — opens a loopback OAuth + PKCE flow | -| `device` | Headless machine — prints a code to enter on another device | +> If you don't have a gateway running yet, skip `openclaw gateway restart` — the channel will come up on your next `openclaw gateway run`. ## Usage @@ -173,12 +161,9 @@ rm -rf ~/.openclaw/credentials/helloagent | Variable | Default | Purpose | |---|---|---| -| `HELLOAGENT_API_URL` | `https://api.helloagent.cc` | REST base for OAuth + channel link | +| `HELLOAGENT_API_URL` | `https://api.helloagent.cc` | REST base used during token import | | `HELLOAGENT_WEB_URL` | `https://app.helloagent.cc` | Web app URL (token-issue page) | -| `HELLOAGENT_RELAY_WS_URL` | `wss://api.helloagent.cc/v1/ws` | Relay WebSocket | -| `HELLOAGENT_AGENT_NAME` | `jarvis` | Agent suffix used during pair | -| `HELLOAGENT_PAIR_MODE` | `import` | `import` / `oauth` / `device` | -| `HELLOAGENT_OAUTH_CLIENT_ID` | `openclaw` | OAuth client id (PKCE flow) | +| `HELLOAGENT_RELAY_WS_URL` | `wss://api.helloagent.cc/v1/ws` | Relay WebSocket the gateway connects to | | `HELLOAGENT_DEBUG` | `0` | Set to `1` for verbose plugin logs | ## Development From ce1085f73dc95f27ec30e0b379d0146b07449f9e Mon Sep 17 00:00:00 2001 From: himanshu Date: Tue, 12 May 2026 10:43:48 +0530 Subject: [PATCH 4/5] README: drop Usage and Multiple accounts sections; add gateway restart to manual recovery - Remove the Usage block (channels list/logout, dmPolicy table) and the Multiple accounts block. The Get-started recipe is enough; the rest belonged in dedicated docs, not the front-page README. - In the "Unsupported channel" troubleshooting step, add the `openclaw gateway restart` line between the cfg flag write and the retry login. Same reasoning as the Get-started block: a running gateway needs to reload its plugin registry to pick up the new channel. Co-Authored-By: Claude Opus 4.7 (1M context) --- README.md | 47 ++--------------------------------------------- 1 file changed, 2 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index d8658ff..583a916 100644 --- a/README.md +++ b/README.md @@ -23,58 +23,15 @@ That's it. The plugin auto-enables `channels.helloagent` in your `openclaw.json` > If you don't have a gateway running yet, skip `openclaw gateway restart` — the channel will come up on your next `openclaw gateway run`. -## Usage - -```bash -openclaw channels list # show channel + account status -openclaw channels logout --channel helloagent # remove credentials -``` - -DM policy is configured per-account: - -```bash -openclaw config set channels.helloagent.dmPolicy allowlist -openclaw config set channels.helloagent.allowFrom.0 alice -``` - -| `dmPolicy` | Behavior | -|---|---| -| `allowlist` (default) | Only handles in `allowFrom` can DM the agent | -| `pairing` | New peers must approve a pairing code first | -| `allow-all` | Any HelloAgent peer can DM (a warning is logged) | -| `deny-all` | Inbound DMs are dropped | - -## Multiple accounts - -Each named account has its own `creds.json` and cfg block: - -```json -{ - "channels": { - "helloagent": { - "accounts": { - "work": { "enabled": true, "dmPolicy": "allowlist", "allowFrom": ["alice"] }, - "personal": { "enabled": true, "dmPolicy": "allow-all" } - } - } - } -} -``` - -Pair them with `--account`: - -```bash -openclaw channels login --channel helloagent --account work -``` - ## Troubleshooting ### `Channel login failed: Error: Unsupported channel: helloagent` -OpenClaw doesn't have `channels.helloagent` in your config yet. Recent versions of this plugin set that flag automatically on import, so this usually means you're on an older build. Fix it with one command: +OpenClaw doesn't have `channels.helloagent` in your config yet. Recent versions of this plugin set that flag automatically on import, so this usually means you're on an older build. Fix it manually: ```bash openclaw config set channels.helloagent.enabled true +openclaw gateway restart # only if a gateway is running openclaw channels login --channel helloagent ``` From 5ccfea4d13d5b484973a9093dba2d15b74be715b Mon Sep 17 00:00:00 2001 From: himanshu Date: Tue, 12 May 2026 11:26:04 +0530 Subject: [PATCH 5/5] Add smoke tests for auto-enable-channel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Covers the helper that this PR introduces: - channelAlreadyDecided across six cfg shapes (empty, partial, primitive, enabled:true, enabled:false, non-object entry). - patchCfgInPlace preserves sibling channels and existing helloagent keys (dmPolicy, allowFrom) when merging in enabled:true. - End-to-end ensureHelloAgentChannelEnabled disk behavior: - Missing cfg → fresh write, no .bak. - Existing cfg → patch in + .bak rotation. - User opt-out (enabled:false) preserved byte-for-byte. - Already enabled → no-op (no rewrite, no .bak). - Corrupt cfg → leave it alone. - Idempotent per process (attempted guard). - Post-reset re-evaluates and patches without losing existing keys. Exposes a narrow __testing namespace from auto-enable-channel.ts for the helpers and an attempted-flag reset; not part of the public API. Co-Authored-By: Claude Opus 4.7 --- src/core/auto-enable-channel.ts | 15 +++ tests/smoke.ts | 184 ++++++++++++++++++++++++++++++++ 2 files changed, 199 insertions(+) diff --git a/src/core/auto-enable-channel.ts b/src/core/auto-enable-channel.ts index 209d30a..265c86b 100644 --- a/src/core/auto-enable-channel.ts +++ b/src/core/auto-enable-channel.ts @@ -136,3 +136,18 @@ export function ensureHelloAgentChannelEnabled(): void { // ignore } } + +/** + * Internals exposed for the smoke test (tests/smoke.ts). Not part of the + * public API — do not import from outside this package. + * + * @internal + */ +export const __testing = { + channelAlreadyDecided, + patchCfgInPlace, + resolveCfgPath, + resetAttempted(): void { + attempted = false; + }, +}; diff --git a/tests/smoke.ts b/tests/smoke.ts index 6b0a373..75e2ab8 100644 --- a/tests/smoke.ts +++ b/tests/smoke.ts @@ -31,6 +31,10 @@ import { writeCreds, type HelloAgentCreds, } from "../src/core/auth-store.js"; +import { + __testing as autoEnableInternals, + ensureHelloAgentChannelEnabled, +} from "../src/core/auto-enable-channel.js"; import { mergeHelloAgentAccountConfig, readCfg, @@ -479,6 +483,185 @@ async function testCfgStore(tmpDir: string): Promise { ok("writeCfg creates .bak rotation on overwrite"); } +// --------------------------------------------------------------------------- +// 8. auto-enable-channel — pure helpers + disk side effect +// --------------------------------------------------------------------------- + +async function testAutoEnableChannel(tmp: string): Promise { + const fs = await import("node:fs/promises"); + + // 1) channelAlreadyDecided — pure, six shapes. + const decided = autoEnableInternals.channelAlreadyDecided; + assertEq(decided({}), false, "empty cfg → not decided"); + assertEq(decided({ channels: {} }), false, "channels {} → not decided"); + assertEq(decided({ channels: { helloagent: {} } }), false, "helloagent {} → not decided"); + assertEq( + decided({ channels: { helloagent: { dmPolicy: "allowlist" } } }), + false, + "policy only, no enabled key → not decided", + ); + assertEq( + decided({ channels: { helloagent: { enabled: true } } }), + true, + "enabled: true → decided", + ); + assertEq( + decided({ channels: { helloagent: { enabled: false } } }), + true, + "enabled: false (opt-out) → decided", + ); + assertEq( + decided({ channels: { helloagent: [] as unknown as Record } }), + false, + "non-object entry → not decided", + ); + ok("channelAlreadyDecided covers all six cfg shapes"); + + // 2) patchCfgInPlace — pure, mutates cfg. + const a: Record = {}; + autoEnableInternals.patchCfgInPlace(a); + assertEq( + (a.channels as { helloagent: { enabled: boolean } }).helloagent.enabled, + true, + "patch into empty cfg", + ); + + const b: Record = { + channels: { + telegram: { enabled: true }, + helloagent: { dmPolicy: "allowlist", allowFrom: ["alice"] }, + }, + }; + autoEnableInternals.patchCfgInPlace(b); + const bH = (b.channels as { helloagent: Record }).helloagent; + assertEq(bH.enabled, true, "patch adds enabled"); + assertEq(bH.dmPolicy, "allowlist", "patch preserves dmPolicy"); + assert( + Array.isArray(bH.allowFrom) && (bH.allowFrom as string[])[0] === "alice", + "patch preserves allowFrom", + ); + const bTele = (b.channels as { telegram: { enabled: boolean } }).telegram; + assertEq(bTele.enabled, true, "patch preserves other channels"); + ok("patchCfgInPlace merges without clobbering siblings"); + + // 3) ensureHelloAgentChannelEnabled — end-to-end disk behavior. + + // 3a) Missing cfg → creates one with enabled=true. + const cfg3a = path.join(tmp, "auto-enable-3a", "openclaw.json"); + process.env.OPENCLAW_CONFIG_PATH = cfg3a; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + const after3a = JSON.parse(await fs.readFile(cfg3a, "utf-8")) as { + channels: { helloagent: { enabled: boolean } }; + }; + assertEq(after3a.channels.helloagent.enabled, true, "missing cfg → created with enabled=true"); + const bak3a = await fs + .access(`${cfg3a}.bak`) + .then(() => true) + .catch(() => false); + assertEq(bak3a, false, "no .bak when cfg was fresh-created"); + ok("missing cfg → fresh write, no .bak"); + + // 3b) Existing cfg without helloagent → patched in, .bak rolled. + const cfg3b = path.join(tmp, "auto-enable-3b", "openclaw.json"); + await fs.mkdir(path.dirname(cfg3b), { recursive: true }); + await fs.writeFile( + cfg3b, + JSON.stringify({ channels: { telegram: { enabled: true } } }, null, 2), + ); + process.env.OPENCLAW_CONFIG_PATH = cfg3b; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + const after3b = JSON.parse(await fs.readFile(cfg3b, "utf-8")) as { + channels: { helloagent: { enabled: boolean }; telegram: { enabled: boolean } }; + }; + assertEq(after3b.channels.helloagent.enabled, true, "patched helloagent enabled"); + assertEq(after3b.channels.telegram.enabled, true, "preserved telegram"); + const bak3b = await fs + .access(`${cfg3b}.bak`) + .then(() => true) + .catch(() => false); + assertEq(bak3b, true, ".bak rotated on overwrite"); + ok("existing cfg → patch + .bak rotation"); + + // 3c) User opt-out (enabled: false) is preserved. + const cfg3c = path.join(tmp, "auto-enable-3c", "openclaw.json"); + await fs.mkdir(path.dirname(cfg3c), { recursive: true }); + const optOutPayload = JSON.stringify( + { channels: { helloagent: { enabled: false, dmPolicy: "deny-all" } } }, + null, + 2, + ); + await fs.writeFile(cfg3c, optOutPayload); + process.env.OPENCLAW_CONFIG_PATH = cfg3c; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + assertEq( + await fs.readFile(cfg3c, "utf-8"), + optOutPayload, + "opt-out cfg byte-for-byte unchanged", + ); + ok("enabled:false opt-out is preserved verbatim"); + + // 3d) Already enabled → no-op (no .bak written). + const cfg3d = path.join(tmp, "auto-enable-3d", "openclaw.json"); + await fs.mkdir(path.dirname(cfg3d), { recursive: true }); + const alreadyEnabledPayload = JSON.stringify( + { channels: { helloagent: { enabled: true } } }, + null, + 2, + ); + await fs.writeFile(cfg3d, alreadyEnabledPayload); + process.env.OPENCLAW_CONFIG_PATH = cfg3d; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + assertEq( + await fs.readFile(cfg3d, "utf-8"), + alreadyEnabledPayload, + "enabled:true cfg unchanged", + ); + const bak3d = await fs + .access(`${cfg3d}.bak`) + .then(() => true) + .catch(() => false); + assertEq(bak3d, false, "no .bak created when no patch needed"); + ok("enabled:true is a no-op (no rewrite, no .bak)"); + + // 3e) Corrupt cfg → leave it alone. + const cfg3e = path.join(tmp, "auto-enable-3e", "openclaw.json"); + await fs.mkdir(path.dirname(cfg3e), { recursive: true }); + const garbage = "{ not valid json"; + await fs.writeFile(cfg3e, garbage); + process.env.OPENCLAW_CONFIG_PATH = cfg3e; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + assertEq(await fs.readFile(cfg3e, "utf-8"), garbage, "corrupt cfg untouched"); + ok("corrupt cfg → don't overwrite"); + + // 3f) Idempotency within a single process: the `attempted` guard short-circuits. + const cfg3f = path.join(tmp, "auto-enable-3f", "openclaw.json"); + process.env.OPENCLAW_CONFIG_PATH = cfg3f; + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + // Tamper with the file after the first call; a second call should NOT rewrite. + await fs.writeFile(cfg3f, JSON.stringify({ tampered: true }, null, 2)); + ensureHelloAgentChannelEnabled(); + const after3f = JSON.parse(await fs.readFile(cfg3f, "utf-8")) as { tampered?: boolean }; + assertEq(after3f.tampered, true, "second call did not rewrite (attempted guard)"); + ok("ensureHelloAgentChannelEnabled is idempotent per process"); + + // 3g) Subsequent process (after reset) re-evaluates from disk. + autoEnableInternals.resetAttempted(); + ensureHelloAgentChannelEnabled(); + const after3g = JSON.parse(await fs.readFile(cfg3f, "utf-8")) as { + channels?: { helloagent?: { enabled?: boolean } }; + tampered?: boolean; + }; + assertEq(after3g.channels?.helloagent?.enabled, true, "post-reset re-patch applied"); + assertEq(after3g.tampered, true, "post-reset re-patch preserved tampered key"); + ok("post-reset re-evaluates and patches without losing existing keys"); +} + // --------------------------------------------------------------------------- // Main // --------------------------------------------------------------------------- @@ -498,6 +681,7 @@ async function main(): Promise { await step("5. security.collectWarnings", testSecurityWarnings); await step("6. Disk creds → cache → plugin.config", () => testDiskCredsWiring(tmp)); await step("7. cfg-store atomic I/O", () => testCfgStore(tmp)); + await step("8. auto-enable-channel", () => testAutoEnableChannel(tmp)); } finally { if (originalState === undefined) delete process.env.OPENCLAW_STATE_DIR; else process.env.OPENCLAW_STATE_DIR = originalState;