Skip to content

Commit 8b9afbd

Browse files
Merge remote-tracking branch 'upstream/main' into pr-118073-prep
2 parents db5c4d6 + 0c32879 commit 8b9afbd

43 files changed

Lines changed: 772 additions & 94 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/plugins/sdk-channel-plugins.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,13 @@ resolved config unchanged, stopping one account settles only that account's
213213
monitor and drain, and a fresh monitor recovers that account's rows exactly
214214
once. If any guarantee cannot be proved, omit the flag.
215215

216+
### Runtime lifecycle status
217+
218+
For channel-authored runtime state, `ChannelAccountSnapshot.lifecycle` is the
219+
successor to `healthState`. Existing plugins may keep publishing `healthState`
220+
during adoption, and core-derived policy writes remain supported. There is no
221+
removal date; removal waits for external channel-plugin adoption.
222+
216223
### Typing indicators
217224

218225
If your channel supports typing indicators outside inbound replies, expose

‎extensions/buzz/src/gateway.lifecycle.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,16 @@ describe("Buzz gateway lifecycle", () => {
165165

166166
await vi.waitFor(() => expect(gatewayMocks.startBuzzBus).toHaveBeenCalledOnce());
167167
expect(gatewayMocks.startBuzzBus.mock.calls[0]?.[0].profileName).toBe("Molt");
168+
expect(setStatus).toHaveBeenCalledWith({
169+
accountId: account.accountId,
170+
running: true,
171+
lifecycle: "ready",
172+
configured: true,
173+
enabled: account.enabled,
174+
baseUrl: account.relayUrl,
175+
publicKey: BOT_PUBLIC_KEY,
176+
lastError: null,
177+
});
168178
gatewayMocks.onFatalError?.(new Error("relay failed"));
169179

170180
await vi.waitFor(() => expect(gatewayMocks.startBuzzBus).toHaveBeenCalledTimes(2), {
@@ -174,6 +184,7 @@ describe("Buzz gateway lifecycle", () => {
174184
expect(setStatus).toHaveBeenCalledWith({
175185
accountId: account.accountId,
176186
running: false,
187+
lifecycle: "recovering",
177188
lastError: "relay failed",
178189
});
179190

‎extensions/buzz/src/gateway.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ export async function startBuzzGatewayAccount(ctx: ChannelGatewayContext<Resolve
141141
ctx.setStatus({
142142
accountId: account.accountId,
143143
running: true,
144+
lifecycle: "ready",
144145
configured: true,
145146
enabled: account.enabled,
146147
baseUrl: account.relayUrl,
@@ -170,6 +171,7 @@ export async function startBuzzGatewayAccount(ctx: ChannelGatewayContext<Resolve
170171
ctx.setStatus({
171172
accountId: account.accountId,
172173
running: false,
174+
...(cycleError ? { lifecycle: "recovering" as const } : {}),
173175
...(cycleError ? { lastError: cycleError.message } : {}),
174176
});
175177
}

‎extensions/discord/src/monitor/provider.lifecycle.test.ts‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { EventEmitter } from "node:events";
33
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
44
import { beforeAll, beforeEach, describe, expect, it, vi, type Mock } from "vitest";
5-
import type { GatewayPlugin } from "../internal/gateway.js";
5+
import { GatewayCloseCodes, type GatewayPlugin } from "../internal/gateway.js";
66
import type { waitForDiscordGatewayStop } from "../monitor.gateway.js";
77
import {
88
DISCORD_GATEWAY_TRANSPORT_ACTIVITY_EVENT,
@@ -194,6 +194,8 @@ describe("runDiscordGatewayLifecycle", () => {
194194

195195
type StatusPatch = {
196196
connected?: boolean;
197+
lifecycle?: "ready" | "recovering" | "blocked";
198+
terminalDisconnect?: boolean;
197199
lastDisconnect?: null | Record<string, unknown>;
198200
lastError?: string | null;
199201
};
@@ -268,7 +270,8 @@ describe("runDiscordGatewayLifecycle", () => {
268270

269271
expectStatusPatch(
270272
statusSink,
271-
(patch) => patch.connected === true && patch.lastDisconnect === null,
273+
(patch) =>
274+
patch.connected === true && patch.lifecycle === "ready" && patch.lastDisconnect === null,
272275
);
273276
});
274277

@@ -363,7 +366,14 @@ describe("runDiscordGatewayLifecycle", () => {
363366
expectStatusPatch(
364367
statusSink,
365368
(patch) =>
366-
patch.connected === true && patch.lastDisconnect === null && patch.lastError === null,
369+
patch.connected === true &&
370+
patch.lifecycle === "ready" &&
371+
patch.lastDisconnect === null &&
372+
patch.lastError === null,
373+
);
374+
expectStatusPatch(
375+
statusSink,
376+
(patch) => patch.connected === false && patch.lifecycle === "recovering",
367377
);
368378
} finally {
369379
vi.useRealTimers();
@@ -618,11 +628,38 @@ describe("runDiscordGatewayLifecycle", () => {
618628
statusSink,
619629
(patch) =>
620630
patch.connected === false &&
631+
patch.lifecycle === "recovering" &&
621632
patch.lastDisconnect !== null &&
622633
patch.lastDisconnect?.status === 1006,
623634
);
624635
});
625636

637+
it.each([GatewayCloseCodes.AuthenticationFailed, GatewayCloseCodes.InvalidIntents])(
638+
"publishes blocked lifecycle for fatal gateway close code %s",
639+
async (closeCode) => {
640+
const { emitter, gateway } = createGatewayHarness();
641+
gateway.isConnected = true;
642+
getDiscordGatewayEmitterMock.mockReturnValueOnce(emitter);
643+
waitForDiscordGatewayStopMock.mockImplementationOnce(async () => {
644+
emitter.emit("debug", `Gateway websocket closed: ${closeCode}`);
645+
});
646+
647+
const { lifecycleParams, statusSink } = createLifecycleHarness({ gateway });
648+
649+
await expect(runDiscordGatewayLifecycle(lifecycleParams)).resolves.toBeUndefined();
650+
651+
expectStatusPatch(
652+
statusSink,
653+
(patch) =>
654+
patch.connected === false &&
655+
patch.lifecycle === "blocked" &&
656+
patch.terminalDisconnect === true &&
657+
patch.lastError === `Gateway websocket closed: ${closeCode}` &&
658+
patch.lastDisconnect?.status === closeCode,
659+
);
660+
},
661+
);
662+
626663
it("pushes disconnected status when the gateway schedules a reconnect", async () => {
627664
const { emitter, gateway } = createGatewayHarness();
628665
gateway.isConnected = true;
@@ -639,6 +676,7 @@ describe("runDiscordGatewayLifecycle", () => {
639676
statusSink,
640677
(patch) =>
641678
patch.connected === false &&
679+
patch.lifecycle === "recovering" &&
642680
patch.lastError === "Gateway reconnect scheduled in 1000ms (zombie, resume=true)",
643681
);
644682
});
@@ -665,7 +703,8 @@ describe("runDiscordGatewayLifecycle", () => {
665703
expectStatusPatch(statusSink, (patch) => patch.connected === false);
666704
expectStatusPatch(
667705
statusSink,
668-
(patch) => patch.connected === true && patch.lastDisconnect === null,
706+
(patch) =>
707+
patch.connected === true && patch.lifecycle === "ready" && patch.lastDisconnect === null,
669708
);
670709
} finally {
671710
vi.useRealTimers();

‎extensions/discord/src/monitor/provider.lifecycle.ts‎

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
// Discord provider module implements model/runtime integration.
2-
import {
3-
createConnectedChannelStatusPatch,
4-
createTransportActivityStatusPatch,
5-
} from "openclaw/plugin-sdk/gateway-runtime";
2+
import { createTransportActivityStatusPatch } from "openclaw/plugin-sdk/gateway-runtime";
63
import { asDateTimestampMs, parseStrictPositiveInteger } from "openclaw/plugin-sdk/number-runtime";
74
import { danger, sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
85
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
96
import { formatErrorMessage } from "openclaw/plugin-sdk/ssrf-runtime";
107
import { attachDiscordGatewayLogging } from "../gateway-logging.js";
8+
import { isFatalGatewayCloseCode } from "../internal/gateway-close-codes.js";
9+
import { GatewayCloseCodes } from "../internal/gateway.js";
1110
import { getDiscordGatewayEmitter, waitForDiscordGatewayStop } from "../monitor.gateway.js";
1211
import type { DiscordVoiceManager } from "../voice/manager.js";
1312
import {
@@ -20,7 +19,7 @@ import {
2019
type DiscordGatewayEvent,
2120
type DiscordGatewaySupervisor,
2221
} from "./gateway-supervisor.js";
23-
import type { DiscordMonitorStatusSink } from "./status.js";
22+
import { createDiscordReadyStatusPatch, type DiscordMonitorStatusSink } from "./status.js";
2423

2524
const DEFAULT_DISCORD_GATEWAY_READY_TIMEOUT_MS = 15_000;
2625
const DEFAULT_DISCORD_GATEWAY_RUNTIME_READY_TIMEOUT_MS = 30_000;
@@ -214,11 +213,7 @@ function createGatewayStatusObserver(params: {
214213
queuedForceStopError = err;
215214
};
216215
const pushConnectedStatus = (at: number) => {
217-
params.pushStatus({
218-
...createConnectedChannelStatusPatch(at),
219-
lastDisconnect: null,
220-
lastError: null,
221-
});
216+
params.pushStatus(createDiscordReadyStatusPatch(at));
222217
};
223218
const startReadyWatch = () => {
224219
clearReadyWatch();
@@ -249,6 +244,7 @@ function createGatewayStatusObserver(params: {
249244
);
250245
params.pushStatus({
251246
connected: false,
247+
lifecycle: "recovering",
252248
lastEventAt: at,
253249
lastDisconnect: {
254250
at,
@@ -277,8 +273,14 @@ function createGatewayStatusObserver(params: {
277273
if (message.includes("Gateway websocket closed")) {
278274
clearReadyWatch();
279275
const code = parseGatewayCloseCode(message);
276+
// Fatal gateway closes require operator repair. Keep the outer channel supervisor from
277+
// turning an invalid credential or configuration into an automatic restart loop.
278+
const terminalDisconnect =
279+
code !== undefined && isFatalGatewayCloseCode(code as GatewayCloseCodes);
280280
params.pushStatus({
281281
connected: false,
282+
lifecycle: terminalDisconnect ? "blocked" : "recovering",
283+
...(terminalDisconnect ? { terminalDisconnect: true, lastError: message } : {}),
282284
lastEventAt: at,
283285
lastDisconnect: {
284286
at,
@@ -291,6 +293,7 @@ function createGatewayStatusObserver(params: {
291293
clearReadyWatch();
292294
params.pushStatus({
293295
connected: false,
296+
lifecycle: "recovering",
294297
lastEventAt: at,
295298
lastError: message,
296299
});
@@ -333,11 +336,7 @@ async function waitForGatewayReady(params: {
333336
}
334337
if (params.gateway?.isConnected === true) {
335338
const at = Date.now();
336-
params.pushStatus?.({
337-
...createConnectedChannelStatusPatch(at),
338-
lastDisconnect: null,
339-
lastError: null,
340-
});
339+
params.pushStatus?.(createDiscordReadyStatusPatch(at));
341340
return "ready";
342341
}
343342
if (Date.now() >= deadlineAt) {
@@ -375,6 +374,7 @@ async function waitForGatewayReady(params: {
375374
);
376375
params.pushStatus?.({
377376
connected: false,
377+
lifecycle: "recovering",
378378
lastEventAt: restartAt,
379379
lastDisconnect: {
380380
at: restartAt,

‎extensions/discord/src/monitor/provider.test.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1172,8 +1172,12 @@ describe("monitorDiscordProvider", () => {
11721172
setStatus,
11731173
});
11741174

1175-
const statuses = setStatus.mock.calls.map((call) => call[0] as { connected?: boolean });
1176-
expect(statuses.some((status) => status.connected === true)).toBe(true);
1175+
const statuses = setStatus.mock.calls.map(
1176+
(call) => call[0] as { connected?: boolean; lifecycle?: string },
1177+
);
1178+
expect(
1179+
statuses.some((status) => status.connected === true && status.lifecycle === "ready"),
1180+
).toBe(true);
11771181
expect(statuses.some((status) => status.connected === false)).toBe(true);
11781182
});
11791183

‎extensions/discord/src/monitor/provider.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// Discord provider module implements model/runtime integration.
22
import type { ChannelRuntimeSurface } from "openclaw/plugin-sdk/channel-contract";
33
import type { OpenClawConfig, ReplyToMode } from "openclaw/plugin-sdk/config-contracts";
4-
import { createConnectedChannelStatusPatch } from "openclaw/plugin-sdk/gateway-runtime";
54
import { resolveTextChunkLimit } from "openclaw/plugin-sdk/reply-chunking";
65
import { getRuntimeConfig } from "openclaw/plugin-sdk/runtime-config-snapshot";
76
import { logVerbose, warn } from "openclaw/plugin-sdk/runtime-env";
@@ -42,7 +41,7 @@ import {
4241
} from "./provider.startup.js";
4342
import { resolveDiscordRestFetch } from "./rest-fetch.js";
4443
import { formatDiscordStartupStatusMessage } from "./startup-status.js";
45-
import type { DiscordMonitorStatusSink } from "./status.js";
44+
import { createDiscordReadyStatusPatch, type DiscordMonitorStatusSink } from "./status.js";
4645

4746
export type MonitorDiscordOpts = {
4847
token?: string;
@@ -482,7 +481,7 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
482481
}),
483482
);
484483
if (lifecycleGateway?.isConnected) {
485-
opts.setStatus?.(createConnectedChannelStatusPatch());
484+
opts.setStatus?.(createDiscordReadyStatusPatch());
486485
}
487486

488487
lifecycleStarted = true;

‎extensions/discord/src/monitor/status.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
// Discord plugin module implements status behavior.
2+
import { createConnectedChannelStatusPatch } from "openclaw/plugin-sdk/gateway-runtime";
3+
24
type DiscordMonitorStatusPatch = {
35
connected?: boolean;
46
lastEventAt?: number | null;
@@ -15,9 +17,22 @@ type DiscordMonitorStatusPatch = {
1517
| null;
1618
lastInboundAt?: number | null;
1719
lastError?: string | null;
20+
lifecycle?: "ready" | "recovering" | "blocked";
21+
terminalDisconnect?: boolean;
1822
busy?: boolean;
1923
activeRuns?: number;
2024
lastRunActivityAt?: number | null;
2125
};
2226

2327
export type DiscordMonitorStatusSink = (patch: DiscordMonitorStatusPatch) => void;
28+
29+
/** READY proves a prior terminal failure was repaired, so the account is restartable again. */
30+
export function createDiscordReadyStatusPatch(at: number = Date.now()) {
31+
return {
32+
...createConnectedChannelStatusPatch(at),
33+
lifecycle: "ready" as const,
34+
terminalDisconnect: undefined,
35+
lastDisconnect: null,
36+
lastError: null,
37+
};
38+
}

‎extensions/irc/src/monitor.test.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,11 @@ async function startDisconnectingIrcServer(): Promise<DisconnectingIrcServer> {
103103
idx = buffer.indexOf("\n");
104104
lines.push(line);
105105
if (line.startsWith("USER ")) {
106-
socket.write(":server 001 bot :welcome\r\n");
106+
if (connectionNumber === 2) {
107+
socket.destroy();
108+
} else {
109+
socket.write(":server 001 bot :welcome\r\n");
110+
}
107111
if (connectionNumber === 1) {
108112
setTimeout(() => socket.destroy(), 10);
109113
}
@@ -333,6 +337,7 @@ describe("irc monitor reconnect", () => {
333337
it("reconnects when an established IRC socket closes", async () => {
334338
await withIngressQueue(async (ingressQueue) => {
335339
installMonitorRuntime();
340+
const statusSink = vi.fn();
336341
const server = await startDisconnectingIrcServer();
337342
const config = {
338343
channels: {
@@ -350,14 +355,20 @@ describe("irc monitor reconnect", () => {
350355
let monitor: { stop: () => Promise<void> } | undefined;
351356

352357
try {
353-
monitor = await monitorIrcProvider({ config, ingressQueue });
358+
monitor = await monitorIrcProvider({ config, ingressQueue, statusSink });
354359
await waitForIrcCondition(
355360
() =>
356-
server.connectionCount >= 2 &&
357-
server.lines.filter((line) => line === "USER bot 0 * :OpenClaw").length >= 2,
358-
"expected IRC monitor to reconnect after the first socket closed",
361+
server.connectionCount >= 3 &&
362+
server.lines.filter((line) => line === "USER bot 0 * :OpenClaw").length >= 3 &&
363+
statusSink.mock.calls.filter(([patch]) => patch.lifecycle).length >= 4,
364+
"expected IRC monitor to recover after a failed reconnect attempt",
359365
);
360-
expect(server.connectionCount).toBeGreaterThanOrEqual(2);
366+
expect(server.connectionCount).toBeGreaterThanOrEqual(3);
367+
expect(
368+
statusSink.mock.calls.flatMap(([patch]) =>
369+
patch.lifecycle ? [patch.lifecycle as string] : [],
370+
),
371+
).toEqual(["ready", "recovering", "recovering", "ready"]);
361372
} finally {
362373
if (monitor) {
363374
await monitor.stop();

0 commit comments

Comments
 (0)