Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11), free to diverge. Tree copied sans upstream .git; upstream remote added for future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19. Preserves docs/ARCHITECTURE.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
375 lines
12 KiB
TypeScript
375 lines
12 KiB
TypeScript
// Slack helper module supports monitor helpers behavior.
|
|
import type { ChannelRuntimeSurface } from "openclaw/plugin-sdk/channel-contract";
|
|
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
|
|
import { vi } from "vitest";
|
|
import type { Mock } from "vitest";
|
|
import { clearSlackInboundDeliveryStateForTest } from "./monitor/inbound-delivery-state.js";
|
|
|
|
type SlackHandler = (args: unknown) => Promise<void>;
|
|
type SlackMiddleware = (args: { next: () => Promise<void> } & Record<string, unknown>) => unknown;
|
|
type SlackProviderMonitor = (params: {
|
|
botToken: string;
|
|
appToken: string;
|
|
abortSignal: AbortSignal;
|
|
config?: Record<string, unknown>;
|
|
channelRuntime?: ChannelRuntimeSurface;
|
|
runtime?: RuntimeEnv;
|
|
}) => Promise<unknown>;
|
|
|
|
type SlackTestState = {
|
|
config: Record<string, unknown>;
|
|
appStartMock: Mock<(...args: unknown[]) => Promise<unknown>>;
|
|
appStopMock: Mock<(...args: unknown[]) => Promise<unknown>>;
|
|
sendMock: Mock<(...args: unknown[]) => Promise<unknown>>;
|
|
replyMock: Mock<(...args: unknown[]) => unknown>;
|
|
updateLastRouteMock: Mock<(...args: unknown[]) => unknown>;
|
|
reactMock: Mock<(...args: unknown[]) => unknown>;
|
|
reactionAddMock: Mock<(...args: unknown[]) => unknown>;
|
|
reactionRemoveMock: Mock<(...args: unknown[]) => unknown>;
|
|
readAllowFromStoreMock: Mock<(...args: unknown[]) => Promise<unknown>>;
|
|
upsertPairingRequestMock: Mock<(...args: unknown[]) => Promise<unknown>>;
|
|
resolveSlackUserAllowlistMock: Mock<
|
|
(params: { entries: string[] }) => Promise<Array<{ input: string; resolved: boolean }>>
|
|
>;
|
|
};
|
|
|
|
const slackTestState: SlackTestState = vi.hoisted(() => ({
|
|
config: {} as Record<string, unknown>,
|
|
appStartMock: vi.fn(),
|
|
appStopMock: vi.fn(),
|
|
sendMock: vi.fn(),
|
|
replyMock: vi.fn(),
|
|
updateLastRouteMock: vi.fn(),
|
|
reactMock: vi.fn(),
|
|
reactionAddMock: vi.fn(),
|
|
reactionRemoveMock: vi.fn(),
|
|
readAllowFromStoreMock: vi.fn(),
|
|
upsertPairingRequestMock: vi.fn(),
|
|
resolveSlackUserAllowlistMock: vi.fn(),
|
|
}));
|
|
|
|
export const getSlackTestState = (): SlackTestState => slackTestState;
|
|
|
|
type SlackClient = {
|
|
auth: { test: Mock<(...args: unknown[]) => Promise<Record<string, unknown>>> };
|
|
conversations: {
|
|
info: Mock<(...args: unknown[]) => Promise<Record<string, unknown>>>;
|
|
replies: Mock<(...args: unknown[]) => Promise<Record<string, unknown>>>;
|
|
history: Mock<(...args: unknown[]) => Promise<Record<string, unknown>>>;
|
|
};
|
|
users: {
|
|
info: Mock<(...args: unknown[]) => Promise<{ user: { profile: { display_name: string } } }>>;
|
|
};
|
|
assistant: {
|
|
threads: {
|
|
setStatus: Mock<(...args: unknown[]) => Promise<{ ok: boolean }>>;
|
|
};
|
|
};
|
|
reactions: {
|
|
add: (...args: unknown[]) => unknown;
|
|
remove: (...args: unknown[]) => unknown;
|
|
};
|
|
};
|
|
|
|
export const getSlackHandlers = () => ensureSlackTestRuntime().handlers;
|
|
|
|
export const getSlackClient = () => ensureSlackTestRuntime().client;
|
|
|
|
function ensureSlackTestRuntime(): {
|
|
handlers: Map<string, SlackHandler>;
|
|
client: SlackClient;
|
|
} {
|
|
const globalState = globalThis as {
|
|
__slackHandlers?: Map<string, SlackHandler>;
|
|
__slackClient?: SlackClient;
|
|
};
|
|
if (!globalState["__slackHandlers"]) {
|
|
globalState["__slackHandlers"] = new Map<string, SlackHandler>();
|
|
}
|
|
if (!globalState["__slackClient"]) {
|
|
globalState["__slackClient"] = {
|
|
auth: { test: vi.fn().mockResolvedValue({ user_id: "bot-user", bot_id: "bot-id" }) },
|
|
conversations: {
|
|
info: vi.fn().mockResolvedValue({
|
|
channel: { name: "dm", is_im: true },
|
|
}),
|
|
replies: vi.fn().mockResolvedValue({ messages: [] }),
|
|
history: vi.fn().mockResolvedValue({ messages: [] }),
|
|
},
|
|
users: {
|
|
info: vi.fn().mockResolvedValue({
|
|
user: { profile: { display_name: "Ada" } },
|
|
}),
|
|
},
|
|
assistant: {
|
|
threads: {
|
|
setStatus: vi.fn().mockResolvedValue({ ok: true }),
|
|
},
|
|
},
|
|
reactions: {
|
|
add: (...args: unknown[]) => {
|
|
slackTestState.reactionAddMock(...args);
|
|
return slackTestState.reactMock(...args);
|
|
},
|
|
remove: (...args: unknown[]) => {
|
|
slackTestState.reactionRemoveMock(...args);
|
|
return slackTestState.reactMock(...args);
|
|
},
|
|
},
|
|
};
|
|
}
|
|
return {
|
|
handlers: globalState["__slackHandlers"],
|
|
client: globalState["__slackClient"],
|
|
};
|
|
}
|
|
|
|
export const flush = () =>
|
|
new Promise((resolve) => {
|
|
setTimeout(resolve, 0);
|
|
});
|
|
|
|
async function waitForSlackEvent(name: string) {
|
|
for (let i = 0; i < 10; i += 1) {
|
|
if (getSlackHandlers()?.has(name)) {
|
|
return;
|
|
}
|
|
await flush();
|
|
}
|
|
}
|
|
|
|
export function startSlackMonitor(
|
|
monitorSlackProvider: SlackProviderMonitor,
|
|
opts?: {
|
|
botToken?: string;
|
|
appToken?: string;
|
|
channelRuntime?: ChannelRuntimeSurface;
|
|
runtime?: RuntimeEnv;
|
|
},
|
|
) {
|
|
const controller = new AbortController();
|
|
const run = monitorSlackProvider({
|
|
botToken: opts?.botToken ?? "bot-token",
|
|
appToken: opts?.appToken ?? "app-token",
|
|
abortSignal: controller.signal,
|
|
config: slackTestState.config,
|
|
channelRuntime: opts?.channelRuntime,
|
|
runtime: opts?.runtime,
|
|
});
|
|
return { controller, run };
|
|
}
|
|
|
|
export async function getSlackHandlerOrThrow(name: string) {
|
|
await waitForSlackEvent(name);
|
|
const handler = getSlackHandlers()?.get(name);
|
|
if (!handler) {
|
|
throw new Error(`Slack ${name} handler not registered`);
|
|
}
|
|
return handler;
|
|
}
|
|
|
|
export async function stopSlackMonitor(params: {
|
|
controller: AbortController;
|
|
run: Promise<unknown>;
|
|
}) {
|
|
await flush();
|
|
params.controller.abort();
|
|
await params.run;
|
|
}
|
|
|
|
async function runSlackEventOnce(
|
|
monitorSlackProvider: SlackProviderMonitor,
|
|
name: string,
|
|
args: unknown,
|
|
opts?: { botToken?: string; appToken?: string },
|
|
) {
|
|
const { controller, run } = startSlackMonitor(monitorSlackProvider, opts);
|
|
const handler = await getSlackHandlerOrThrow(name);
|
|
await handler(args);
|
|
await stopSlackMonitor({ controller, run });
|
|
}
|
|
|
|
export async function runSlackMessageOnce(
|
|
monitorSlackProvider: SlackProviderMonitor,
|
|
args: unknown,
|
|
opts?: { botToken?: string; appToken?: string },
|
|
) {
|
|
await runSlackEventOnce(monitorSlackProvider, "message", args, opts);
|
|
}
|
|
|
|
export const defaultSlackTestConfig = () => ({
|
|
messages: {
|
|
responsePrefix: "PFX",
|
|
ackReaction: "👀",
|
|
ackReactionScope: "group-mentions",
|
|
},
|
|
channels: {
|
|
slack: {
|
|
dm: { enabled: true, policy: "open", allowFrom: ["*"] },
|
|
groupPolicy: "open",
|
|
},
|
|
},
|
|
});
|
|
|
|
export function resetSlackTestState(config: Record<string, unknown> = defaultSlackTestConfig()) {
|
|
clearSlackInboundDeliveryStateForTest();
|
|
slackTestState.config = config;
|
|
slackTestState.appStartMock.mockReset().mockResolvedValue(undefined);
|
|
slackTestState.appStopMock.mockReset().mockResolvedValue(undefined);
|
|
slackTestState.sendMock.mockReset().mockResolvedValue(undefined);
|
|
slackTestState.replyMock.mockReset();
|
|
slackTestState.updateLastRouteMock.mockReset();
|
|
slackTestState.reactMock.mockReset();
|
|
slackTestState.reactionAddMock.mockReset();
|
|
slackTestState.reactionRemoveMock.mockReset();
|
|
slackTestState.readAllowFromStoreMock.mockReset().mockResolvedValue([]);
|
|
slackTestState.upsertPairingRequestMock.mockReset().mockResolvedValue({
|
|
code: "PAIRCODE",
|
|
created: true,
|
|
});
|
|
slackTestState.resolveSlackUserAllowlistMock
|
|
.mockReset()
|
|
.mockImplementation(async ({ entries }) =>
|
|
entries.map((input) => ({ input, resolved: false })),
|
|
);
|
|
const client = getSlackClient();
|
|
client.auth.test.mockReset().mockResolvedValue({ user_id: "bot-user", bot_id: "bot-id" });
|
|
client.conversations.info.mockReset().mockResolvedValue({
|
|
channel: { name: "dm", is_im: true },
|
|
});
|
|
client.conversations.replies.mockReset().mockResolvedValue({ messages: [] });
|
|
client.conversations.history.mockReset().mockResolvedValue({ messages: [] });
|
|
client.users.info.mockReset().mockResolvedValue({
|
|
user: { profile: { display_name: "Ada" } },
|
|
});
|
|
client.assistant.threads.setStatus.mockReset().mockResolvedValue({ ok: true });
|
|
getSlackHandlers()?.clear();
|
|
}
|
|
|
|
vi.mock("./monitor/config.runtime.js", async () => {
|
|
const actual = await vi.importActual<typeof import("./monitor/config.runtime.js")>(
|
|
"./monitor/config.runtime.js",
|
|
);
|
|
return {
|
|
...actual,
|
|
loadConfig: () => slackTestState.config,
|
|
readSessionUpdatedAt: vi.fn(() => undefined),
|
|
recordSessionMetaFromInbound: vi.fn().mockResolvedValue(undefined),
|
|
resolveStorePath: vi.fn(() => "/tmp/openclaw-sessions.json"),
|
|
updateLastRoute: (...args: unknown[]) => slackTestState.updateLastRouteMock(...args),
|
|
};
|
|
});
|
|
|
|
vi.mock("./monitor/reply.runtime.js", async () => {
|
|
const actual = await vi.importActual<typeof import("./monitor/reply.runtime.js")>(
|
|
"./monitor/reply.runtime.js",
|
|
);
|
|
type DispatchParams = Parameters<typeof actual.dispatchInboundMessage>[0];
|
|
type BufferedDispatchParams = Parameters<
|
|
typeof actual.dispatchReplyWithBufferedBlockDispatcher
|
|
>[0];
|
|
type ReplyResolver = NonNullable<DispatchParams["replyResolver"]>;
|
|
const replyResolver: ReplyResolver = (...args) =>
|
|
slackTestState.replyMock(...args) as ReturnType<ReplyResolver>;
|
|
return {
|
|
...actual,
|
|
dispatchInboundMessage: (params: Parameters<typeof actual.dispatchInboundMessage>[0]) =>
|
|
actual.dispatchInboundMessage({
|
|
...params,
|
|
replyResolver,
|
|
}),
|
|
dispatchReplyWithBufferedBlockDispatcher: (params: BufferedDispatchParams) =>
|
|
actual.dispatchReplyWithBufferedBlockDispatcher({
|
|
...params,
|
|
replyResolver,
|
|
}),
|
|
};
|
|
});
|
|
|
|
vi.mock("./resolve-channels.js", () => ({
|
|
resolveSlackChannelAllowlist: async ({ entries }: { entries: string[] }) =>
|
|
entries.map((input) => ({ input, resolved: false })),
|
|
}));
|
|
|
|
vi.mock("./resolve-users.js", () => ({
|
|
resolveSlackUserAllowlist: (params: { entries: string[] }) =>
|
|
slackTestState.resolveSlackUserAllowlistMock(params),
|
|
}));
|
|
|
|
vi.mock("./monitor/send.runtime.js", () => {
|
|
return {
|
|
sendMessageSlack: (...args: unknown[]) => slackTestState.sendMock(...args),
|
|
};
|
|
});
|
|
|
|
vi.mock("./monitor/conversation.runtime.js", async () => {
|
|
const actual = await vi.importActual<typeof import("./monitor/conversation.runtime.js")>(
|
|
"./monitor/conversation.runtime.js",
|
|
);
|
|
return {
|
|
...actual,
|
|
readChannelAllowFromStore: (...args: unknown[]) =>
|
|
slackTestState.readAllowFromStoreMock(...args),
|
|
recordInboundSession: vi.fn().mockResolvedValue(undefined),
|
|
upsertChannelPairingRequest: (...args: unknown[]) =>
|
|
slackTestState.upsertPairingRequestMock(...args),
|
|
};
|
|
});
|
|
|
|
vi.mock("@slack/bolt", () => {
|
|
const { handlers, client: slackClient } = ensureSlackTestRuntime();
|
|
class App {
|
|
client = slackClient;
|
|
receiver: unknown;
|
|
middlewares: SlackMiddleware[] = [];
|
|
|
|
constructor(args?: { receiver?: unknown }) {
|
|
this.receiver = args?.receiver;
|
|
}
|
|
use(middleware: SlackMiddleware) {
|
|
this.middlewares.push(middleware);
|
|
}
|
|
event(name: string, handler: SlackHandler) {
|
|
handlers.set(name, async (args: unknown) => {
|
|
const eventArgs =
|
|
args && typeof args === "object" && !Array.isArray(args)
|
|
? (args as Record<string, unknown>)
|
|
: {};
|
|
const run = async (index: number): Promise<void> => {
|
|
const middleware = this.middlewares[index];
|
|
if (!middleware) {
|
|
await handler(args);
|
|
return;
|
|
}
|
|
await middleware({
|
|
...eventArgs,
|
|
next: () => run(index + 1),
|
|
});
|
|
};
|
|
await run(0);
|
|
});
|
|
}
|
|
command() {
|
|
/* no-op */
|
|
}
|
|
start = (...args: unknown[]) => slackTestState.appStartMock(...args);
|
|
stop = (...args: unknown[]) => slackTestState.appStopMock(...args);
|
|
}
|
|
class HTTPReceiver {
|
|
requestListener = vi.fn();
|
|
}
|
|
class SocketModeReceiver {
|
|
client = {
|
|
...slackClient,
|
|
on: vi.fn(),
|
|
off: vi.fn(),
|
|
};
|
|
}
|
|
return {
|
|
App,
|
|
HTTPReceiver,
|
|
SocketModeReceiver,
|
|
default: { App, HTTPReceiver, SocketModeReceiver },
|
|
};
|
|
});
|