test: stabilize gateway tests

This commit is contained in:
Peter Steinberger
2026-01-04 04:16:38 +01:00
parent 3c4c2aa98c
commit 24aa3e3311
21 changed files with 192 additions and 104 deletions

View File

@@ -54,7 +54,9 @@ function ensureAgentJobListener() {
? (evt.data.endedAt as number)
: undefined;
const error =
typeof evt.data?.error === "string" ? (evt.data.error as string) : undefined;
typeof evt.data?.error === "string"
? (evt.data.error as string)
: undefined;
agentRunStarts.delete(evt.runId);
recordAgentJobSnapshot({
runId: evt.runId,
@@ -115,7 +117,9 @@ export async function waitForAgentJob(params: {
? (evt.data.endedAt as number)
: undefined;
const error =
typeof evt.data?.error === "string" ? (evt.data.error as string) : undefined;
typeof evt.data?.error === "string"
? (evt.data.error as string)
: undefined;
const snapshot: AgentJobSnapshot = {
runId: evt.runId,
state: state === "error" ? "error" : "done",

View File

@@ -1,22 +1,22 @@
import { randomUUID } from "node:crypto";
import { agentCommand } from "../../commands/agent.js";
import { loadConfig } from "../../config/config.js";
import { type SessionEntry, saveSessionStore } from "../../config/sessions.js";
import { registerAgentRunContext } from "../../infra/agent-events.js";
import { defaultRuntime } from "../../runtime.js";
import { normalizeE164 } from "../../utils.js";
import { loadConfig } from "../../config/config.js";
import { saveSessionStore, type SessionEntry } from "../../config/sessions.js";
import { resolveSendPolicy } from "../../sessions/send-policy.js";
import { normalizeE164 } from "../../utils.js";
import {
type AgentWaitParams,
ErrorCodes,
errorShape,
formatValidationErrors,
validateAgentParams,
validateAgentWaitParams,
type AgentWaitParams,
} from "../protocol/index.js";
import { formatForLog } from "../ws-log.js";
import { loadSessionEntry } from "../session-utils.js";
import { formatForLog } from "../ws-log.js";
import { waitForAgentJob } from "./agent-job.js";
import type { GatewayRequestHandlers } from "./types.js";
@@ -67,7 +67,8 @@ export const agentHandlers: GatewayRequestHandlers = {
let cfgForAgent: ReturnType<typeof loadConfig> | undefined;
if (requestedSessionKey) {
const { cfg, storePath, store, entry } = loadSessionEntry(requestedSessionKey);
const { cfg, storePath, store, entry } =
loadSessionEntry(requestedSessionKey);
cfgForAgent = cfg;
const now = Date.now();
const sessionId = entry?.sessionId ?? randomUUID();
@@ -132,13 +133,17 @@ export const agentHandlers: GatewayRequestHandlers = {
const lastChannel = sessionEntry?.lastChannel;
const lastTo =
typeof sessionEntry?.lastTo === "string" ? sessionEntry.lastTo.trim() : "";
typeof sessionEntry?.lastTo === "string"
? sessionEntry.lastTo.trim()
: "";
const resolvedChannel = (() => {
if (requestedChannel === "last") {
// WebChat is not a deliverable surface. Treat it as "unset" for routing,
// so VoiceWake and CLI callers don't get stuck with deliver=false.
return lastChannel && lastChannel !== "webchat" ? lastChannel : "whatsapp";
return lastChannel && lastChannel !== "webchat"
? lastChannel
: "whatsapp";
}
if (
requestedChannel === "whatsapp" ||
@@ -150,7 +155,9 @@ export const agentHandlers: GatewayRequestHandlers = {
) {
return requestedChannel;
}
return lastChannel && lastChannel !== "webchat" ? lastChannel : "whatsapp";
return lastChannel && lastChannel !== "webchat"
? lastChannel
: "whatsapp";
})();
const resolvedTo = (() => {

View File

@@ -2,9 +2,10 @@ import { randomUUID } from "node:crypto";
import { resolveThinkingDefault } from "../../agents/model-selection.js";
import { agentCommand } from "../../commands/agent.js";
import { saveSessionStore, type SessionEntry } from "../../config/sessions.js";
import { type SessionEntry, saveSessionStore } from "../../config/sessions.js";
import { defaultRuntime } from "../../runtime.js";
import { resolveSendPolicy } from "../../sessions/send-policy.js";
import { buildMessageWithAttachments } from "../chat-attachments.js";
import {
ErrorCodes,
errorShape,
@@ -21,7 +22,6 @@ import {
resolveSessionModelRef,
} from "../session-utils.js";
import { formatForLog } from "../ws-log.js";
import { buildMessageWithAttachments } from "../chat-attachments.js";
import type { GatewayRequestHandlers } from "./types.js";
export const chatHandlers: GatewayRequestHandlers = {
@@ -49,7 +49,8 @@ export const chatHandlers: GatewayRequestHandlers = {
const defaultLimit = 200;
const requested = typeof limit === "number" ? limit : defaultLimit;
const max = Math.min(hardMax, requested);
const sliced = rawMessages.length > max ? rawMessages.slice(-max) : rawMessages;
const sliced =
rawMessages.length > max ? rawMessages.slice(-max) : rawMessages;
const capped = capArrayByJsonBytes(
sliced,
MAX_CHAT_HISTORY_MESSAGES_BYTES,
@@ -102,7 +103,10 @@ export const chatHandlers: GatewayRequestHandlers = {
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, "runId does not match sessionKey"),
errorShape(
ErrorCodes.INVALID_REQUEST,
"runId does not match sessionKey",
),
);
return;
}
@@ -123,8 +127,18 @@ export const chatHandlers: GatewayRequestHandlers = {
context.bridgeSendToSession(sessionKey, "chat", payload);
respond(true, { ok: true, aborted: true });
},
"chat.send": async ({ params, respond, context, client, isWebchatConnect }) => {
if (client && isWebchatConnect(client.connect) && !context.hasConnectedMobileNode()) {
"chat.send": async ({
params,
respond,
context,
client,
isWebchatConnect,
}) => {
if (
client &&
isWebchatConnect(client.connect) &&
!context.hasConnectedMobileNode()
) {
respond(
false,
undefined,
@@ -220,7 +234,10 @@ export const chatHandlers: GatewayRequestHandlers = {
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, "send blocked by session policy"),
errorShape(
ErrorCodes.INVALID_REQUEST,
"send blocked by session policy",
),
);
return;
}

View File

@@ -1,8 +1,8 @@
import type { CronJobCreate, CronJobPatch } from "../../cron/types.js";
import {
readCronRunLogEntries,
resolveCronRunLogPath,
} from "../../cron/run-log.js";
import type { CronJobCreate, CronJobPatch } from "../../cron/types.js";
import {
ErrorCodes,
errorShape,
@@ -102,7 +102,10 @@ export const cronHandlers: GatewayRequestHandlers = {
id: string;
patch: Record<string, unknown>;
};
const job = await context.cron.update(p.id, p.patch as unknown as CronJobPatch);
const job = await context.cron.update(
p.id,
p.patch as unknown as CronJobPatch,
);
respond(true, job, undefined);
},
"cron.remove": async ({ params, respond, context }) => {

View File

@@ -13,7 +13,9 @@ export const healthHandlers: GatewayRequestHandlers = {
if (cached && now - cached.ts < HEALTH_REFRESH_INTERVAL_MS) {
respond(true, cached, undefined, { cached: true });
void refreshHealthSnapshot({ probe: false }).catch((err) =>
logHealth.error(`background health refresh failed: ${formatError(err)}`),
logHealth.error(
`background health refresh failed: ${formatError(err)}`,
),
);
return;
}

View File

@@ -23,7 +23,11 @@ export const modelsHandlers: GatewayRequestHandlers = {
const models = await context.loadGatewayModelCatalog();
respond(true, { models }, undefined);
} catch (err) {
respond(false, undefined, errorShape(ErrorCodes.UNAVAILABLE, String(err)));
respond(
false,
undefined,
errorShape(ErrorCodes.UNAVAILABLE, String(err)),
);
}
},
};

View File

@@ -244,7 +244,11 @@ export const nodeHandlers: GatewayRequestHandlers = {
);
return;
}
respond(true, { nodeId: updated.nodeId, displayName: updated.displayName }, undefined);
respond(
true,
{ nodeId: updated.nodeId, displayName: updated.displayName },
undefined,
);
} catch (err) {
respond(
false,
@@ -449,7 +453,9 @@ export const nodeHandlers: GatewayRequestHandlers = {
try {
const paramsJSON =
"params" in p && p.params !== undefined ? JSON.stringify(p.params) : null;
"params" in p && p.params !== undefined
? JSON.stringify(p.params)
: null;
const res = await context.bridge.invoke({
nodeId,
command,

View File

@@ -1,12 +1,16 @@
import type { ClawdisConfig } from "../../config/config.js";
import {
loadConfig,
readConfigFileSnapshot,
writeConfigFile,
} from "../../config/config.js";
import { type DiscordProbe, probeDiscord } from "../../discord/probe.js";
import { type IMessageProbe, probeIMessage } from "../../imessage/probe.js";
import type { ClawdisConfig } from "../../config/config.js";
import { loadConfig, readConfigFileSnapshot, writeConfigFile } from "../../config/config.js";
import { webAuthExists } from "../../providers/web/index.js";
import { getWebAuthAgeMs, readWebSelfId } from "../../web/session.js";
import { probeSignal, type SignalProbe } from "../../signal/probe.js";
import { probeTelegram, type TelegramProbe } from "../../telegram/probe.js";
import { resolveTelegramToken } from "../../telegram/token.js";
import { getWebAuthAgeMs, readWebSelfId } from "../../web/session.js";
import {
ErrorCodes,
errorShape,
@@ -35,7 +39,8 @@ export const providersHandlers: GatewayRequestHandlers = {
typeof timeoutMsRaw === "number" ? Math.max(1000, timeoutMsRaw) : 10_000;
const cfg = loadConfig();
const telegramCfg = cfg.telegram;
const telegramEnabled = Boolean(telegramCfg) && telegramCfg?.enabled !== false;
const telegramEnabled =
Boolean(telegramCfg) && telegramCfg?.enabled !== false;
const { token: telegramToken, source: tokenSource } = telegramEnabled
? resolveTelegramToken(cfg)
: { token: "", source: "none" as const };
@@ -55,9 +60,7 @@ export const providersHandlers: GatewayRequestHandlers = {
const discordEnvToken = discordEnabled
? process.env.DISCORD_BOT_TOKEN?.trim()
: "";
const discordConfigToken = discordEnabled
? discordCfg?.token?.trim()
: "";
const discordConfigToken = discordEnabled ? discordCfg?.token?.trim() : "";
const discordToken = discordEnvToken || discordConfigToken || "";
const discordTokenSource = discordEnvToken
? "env"
@@ -203,7 +206,11 @@ export const providersHandlers: GatewayRequestHandlers = {
delete nextCfg.telegram;
}
await writeConfigFile(nextCfg);
respond(true, { cleared: hadToken, envToken: Boolean(envToken) }, undefined);
respond(
true,
{ cleared: hadToken, envToken: Boolean(envToken) },
undefined,
);
} catch (err) {
respond(
false,

View File

@@ -1,7 +1,7 @@
import { loadConfig } from "../../config/config.js";
import { sendMessageDiscord } from "../../discord/index.js";
import { shouldLogVerbose } from "../../globals.js";
import { sendMessageIMessage } from "../../imessage/index.js";
import { loadConfig } from "../../config/config.js";
import { sendMessageSignal } from "../../signal/index.js";
import { sendMessageTelegram } from "../../telegram/send.js";
import { resolveTelegramToken } from "../../telegram/token.js";

View File

@@ -423,22 +423,35 @@ export const sessionsHandlers: GatewayRequestHandlers = {
const { storePath, store, entry } = loadSessionEntry(key);
const sessionId = entry?.sessionId;
if (!sessionId) {
respond(true, { ok: true, key, compacted: false, reason: "no sessionId" }, undefined);
respond(
true,
{ ok: true, key, compacted: false, reason: "no sessionId" },
undefined,
);
return;
}
const filePath = resolveSessionTranscriptCandidates(sessionId, storePath).find(
(candidate) => fs.existsSync(candidate),
);
const filePath = resolveSessionTranscriptCandidates(
sessionId,
storePath,
).find((candidate) => fs.existsSync(candidate));
if (!filePath) {
respond(true, { ok: true, key, compacted: false, reason: "no transcript" }, undefined);
respond(
true,
{ ok: true, key, compacted: false, reason: "no transcript" },
undefined,
);
return;
}
const raw = fs.readFileSync(filePath, "utf-8");
const lines = raw.split(/\r?\n/).filter((l) => l.trim().length > 0);
if (lines.length <= maxLines) {
respond(true, { ok: true, key, compacted: false, kept: lines.length }, undefined);
respond(
true,
{ ok: true, key, compacted: false, kept: lines.length },
undefined,
);
return;
}

View File

@@ -1,6 +1,6 @@
import { DEFAULT_AGENT_WORKSPACE_DIR } from "../../agents/workspace.js";
import { installSkill } from "../../agents/skills-install.js";
import { buildWorkspaceSkillStatus } from "../../agents/skills-status.js";
import { DEFAULT_AGENT_WORKSPACE_DIR } from "../../agents/workspace.js";
import type { ClawdisConfig } from "../../config/config.js";
import { loadConfig, writeConfigFile } from "../../config/config.js";
import { resolveUserPath } from "../../utils.js";
@@ -64,7 +64,9 @@ export const skillsHandlers: GatewayRequestHandlers = {
respond(
result.ok,
result,
result.ok ? undefined : errorShape(ErrorCodes.UNAVAILABLE, result.message),
result.ok
? undefined
: errorShape(ErrorCodes.UNAVAILABLE, result.message),
);
},
"skills.update": async ({ params, respond }) => {
@@ -115,6 +117,10 @@ export const skillsHandlers: GatewayRequestHandlers = {
skills,
};
await writeConfigFile(nextConfig);
respond(true, { ok: true, skillKey: p.skillKey, config: current }, undefined);
respond(
true,
{ ok: true, skillKey: p.skillKey, config: current },
undefined,
);
},
};

View File

@@ -65,7 +65,8 @@ export const systemHandlers: GatewayRequestHandlers = {
Number.isFinite(params.lastInputSeconds)
? params.lastInputSeconds
: undefined;
const reason = typeof params.reason === "string" ? params.reason : undefined;
const reason =
typeof params.reason === "string" ? params.reason : undefined;
const tags =
Array.isArray(params.tags) &&
params.tags.every((t) => typeof t === "string")

View File

@@ -8,7 +8,11 @@ import type { GatewayRequestHandlers } from "./types.js";
export const talkHandlers: GatewayRequestHandlers = {
"talk.mode": ({ params, respond, context, client, isWebchatConnect }) => {
if (client && isWebchatConnect(client.connect) && !context.hasConnectedMobileNode()) {
if (
client &&
isWebchatConnect(client.connect) &&
!context.hasConnectedMobileNode()
) {
respond(
false,
undefined,

View File

@@ -4,9 +4,13 @@ import type { HealthSummary } from "../../commands/health.js";
import type { CronService } from "../../cron/service.js";
import type { startNodeBridgeServer } from "../../infra/bridge/server.js";
import type { WizardSession } from "../../wizard/session.js";
import type { ConnectParams, ErrorShape, RequestFrame } from "../protocol/index.js";
import type { DedupeEntry } from "../server-shared.js";
import type {
ConnectParams,
ErrorShape,
RequestFrame,
} from "../protocol/index.js";
import type { ProviderRuntimeSnapshot } from "../server-providers.js";
import type { DedupeEntry } from "../server-shared.js";
export type GatewayClient = {
connect: ConnectParams;

View File

@@ -1,4 +1,7 @@
import { loadVoiceWakeConfig, setVoiceWakeTriggers } from "../../infra/voicewake.js";
import {
loadVoiceWakeConfig,
setVoiceWakeTriggers,
} from "../../infra/voicewake.js";
import { ErrorCodes, errorShape } from "../protocol/index.js";
import { normalizeVoiceWakeTriggers } from "../server-utils.js";
import { formatForLog } from "../ws-log.js";

View File

@@ -1,7 +1,6 @@
import { randomUUID } from "node:crypto";
import { WizardSession } from "../../wizard/session.js";
import { defaultRuntime } from "../../runtime.js";
import { WizardSession } from "../../wizard/session.js";
import {
ErrorCodes,
errorShape,
@@ -39,7 +38,8 @@ export const wizardHandlers: GatewayRequestHandlers = {
const sessionId = randomUUID();
const opts = {
mode: params.mode as "local" | "remote" | undefined,
workspace: typeof params.workspace === "string" ? params.workspace : undefined,
workspace:
typeof params.workspace === "string" ? params.workspace : undefined,
};
const session = new WizardSession((prompter) =>
context.wizardRunner(opts, defaultRuntime, prompter),