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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

296 lines
9.1 KiB
TypeScript

// Clickclack tests cover gateway plugin behavior.
import { EventEmitter } from "node:events";
import type { ChannelGatewayContext } from "openclaw/plugin-sdk/channel-contract";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ResolvedClickClackAccount } from "./types.js";
class FakeSocket extends EventEmitter {
emitErrorOnClose = false;
close = vi.fn(() => {
if (this.emitErrorOnClose) {
this.emit("error", new Error("socket closed while connecting"));
}
this.emit("close");
});
}
const mocks = vi.hoisted(() => ({
client: {
me: vi.fn(),
events: vi.fn(),
websocket: vi.fn(),
channelMessages: vi.fn(),
directMessages: vi.fn(),
thread: vi.fn(),
},
handleClickClackInbound: vi.fn(),
resolveClickClackInboundAccess: vi.fn(),
resolveWorkspaceId: vi.fn(),
}));
vi.mock("./access.js", () => ({
resolveClickClackInboundAccess: mocks.resolveClickClackInboundAccess,
}));
vi.mock("./http-client.js", () => ({
createClickClackClient: vi.fn(() => mocks.client),
}));
vi.mock("./inbound.js", () => ({
handleClickClackInbound: mocks.handleClickClackInbound,
}));
vi.mock("./resolve.js", () => ({
resolveWorkspaceId: mocks.resolveWorkspaceId,
}));
import { startClickClackGatewayAccount } from "./gateway.js";
function createGatewayContext(
abortSignal: AbortSignal,
): ChannelGatewayContext<ResolvedClickClackAccount> {
const setStatus = vi.fn();
const log = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() };
return {
cfg: {
channels: {
clickclack: {
baseUrl: "https://clickclack.example",
token: "test-token",
workspace: "main",
reconnectMs: 1,
},
},
} as ChannelGatewayContext<ResolvedClickClackAccount>["cfg"],
accountId: "default",
account: {} as ResolvedClickClackAccount,
runtime: {} as ChannelGatewayContext<ResolvedClickClackAccount>["runtime"],
abortSignal,
log,
getStatus: () =>
({ accountId: "default" }) as ReturnType<
ChannelGatewayContext<ResolvedClickClackAccount>["getStatus"]
>,
setStatus,
};
}
describe("ClickClack gateway", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.client.me.mockResolvedValue({
id: "bot-user",
display_name: "Bot",
handle: "bot",
avatar_url: "",
created_at: "2026-01-01T00:00:00.000Z",
});
mocks.client.events.mockResolvedValue([]);
mocks.resolveClickClackInboundAccess.mockResolvedValue({
shouldDispatch: true,
commandAuthorized: true,
});
mocks.resolveWorkspaceId.mockResolvedValue("workspace-1");
mocks.client.channelMessages.mockResolvedValue([
{
id: "msg-1",
workspace_id: "workspace-1",
channel_id: "chan-1",
author_id: "human-1",
thread_root_id: "msg-1",
body: "hello",
body_format: "markdown",
created_at: "2026-01-01T00:00:00.000Z",
author: {
id: "human-1",
kind: "human",
display_name: "Human",
handle: "human",
avatar_url: "",
created_at: "2026-01-01T00:00:00.000Z",
},
},
]);
});
it("skips malformed websocket frames without stopping the monitor", async () => {
const socket = new FakeSocket();
mocks.client.websocket.mockReturnValue(socket);
const abort = new AbortController();
const ctx = createGatewayContext(abort.signal);
let runError: unknown;
const run = startClickClackGatewayAccount(ctx).catch((error: unknown) => {
runError = error;
});
await vi.waitFor(() => expect(mocks.client.websocket).toHaveBeenCalledTimes(1));
socket.emit("message", Buffer.from("{not json"));
await new Promise((resolve) => {
setImmediate(resolve);
});
expect(runError).toBeUndefined();
expect(ctx.log?.warn).toHaveBeenCalledWith(
"[default] skipped malformed ClickClack websocket event",
);
socket.emit(
"message",
Buffer.from(
JSON.stringify({
id: "evt-1",
cursor: "cursor-1",
type: "message.created",
workspace_id: "workspace-1",
channel_id: "chan-1",
seq: 2,
created_at: "2026-01-01T00:00:00.000Z",
payload: { message_id: "msg-1", author_id: "human-1" },
}),
),
);
await vi.waitFor(() => expect(mocks.handleClickClackInbound).toHaveBeenCalledTimes(1));
expect(mocks.handleClickClackInbound.mock.calls[0]?.[0].access).toEqual({
shouldDispatch: true,
commandAuthorized: true,
});
abort.abort();
await run;
expect(runError).toBeUndefined();
});
it("drops messages denied by ClickClack sender access before inbound handling", async () => {
const socket = new FakeSocket();
mocks.client.websocket.mockReturnValue(socket);
mocks.resolveClickClackInboundAccess.mockResolvedValue({
shouldDispatch: false,
commandAuthorized: false,
});
const abort = new AbortController();
const ctx = createGatewayContext(abort.signal);
const run = startClickClackGatewayAccount(ctx);
await vi.waitFor(() => expect(mocks.client.websocket).toHaveBeenCalledTimes(1));
socket.emit(
"message",
Buffer.from(
JSON.stringify({
id: "evt-1",
cursor: "cursor-1",
type: "message.created",
workspace_id: "workspace-1",
channel_id: "chan-1",
seq: 2,
created_at: "2026-01-01T00:00:00.000Z",
payload: { message_id: "msg-1", author_id: "human-1" },
}),
),
);
await vi.waitFor(() => expect(mocks.resolveClickClackInboundAccess).toHaveBeenCalledTimes(1));
expect(mocks.handleClickClackInbound).not.toHaveBeenCalled();
abort.abort();
await run;
});
it("reconnects after ClickClack websocket errors", async () => {
const firstSocket = new FakeSocket();
firstSocket.emitErrorOnClose = true;
const secondSocket = new FakeSocket();
mocks.client.websocket.mockReturnValueOnce(firstSocket).mockReturnValueOnce(secondSocket);
const abort = new AbortController();
const ctx = createGatewayContext(abort.signal);
const run = startClickClackGatewayAccount(ctx);
await vi.waitFor(() => expect(mocks.client.websocket).toHaveBeenCalledTimes(1));
firstSocket.emit("error", new Error("gateway dropped"));
await vi.waitFor(() => expect(mocks.client.websocket).toHaveBeenCalledTimes(2));
expect(ctx.log?.warn).toHaveBeenCalledWith(
"[default] ClickClack websocket error; reconnecting: gateway dropped",
);
abort.abort();
await run;
});
it("does not log reconnect warnings when abort closes a connecting websocket", async () => {
const socket = new FakeSocket();
socket.emitErrorOnClose = true;
mocks.client.websocket.mockReturnValue(socket);
const abort = new AbortController();
const ctx = createGatewayContext(abort.signal);
const run = startClickClackGatewayAccount(ctx);
await vi.waitFor(() => expect(mocks.client.websocket).toHaveBeenCalledTimes(1));
abort.abort();
await run;
expect(ctx.log?.warn).not.toHaveBeenCalledWith(
"[default] ClickClack websocket error; reconnecting: socket closed while connecting",
);
expect(mocks.client.websocket).toHaveBeenCalledTimes(1);
});
it("clears running status when backlog polling fails", async () => {
mocks.client.events.mockRejectedValue(new Error("clickclack unavailable"));
const abort = new AbortController();
const ctx = createGatewayContext(abort.signal);
await expect(startClickClackGatewayAccount(ctx)).rejects.toThrow("clickclack unavailable");
expect(ctx.setStatus).toHaveBeenCalledWith({
accountId: "default",
running: true,
configured: true,
enabled: true,
baseUrl: "https://clickclack.example",
});
expect(ctx.setStatus).toHaveBeenLastCalledWith({
accountId: "default",
running: false,
});
});
it("wraps non-Error ws message rejections with the original value in the message", async () => {
const socket = new FakeSocket();
mocks.client.websocket.mockReturnValue(socket);
const rejection = { code: "ECONNRESET", retryable: true };
mocks.resolveClickClackInboundAccess.mockRejectedValue(rejection);
const abort = new AbortController();
const ctx = createGatewayContext(abort.signal);
const run = startClickClackGatewayAccount(ctx);
await vi.waitFor(() => expect(mocks.client.websocket).toHaveBeenCalledTimes(1));
socket.emit(
"message",
Buffer.from(
JSON.stringify({
id: "evt-1",
cursor: "cursor-1",
type: "message.created",
workspace_id: "workspace-1",
channel_id: "chan-1",
seq: 2,
created_at: "2026-01-01T00:00:00.000Z",
payload: { message_id: "msg-1", author_id: "human-1" },
}),
),
);
await expect(run).rejects.toMatchObject({
message: 'ClickClack ws message failed: {"code":"ECONNRESET","retryable":true}',
cause: rejection,
});
expect(ctx.setStatus).toHaveBeenLastCalledWith({
accountId: "default",
running: false,
});
});
});