Feat/upgrade openclaw (#729)

This commit is contained in:
paisley
2026-04-01 14:22:47 +08:00
committed by GitHub
Unverified
parent bf5b089158
commit d34a88e629
24 changed files with 903 additions and 600 deletions

View File

@@ -235,8 +235,13 @@ export class GatewayManager extends EventEmitter {
assertLifecycle: (phase) => {
this.lifecycleController.assert(startEpoch, phase);
},
findExistingGateway: async (port, ownedPid) => {
return await findExistingGatewayProcess({ port, ownedPid });
findExistingGateway: async (port) => {
// Always read the current process pid dynamically so that retries
// don't treat a just-spawned gateway as an orphan. The ownedPid
// snapshot captured at start() entry is stale after startProcess()
// replaces this.process — leading to the just-started pid being
// immediately killed as a false orphan on the next retry iteration.
return await findExistingGatewayProcess({ port, ownedPid: this.process?.pid });
},
connect: async (port, externalToken) => {
await this.connect(port, externalToken);
@@ -335,9 +340,14 @@ export class GatewayManager extends EventEmitter {
}
}
// Close WebSocket
// Close WebSocket — use terminate() to force-close the TCP connection
// immediately without waiting for the WebSocket close handshake.
// ws.close() sends a close frame and waits for the server to respond;
// if the gateway process is being killed concurrently, the handshake
// never completes and the connection stays ESTABLISHED indefinitely,
// accumulating leaked connections on every restart cycle.
if (this.ws) {
this.ws.close(1000, 'Gateway stopped by user');
try { this.ws.terminate(); } catch { /* ignore */ }
this.ws = null;
}
@@ -792,7 +802,7 @@ export class GatewayManager extends EventEmitter {
onMessage: (message) => {
this.handleMessage(message);
},
onCloseAfterHandshake: () => {
onCloseAfterHandshake: (closeCode) => {
this.connectionMonitor.clear();
if (this.status.state === 'running') {
this.setStatus({ state: 'stopped' });
@@ -801,7 +811,11 @@ export class GatewayManager extends EventEmitter {
// handler (`onExit`) which calls scheduleReconnect(). Triggering
// reconnect from WS close as well races with the exit handler and can
// cause double start() attempts or port conflicts during TCP TIME_WAIT.
if (process.platform !== 'win32') {
//
// Exception: code=1012 means the Gateway is performing an in-process
// restart (e.g. config reload). The UtilityProcess stays alive, so
// `onExit` will never fire — we MUST reconnect from the WS close path.
if (process.platform !== 'win32' || closeCode === 1012) {
this.scheduleReconnect();
}
}

View File

@@ -117,6 +117,10 @@ export async function launchGatewayProcess(options: {
const lastSpawnSummary = `mode=${mode}, entry="${entryScript}", args="${options.sanitizeSpawnArgs(gatewayArgs).join(' ')}", cwd="${openclawDir}"`;
const runtimeEnv = { ...forkEnv };
// Only apply the fetch/child_process preload in dev mode.
// In packaged builds Electron's UtilityProcess rejects NODE_OPTIONS
// with --require, logging "Most NODE_OPTIONs are not supported in
// packaged apps" and the preload never loads.
if (!app.isPackaged) {
try {
const preloadPath = ensureGatewayFetchPreload();

View File

@@ -2,79 +2,60 @@ export type RestartDecision =
| { allow: true }
| {
allow: false;
reason: 'circuit_open' | 'budget_exceeded' | 'cooldown_active';
reason: 'cooldown_active';
retryAfterMs: number;
};
type RestartGovernorOptions = {
maxRestartsPerWindow: number;
windowMs: number;
baseCooldownMs: number;
maxCooldownMs: number;
circuitOpenMs: number;
stableResetMs: number;
/** Minimum interval between consecutive restarts (ms). */
cooldownMs: number;
};
const DEFAULT_OPTIONS: RestartGovernorOptions = {
maxRestartsPerWindow: 4,
windowMs: 10 * 60 * 1000,
baseCooldownMs: 2500,
maxCooldownMs: 2 * 60 * 1000,
circuitOpenMs: 10 * 60 * 1000,
stableResetMs: 2 * 60 * 1000,
cooldownMs: 2500,
};
/**
* Lightweight restart rate-limiter.
*
* Prevents rapid-fire restarts by enforcing a simple cooldown between
* consecutive restart executions. Nothing more — no circuit breakers,
* no sliding-window budgets, no exponential back-off. Those mechanisms
* were previously present but removed because:
*
* 1. The root causes of infinite restart loops (stale ownedPid, port
* contention, leaked WebSocket connections) have been fixed at their
* source.
* 2. A 10-minute circuit-breaker lockout actively hurt the user
* experience: legitimate config changes were silently dropped.
* 3. The complexity made the restart path harder to reason about during
* debugging.
*/
export class GatewayRestartGovernor {
private readonly options: RestartGovernorOptions;
private restartTimestamps: number[] = [];
private circuitOpenUntil = 0;
private consecutiveRestarts = 0;
private lastRestartAt = 0;
private lastRunningAt = 0;
private suppressedTotal = 0;
private executedTotal = 0;
private static readonly MAX_COUNTER = Number.MAX_SAFE_INTEGER;
constructor(options?: Partial<RestartGovernorOptions>) {
this.options = { ...DEFAULT_OPTIONS, ...options };
}
onRunning(now = Date.now()): void {
this.lastRunningAt = now;
/** No-op kept for interface compatibility with callers. */
onRunning(_now = Date.now()): void {
// Previously used to track "stable running" for exponential back-off
// reset. No longer needed with the simplified cooldown model.
}
decide(now = Date.now()): RestartDecision {
this.pruneOld(now);
this.maybeResetConsecutive(now);
if (now < this.circuitOpenUntil) {
this.suppressedTotal = this.incrementCounter(this.suppressedTotal);
return {
allow: false,
reason: 'circuit_open',
retryAfterMs: this.circuitOpenUntil - now,
};
}
if (this.restartTimestamps.length >= this.options.maxRestartsPerWindow) {
this.circuitOpenUntil = now + this.options.circuitOpenMs;
this.suppressedTotal = this.incrementCounter(this.suppressedTotal);
return {
allow: false,
reason: 'budget_exceeded',
retryAfterMs: this.options.circuitOpenMs,
};
}
const requiredCooldown = this.getCooldownMs();
if (this.lastRestartAt > 0) {
const sinceLast = now - this.lastRestartAt;
if (sinceLast < requiredCooldown) {
this.suppressedTotal = this.incrementCounter(this.suppressedTotal);
if (sinceLast < this.options.cooldownMs) {
this.suppressedTotal = this.safeIncrement(this.suppressedTotal);
return {
allow: false,
reason: 'cooldown_active',
retryAfterMs: requiredCooldown - sinceLast,
retryAfterMs: this.options.cooldownMs - sinceLast,
};
}
}
@@ -83,11 +64,8 @@ export class GatewayRestartGovernor {
}
recordExecuted(now = Date.now()): void {
this.executedTotal = this.incrementCounter(this.executedTotal);
this.executedTotal = this.safeIncrement(this.executedTotal);
this.lastRestartAt = now;
this.consecutiveRestarts += 1;
this.restartTimestamps.push(now);
this.pruneOld(now);
}
getCounters(): { executedTotal: number; suppressedTotal: number } {
@@ -105,41 +83,12 @@ export class GatewayRestartGovernor {
return {
suppressed_total: this.suppressedTotal,
executed_total: this.executedTotal,
circuit_open_until: this.circuitOpenUntil,
circuit_open_until: 0, // Always 0 — no circuit breaker
};
}
private getCooldownMs(): number {
const factor = Math.pow(2, Math.max(0, this.consecutiveRestarts));
return Math.min(this.options.baseCooldownMs * factor, this.options.maxCooldownMs);
}
private maybeResetConsecutive(now: number): void {
if (this.lastRunningAt <= 0) return;
if (now - this.lastRunningAt >= this.options.stableResetMs) {
this.consecutiveRestarts = 0;
}
}
private pruneOld(now: number): void {
// Detect time rewind (system clock moved backwards) and clear all
// time-based guard state to avoid stale lockouts.
if (this.restartTimestamps.length > 0 && now < this.restartTimestamps[this.restartTimestamps.length - 1]) {
this.restartTimestamps = [];
this.circuitOpenUntil = 0;
this.lastRestartAt = 0;
this.lastRunningAt = 0;
this.consecutiveRestarts = 0;
return;
}
const threshold = now - this.options.windowMs;
while (this.restartTimestamps.length > 0 && this.restartTimestamps[0] < threshold) {
this.restartTimestamps.shift();
}
}
private incrementCounter(current: number): number {
if (current >= GatewayRestartGovernor.MAX_COUNTER) return 0;
private safeIncrement(current: number): number {
if (current >= Number.MAX_SAFE_INTEGER) return 0;
return current + 1;
}
}

View File

@@ -9,13 +9,13 @@ export interface ExistingGatewayInfo {
type StartupHooks = {
port: number;
ownedPid?: number;
ownedPid?: never; // Removed: pid is now read dynamically in findExistingGateway to avoid stale-snapshot bug
shouldWaitForPortFree: boolean;
maxStartAttempts?: number;
resetStartupStderrLines: () => void;
getStartupStderrLines: () => string[];
assertLifecycle: (phase: string) => void;
findExistingGateway: (port: number, ownedPid?: number) => Promise<ExistingGatewayInfo | null>;
findExistingGateway: (port: number) => Promise<ExistingGatewayInfo | null>;
connect: (port: number, externalToken?: string) => Promise<void>;
onConnectedToExistingGateway: () => void;
waitForPortFree: (port: number) => Promise<void>;
@@ -39,7 +39,7 @@ export async function runGatewayStartupSequence(hooks: StartupHooks): Promise<vo
try {
logger.debug('Checking for existing Gateway...');
const existing = await hooks.findExistingGateway(hooks.port, hooks.ownedPid);
const existing = await hooks.findExistingGateway(hooks.port);
hooks.assertLifecycle('start/find-existing');
if (existing) {
logger.debug(`Found existing Gateway on port ${existing.port}`);

View File

@@ -18,6 +18,8 @@ const TRANSIENT_START_ERROR_PATTERNS: RegExp[] = [
/Gateway process exited before becoming ready/i,
/Timed out waiting for connect\.challenge/i,
/Connect handshake timeout/i,
// Port occupied after orphan kill: transient, worth retrying with backoff
/Port \d+ still occupied after \d+ms/i,
];
function normalizeLogLine(value: string): string {

View File

@@ -156,7 +156,8 @@ export async function waitForPortFree(port: number, timeoutMs = 30000): Promise<
await new Promise((resolve) => setTimeout(resolve, pollInterval));
}
logger.warn(`Port ${port} still occupied after ${timeoutMs}ms, proceeding anyway`);
logger.error(`Port ${port} still occupied after ${timeoutMs}ms; aborting startup to avoid port conflict`);
throw new Error(`Port ${port} still occupied after ${timeoutMs}ms`);
}
async function getListeningProcessIds(port: number): Promise<string[]> {
@@ -256,15 +257,18 @@ export async function findExistingGatewayProcess(options: {
return await new Promise<{ port: number; externalToken?: string } | null>((resolve) => {
const testWs = new WebSocket(`ws://localhost:${port}/ws`);
const terminateAndResolve = (result: { port: number; externalToken?: string } | null) => {
// terminate() avoids TIME_WAIT on Windows (vs close() which does WS handshake)
try { testWs.terminate(); } catch { /* ignore */ }
resolve(result);
};
const timeout = setTimeout(() => {
testWs.close();
resolve(null);
terminateAndResolve(null);
}, 2000);
testWs.on('open', () => {
clearTimeout(timeout);
testWs.close();
resolve({ port });
terminateAndResolve({ port });
});
testWs.on('error', () => {

View File

@@ -24,7 +24,10 @@ export async function probeGatewayReady(
settled = true;
clearTimeout(timeout);
try {
testWs.close();
// Use terminate() (TCP RST) instead of close() (WS close handshake)
// to avoid leaving TIME_WAIT connections on Windows. These probe
// WebSockets are short-lived and don't need a graceful close.
testWs.terminate();
} catch {
// ignore
}
@@ -171,7 +174,7 @@ export async function connectGatewaySocket(options: {
getToken: () => Promise<string>;
onHandshakeComplete: (ws: WebSocket) => void;
onMessage: (message: unknown) => void;
onCloseAfterHandshake: () => void;
onCloseAfterHandshake: (code: number) => void;
challengeTimeoutMs?: number;
connectTimeoutMs?: number;
}): Promise<WebSocket> {
@@ -308,7 +311,7 @@ export async function connectGatewaySocket(options: {
return;
}
cleanupHandshakeRequest();
options.onCloseAfterHandshake();
options.onCloseAfterHandshake(code);
});
ws.on('error', (error) => {

View File

@@ -421,13 +421,6 @@ async function buildAgentModelProviderEntry(
authHeader = true;
apiKey = 'minimax-oauth';
}
} else if (config.type === 'qwen-portal') {
const accountApiKey = await getApiKey(config.id);
if (accountApiKey) {
apiKey = accountApiKey;
} else {
apiKey = 'qwen-oauth';
}
}
return {
@@ -591,7 +584,7 @@ export async function syncDefaultProviderToRuntime(
const ock = await resolveRuntimeProviderKey(provider);
const providerKey = await getApiKey(providerId);
const fallbackModels = await getProviderFallbackModelRefs(provider);
const oauthTypes = ['qwen-portal', 'minimax-portal', 'minimax-portal-cn'];
const oauthTypes = ['minimax-portal', 'minimax-portal-cn'];
const browserOAuthRuntimeProvider = await getBrowserOAuthRuntimeProvider(provider);
const isOAuthProvider = (oauthTypes.includes(provider.type) && !providerKey) || Boolean(browserOAuthRuntimeProvider);
@@ -662,20 +655,15 @@ export async function syncDefaultProviderToRuntime(
const defaultBaseUrl = provider.type === 'minimax-portal'
? 'https://api.minimax.io/anthropic'
: (provider.type === 'minimax-portal-cn' ? 'https://api.minimaxi.com/anthropic' : 'https://portal.qwen.ai/v1');
const api: 'anthropic-messages' | 'openai-completions' =
(provider.type === 'minimax-portal' || provider.type === 'minimax-portal-cn')
? 'anthropic-messages'
: 'openai-completions';
: 'https://api.minimaxi.com/anthropic';
const api = 'anthropic-messages' as const;
let baseUrl = provider.baseUrl || defaultBaseUrl;
if ((provider.type === 'minimax-portal' || provider.type === 'minimax-portal-cn') && baseUrl) {
if (baseUrl) {
baseUrl = baseUrl.replace(/\/v1$/, '').replace(/\/anthropic$/, '').replace(/\/$/, '') + '/anthropic';
}
const targetProviderKey = (provider.type === 'minimax-portal' || provider.type === 'minimax-portal-cn')
? 'minimax-portal'
: provider.type;
const targetProviderKey = 'minimax-portal';
await setOpenClawDefaultModelWithOverride(targetProviderKey, getProviderModelRef(provider), {
baseUrl,

View File

@@ -2,7 +2,6 @@ import type { ProviderAccount, ProviderConfig, ProviderType } from '../../shared
import { getProviderDefinition } from '../../shared/providers/registry';
import { getClawXProviderStore } from './store-instance';
const PROVIDER_STORE_SCHEMA_VERSION = 1;
function inferAuthMode(type: ProviderType): ProviderAccount['authMode'] {
if (type === 'ollama') {
@@ -75,7 +74,6 @@ export async function saveProviderAccount(account: ProviderAccount): Promise<voi
const accounts = (store.get('providerAccounts') ?? {}) as Record<string, ProviderAccount>;
accounts[account.id] = account;
store.set('providerAccounts', accounts);
store.set('schemaVersion', PROVIDER_STORE_SCHEMA_VERSION);
}
export async function deleteProviderAccount(accountId: string): Promise<void> {

View File

@@ -218,26 +218,27 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [
},
},
{
id: 'qwen-portal',
name: 'Qwen',
id: 'modelstudio',
name: 'Model Studio',
icon: '☁️',
placeholder: 'sk-...',
model: 'Qwen',
requiresApiKey: false,
isOAuth: true,
defaultModelId: 'coder-model',
requiresApiKey: true,
defaultBaseUrl: 'https://coding.dashscope.aliyuncs.com/v1',
showBaseUrl: true,
defaultModelId: 'qwen3.5-plus',
showModelId: true,
showModelIdInDevModeOnly: true,
modelIdPlaceholder: 'coder-model',
modelIdPlaceholder: 'qwen3.5-plus',
category: 'official',
envVar: 'QWEN_API_KEY',
supportedAuthModes: ['oauth_device'],
defaultAuthMode: 'oauth_device',
envVar: 'MODELSTUDIO_API_KEY',
supportedAuthModes: ['api_key'],
defaultAuthMode: 'api_key',
supportsMultipleAccounts: true,
providerConfig: {
baseUrl: 'https://portal.qwen.ai/v1',
baseUrl: 'https://coding.dashscope.aliyuncs.com/v1',
api: 'openai-completions',
apiKeyEnv: 'QWEN_API_KEY',
apiKeyEnv: 'MODELSTUDIO_API_KEY',
},
},
{

View File

@@ -8,7 +8,7 @@ export const PROVIDER_TYPES = [
'siliconflow',
'minimax-portal',
'minimax-portal-cn',
'qwen-portal',
'modelstudio',
'ollama',
'custom',
] as const;
@@ -23,7 +23,7 @@ export const BUILTIN_PROVIDER_TYPES = [
'siliconflow',
'minimax-portal',
'minimax-portal-cn',
'qwen-portal',
'modelstudio',
'ollama',
] as const;

View File

@@ -1,11 +1,10 @@
/**
* Device OAuth Manager
*
* Manages Device Code OAuth flows for MiniMax and Qwen providers.
* Manages Device Code OAuth flows for MiniMax providers.
*
* The OAuth protocol implementations are fully self-contained in:
* - ./minimax-oauth.ts (MiniMax Device Code + PKCE)
* - ./qwen-oauth.ts (Qwen Device Code + PKCE)
*
* This approach:
* - Hardcodes client_id and endpoints (same as openai-codex-oauth.ts)
@@ -24,12 +23,11 @@ import { getProviderDefaultModel } from './provider-registry';
import { proxyAwareFetch } from './proxy-fetch';
import { saveOAuthTokenToOpenClaw, setOpenClawDefaultModelWithOverride } from './openclaw-auth';
import { loginMiniMaxPortalOAuth, type MiniMaxOAuthToken, type MiniMaxRegion } from './minimax-oauth';
import { loginQwenPortalOAuth, type QwenOAuthToken } from './qwen-oauth';
export type OAuthProviderType = 'minimax-portal' | 'minimax-portal-cn' | 'qwen-portal';
export type OAuthProviderType = 'minimax-portal' | 'minimax-portal-cn';
// Re-export types for consumers
export type { MiniMaxRegion, MiniMaxOAuthToken, QwenOAuthToken };
export type { MiniMaxRegion, MiniMaxOAuthToken };
// ─────────────────────────────────────────────────────────────
// DeviceOAuthManager
@@ -76,8 +74,6 @@ class DeviceOAuthManager extends EventEmitter {
if (provider === 'minimax-portal' || provider === 'minimax-portal-cn') {
const actualRegion = provider === 'minimax-portal-cn' ? 'cn' : (region || 'global');
await this.runMiniMaxFlow(actualRegion, provider);
} else if (provider === 'qwen-portal') {
await this.runQwenFlow();
} else {
throw new Error(`Unsupported OAuth provider type: ${provider}`);
}
@@ -152,47 +148,7 @@ class DeviceOAuthManager extends EventEmitter {
});
}
// ─────────────────────────────────────────────────────────
// Qwen flow
// ─────────────────────────────────────────────────────────
private async runQwenFlow(): Promise<void> {
const provider = this.activeProvider!;
const token: QwenOAuthToken = await this.runWithProxyAwareFetch(() => loginQwenPortalOAuth({
openUrl: async (url: string) => {
logger.info(`[DeviceOAuth] Qwen opening browser: ${url}`);
shell.openExternal(url).catch((err: unknown) =>
logger.warn(`[DeviceOAuth] Failed to open browser:`, err)
);
},
note: async (message: string, _title?: string) => {
if (!this.active) return;
const { verificationUri, userCode } = this.parseNote(message);
if (verificationUri && userCode) {
this.emitCode({ provider, verificationUri, userCode, expiresIn: 300 });
} else {
logger.info(`[DeviceOAuth] Qwen note: ${message}`);
}
},
progress: {
update: (msg: string) => logger.info(`[DeviceOAuth] Qwen progress: ${msg}`),
stop: (msg?: string) => logger.info(`[DeviceOAuth] Qwen progress done: ${msg ?? ''}`),
},
}));
if (!this.active) return;
await this.onSuccess('qwen-portal', {
access: token.access,
refresh: token.refresh,
expires: token.expires,
// Qwen returns a per-account resourceUrl as the API base URL
resourceUrl: token.resourceUrl,
// Qwen uses OpenAI Completions API format
api: 'openai-completions',
});
}
// ─────────────────────────────────────────────────────────
// Success handler
@@ -235,7 +191,7 @@ class DeviceOAuthManager extends EventEmitter {
// or falls back to the provider's default public endpoint.
const defaultBaseUrl = providerType === 'minimax-portal'
? 'https://api.minimax.io/anthropic'
: (providerType === 'minimax-portal-cn' ? 'https://api.minimaxi.com/anthropic' : 'https://portal.qwen.ai/v1');
: 'https://api.minimaxi.com/anthropic';
let baseUrl = token.resourceUrl || defaultBaseUrl;
@@ -247,11 +203,6 @@ class DeviceOAuthManager extends EventEmitter {
// Ensure the base URL ends with /anthropic
if (providerType.startsWith('minimax-portal') && baseUrl) {
baseUrl = baseUrl.replace(/\/v1$/, '').replace(/\/anthropic$/, '').replace(/\/$/, '') + '/anthropic';
} else if (providerType === 'qwen-portal' && baseUrl) {
// Ensure Qwen API gets /v1 at the end
if (!baseUrl.endsWith('/v1')) {
baseUrl = baseUrl.replace(/\/$/, '') + '/v1';
}
}
try {
@@ -263,7 +214,7 @@ class DeviceOAuthManager extends EventEmitter {
authHeader: providerType.startsWith('minimax-portal') ? true : undefined,
// OAuth placeholder — tells Gateway to resolve credentials
// from auth-profiles.json (type: 'oauth') instead of a static API key.
apiKeyEnv: tokenProviderId === 'minimax-portal' ? 'minimax-oauth' : 'qwen-oauth',
apiKeyEnv: 'minimax-oauth',
});
} catch (err) {
logger.warn(`[DeviceOAuth] Failed to configure openclaw models:`, err);
@@ -274,7 +225,6 @@ class DeviceOAuthManager extends EventEmitter {
const nameMap: Record<OAuthProviderType, string> = {
'minimax-portal': 'MiniMax (Global)',
'minimax-portal-cn': 'MiniMax (CN)',
'qwen-portal': 'Qwen',
};
const providerConfig: ProviderConfig = {
id: accountId,

View File

@@ -473,7 +473,7 @@ export async function removeProviderFromOpenClaw(provider: string): Promise<void
const config = await readOpenClawJson();
let modified = false;
// Disable plugin (for OAuth like qwen-portal-auth)
// Disable plugin (for OAuth like minimax-portal-auth)
const plugins = config.plugins as Record<string, unknown> | undefined;
const entries = (plugins?.entries ?? {}) as Record<string, Record<string, unknown>>;
const pluginName = `${provider}-auth`;
@@ -872,6 +872,10 @@ export async function setOpenClawDefaultModelWithOverride(
* Get a set of all active provider IDs configured in openclaw.json.
* Reads the file ONCE and extracts both models.providers and plugins.entries.
*/
// Provider IDs that have been deprecated and should never appear as active.
// These may still linger in openclaw.json from older versions.
const DEPRECATED_PROVIDER_IDS = new Set(['qwen-portal']);
export async function getActiveOpenClawProviders(): Promise<Set<string>> {
const activeProviders = new Set<string>();
@@ -897,7 +901,7 @@ export async function getActiveOpenClawProviders(): Promise<Set<string>> {
}
// 3. agents.defaults.model.primary — the default model reference encodes
// the provider prefix (e.g. "qwen-portal/coder-model" → "qwen-portal").
// the provider prefix (e.g. "modelstudio/qwen3.5-plus" → "modelstudio").
// This covers providers that are active via OAuth or env-key but don't
// have an explicit models.providers entry.
const agents = config.agents as Record<string, unknown> | undefined;
@@ -921,6 +925,11 @@ export async function getActiveOpenClawProviders(): Promise<Set<string>> {
console.warn('Failed to read openclaw.json for active providers:', err);
}
// Remove deprecated providers that may still linger in config/auth files.
for (const deprecated of DEPRECATED_PROVIDER_IDS) {
activeProviders.delete(deprecated);
}
return activeProviders;
}
@@ -1350,10 +1359,24 @@ export async function sanitizeOpenClawConfig(): Promise<void> {
toolsModified = true;
}
// ── tools.exec approvals (OpenClaw 3.28+) ──────────────────────
// ClawX is a local desktop app where the user is the trusted operator.
// Exec approval prompts add unnecessary friction in this context, so we
// set security="full" (allow all commands) and ask="off" (never prompt).
// If a user has manually configured a stricter ~/.openclaw/exec-approvals.json,
// OpenClaw's minSecurity/maxAsk merge will still respect their intent.
const execConfig = (toolsConfig.exec as Record<string, unknown> | undefined) || {};
if (execConfig.security !== 'full' || execConfig.ask !== 'off') {
execConfig.security = 'full';
execConfig.ask = 'off';
toolsConfig.exec = execConfig;
toolsModified = true;
console.log('[sanitize] Set tools.exec.security="full" and tools.exec.ask="off" to disable exec approvals for ClawX desktop');
}
if (toolsModified) {
config.tools = toolsConfig;
modified = true;
console.log('[sanitize] Enforced tools.profile="full" and tools.sessions.visibility="all" for OpenClaw 3.8+');
}
// ── plugins.entries.feishu cleanup ──────────────────────────────
@@ -1465,6 +1488,44 @@ export async function sanitizeOpenClawConfig(): Promise<void> {
modified = true;
}
// ── qwen-portal → modelstudio migration ────────────────────
// OpenClaw 2026.3.28 deprecated qwen-portal OAuth (portal.qwen.ai)
// in favor of Model Studio (DashScope API key). Clean up legacy
// qwen-portal-auth plugin entries and qwen-portal provider config.
const LEGACY_QWEN_PLUGIN_ID = 'qwen-portal-auth';
if (Array.isArray(pluginsObj.allow)) {
const allowArr = pluginsObj.allow as string[];
const legacyIdx = allowArr.indexOf(LEGACY_QWEN_PLUGIN_ID);
if (legacyIdx !== -1) {
allowArr.splice(legacyIdx, 1);
console.log(`[sanitize] Removed deprecated plugin from plugins.allow: ${LEGACY_QWEN_PLUGIN_ID}`);
modified = true;
}
}
if (pEntries?.[LEGACY_QWEN_PLUGIN_ID]) {
delete pEntries[LEGACY_QWEN_PLUGIN_ID];
console.log(`[sanitize] Removed deprecated plugin from plugins.entries: ${LEGACY_QWEN_PLUGIN_ID}`);
modified = true;
}
// Remove deprecated models.providers.qwen-portal
const LEGACY_QWEN_PROVIDER = 'qwen-portal';
if (providers[LEGACY_QWEN_PROVIDER]) {
delete providers[LEGACY_QWEN_PROVIDER];
console.log(`[sanitize] Removed deprecated provider: ${LEGACY_QWEN_PROVIDER}`);
modified = true;
}
// Clean up qwen-portal OAuth auth profile (no longer functional)
const authConfig = config.auth as Record<string, unknown> | undefined;
const authProfiles = authConfig?.profiles as Record<string, unknown> | undefined;
if (authProfiles?.[LEGACY_QWEN_PROVIDER]) {
delete authProfiles[LEGACY_QWEN_PROVIDER];
console.log(`[sanitize] Removed deprecated auth profile: ${LEGACY_QWEN_PROVIDER}`);
modified = true;
}
// ── Remove bare 'feishu' when canonical feishu plugin is present ──
// The Gateway binary automatically adds bare 'feishu' to plugins.allow
// because the official plugin registers the 'feishu' channel.

View File

@@ -1,12 +1,10 @@
const MULTI_INSTANCE_PROVIDER_TYPES = new Set(['custom', 'ollama']);
export const OPENCLAW_PROVIDER_KEY_MINIMAX = 'minimax-portal';
export const OPENCLAW_PROVIDER_KEY_QWEN = 'qwen-portal';
export const OPENCLAW_PROVIDER_KEY_MOONSHOT = 'moonshot';
export const OAUTH_PROVIDER_TYPES = ['qwen-portal', 'minimax-portal', 'minimax-portal-cn'] as const;
export const OAUTH_PROVIDER_TYPES = ['minimax-portal', 'minimax-portal-cn'] as const;
export const OPENCLAW_OAUTH_PLUGIN_PROVIDER_KEYS = [
OPENCLAW_PROVIDER_KEY_MINIMAX,
OPENCLAW_PROVIDER_KEY_QWEN,
] as const;
const OAUTH_PROVIDER_TYPE_SET = new Set<string>(OAUTH_PROVIDER_TYPES);
@@ -54,27 +52,24 @@ export function isMiniMaxProviderType(type: string): boolean {
export function getOAuthProviderTargetKey(type: string): string | undefined {
if (!isOAuthProviderType(type)) return undefined;
return isMiniMaxProviderType(type) ? OPENCLAW_PROVIDER_KEY_MINIMAX : OPENCLAW_PROVIDER_KEY_QWEN;
return OPENCLAW_PROVIDER_KEY_MINIMAX;
}
export function getOAuthProviderApi(type: string): 'anthropic-messages' | 'openai-completions' | undefined {
export function getOAuthProviderApi(type: string): 'anthropic-messages' | undefined {
if (!isOAuthProviderType(type)) return undefined;
return isMiniMaxProviderType(type) ? 'anthropic-messages' : 'openai-completions';
return 'anthropic-messages';
}
export function getOAuthProviderDefaultBaseUrl(type: string): string | undefined {
if (!isOAuthProviderType(type)) return undefined;
if (type === OPENCLAW_PROVIDER_KEY_MINIMAX) return 'https://api.minimax.io/anthropic';
if (type === 'minimax-portal-cn') return 'https://api.minimaxi.com/anthropic';
return 'https://portal.qwen.ai/v1';
return undefined;
}
export function normalizeOAuthBaseUrl(type: string, baseUrl?: string): string | undefined {
export function normalizeOAuthBaseUrl(_type: string, baseUrl?: string): string | undefined {
if (!baseUrl) return undefined;
if (isMiniMaxProviderType(type)) {
return baseUrl.replace(/\/v1$/, '').replace(/\/anthropic$/, '').replace(/\/$/, '') + '/anthropic';
}
return baseUrl;
return baseUrl.replace(/\/v1$/, '').replace(/\/anthropic$/, '').replace(/\/$/, '') + '/anthropic';
}
export function usesOAuthAuthHeader(providerKey: string): boolean {
@@ -83,7 +78,6 @@ export function usesOAuthAuthHeader(providerKey: string): boolean {
export function getOAuthApiKeyEnv(providerKey: string): string | undefined {
if (providerKey === OPENCLAW_PROVIDER_KEY_MINIMAX) return 'minimax-oauth';
if (providerKey === OPENCLAW_PROVIDER_KEY_QWEN) return 'qwen-oauth';
return undefined;
}

View File

@@ -1,211 +0,0 @@
/**
* Self-contained Qwen Device Code OAuth flow.
*
* Implements RFC 8628 (Device Authorization Grant) with PKCE for Qwen API.
* Zero dependency on openclaw extension modules — survives openclaw upgrades.
*
* Protocol:
* 1. POST /api/v1/oauth2/device/code → get device_code, user_code, verification_uri
* 2. Open verification_uri in browser
* 3. Poll POST /api/v1/oauth2/token with device_code until approved
* 4. Return { access, refresh, expires, resourceUrl }
*/
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { proxyAwareFetch } from './proxy-fetch';
// ── Constants ────────────────────────────────────────────────
const QWEN_OAUTH_BASE_URL = 'https://chat.qwen.ai';
const QWEN_OAUTH_DEVICE_CODE_ENDPOINT = `${QWEN_OAUTH_BASE_URL}/api/v1/oauth2/device/code`;
const QWEN_OAUTH_TOKEN_ENDPOINT = `${QWEN_OAUTH_BASE_URL}/api/v1/oauth2/token`;
const QWEN_OAUTH_CLIENT_ID = 'f0304373b74a44d2b584a3fb70ca9e56';
const QWEN_OAUTH_SCOPE = 'openid profile email model.completion';
const QWEN_OAUTH_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
// ── Types ────────────────────────────────────────────────────
export interface QwenOAuthToken {
access: string;
refresh: string;
expires: number;
resourceUrl?: string;
}
interface QwenDeviceAuthorization {
device_code: string;
user_code: string;
verification_uri: string;
verification_uri_complete?: string;
expires_in: number;
interval?: number;
}
type DeviceTokenResult =
| { status: 'success'; token: QwenOAuthToken }
| { status: 'pending'; slowDown?: boolean }
| { status: 'error'; message: string };
export interface QwenOAuthOptions {
openUrl: (url: string) => Promise<void>;
note: (message: string, title?: string) => Promise<void>;
progress: { update: (message: string) => void; stop: (message?: string) => void };
}
// ── PKCE helpers (self-contained, no openclaw dependency) ────
function generatePkce(): { verifier: string; challenge: string } {
const verifier = randomBytes(32).toString('base64url');
const challenge = createHash('sha256').update(verifier).digest('base64url');
return { verifier, challenge };
}
function toFormUrlEncoded(params: Record<string, string>): string {
return new URLSearchParams(params).toString();
}
// ── OAuth flow steps ─────────────────────────────────────────
async function requestDeviceCode(params: { challenge: string }): Promise<QwenDeviceAuthorization> {
const response = await proxyAwareFetch(QWEN_OAUTH_DEVICE_CODE_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
'x-request-id': randomUUID(),
},
body: toFormUrlEncoded({
client_id: QWEN_OAUTH_CLIENT_ID,
scope: QWEN_OAUTH_SCOPE,
code_challenge: params.challenge,
code_challenge_method: 'S256',
}),
});
if (!response.ok) {
const text = await response.text();
throw new Error(`Qwen device authorization failed: ${text || response.statusText}`);
}
const payload = (await response.json()) as QwenDeviceAuthorization & { error?: string };
if (!payload.device_code || !payload.user_code || !payload.verification_uri) {
throw new Error(
payload.error ??
'Qwen device authorization returned an incomplete payload (missing user_code or verification_uri).',
);
}
return payload;
}
async function pollDeviceToken(params: {
deviceCode: string;
verifier: string;
}): Promise<DeviceTokenResult> {
const response = await proxyAwareFetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
body: toFormUrlEncoded({
grant_type: QWEN_OAUTH_GRANT_TYPE,
client_id: QWEN_OAUTH_CLIENT_ID,
device_code: params.deviceCode,
code_verifier: params.verifier,
}),
});
if (!response.ok) {
let payload: { error?: string; error_description?: string } | undefined;
try {
payload = (await response.json()) as { error?: string; error_description?: string };
} catch {
const text = await response.text();
return { status: 'error', message: text || response.statusText };
}
if (payload?.error === 'authorization_pending') {
return { status: 'pending' };
}
if (payload?.error === 'slow_down') {
return { status: 'pending', slowDown: true };
}
return {
status: 'error',
message: payload?.error_description || payload?.error || response.statusText,
};
}
const tokenPayload = (await response.json()) as {
access_token?: string | null;
refresh_token?: string | null;
expires_in?: number | null;
token_type?: string;
resource_url?: string;
};
if (!tokenPayload.access_token || !tokenPayload.refresh_token || !tokenPayload.expires_in) {
return { status: 'error', message: 'Qwen OAuth returned incomplete token payload.' };
}
return {
status: 'success',
token: {
access: tokenPayload.access_token,
refresh: tokenPayload.refresh_token,
expires: Date.now() + tokenPayload.expires_in * 1000,
resourceUrl: tokenPayload.resource_url,
},
};
}
// ── Public API ───────────────────────────────────────────────
export async function loginQwenPortalOAuth(params: QwenOAuthOptions): Promise<QwenOAuthToken> {
const { verifier, challenge } = generatePkce();
const device = await requestDeviceCode({ challenge });
const verificationUrl = device.verification_uri_complete || device.verification_uri;
await params.note(
[
`Open ${verificationUrl} to approve access.`,
`If prompted, enter the code ${device.user_code}.`,
].join('\n'),
'Qwen OAuth',
);
try {
await params.openUrl(verificationUrl);
} catch {
// Fall back to manual copy/paste if browser open fails.
}
const start = Date.now();
let pollIntervalMs = device.interval ? device.interval * 1000 : 2000;
const timeoutMs = device.expires_in * 1000;
while (Date.now() - start < timeoutMs) {
params.progress.update('Waiting for Qwen OAuth approval…');
const result = await pollDeviceToken({
deviceCode: device.device_code,
verifier,
});
if (result.status === 'success') {
return result.token;
}
if (result.status === 'error') {
throw new Error(`Qwen OAuth failed: ${result.message}`);
}
if (result.status === 'pending' && result.slowDown) {
pollIntervalMs = Math.min(pollIntervalMs * 1.5, 10000);
}
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
}
throw new Error('Qwen OAuth timed out waiting for authorization.');
}

View File

@@ -79,7 +79,7 @@
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@larksuite/openclaw-lark": "2026.3.29",
"@larksuite/openclaw-lark": "2026.3.30",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8",
@@ -94,7 +94,7 @@
"@radix-ui/react-tooltip": "^1.2.8",
"@playwright/test": "^1.56.1",
"@soimy/dingtalk": "^3.5.1",
"@tencent-connect/openclaw-qqbot": "^1.6.6",
"@tencent-connect/openclaw-qqbot": "^1.6.7",
"@tencent-weixin/openclaw-weixin": "^2.1.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
@@ -105,7 +105,7 @@
"@typescript-eslint/eslint-plugin": "^8.56.0",
"@typescript-eslint/parser": "^8.56.0",
"@vitejs/plugin-react": "^5.1.4",
"@wecom/wecom-openclaw-plugin": "^2026.3.26",
"@wecom/wecom-openclaw-plugin": "^2026.3.30",
"@whiskeysockets/baileys": "7.0.0-rc.9",
"autoprefixer": "^10.4.24",
"class-variance-authority": "^0.7.1",
@@ -120,7 +120,7 @@
"i18next": "^25.8.11",
"jsdom": "^28.1.0",
"lucide-react": "^0.563.0",
"openclaw": "2026.3.24",
"openclaw": "2026.3.28",
"png2icons": "^2.0.1",
"postcss": "^8.5.6",
"react": "^19.2.4",

731
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -20,7 +20,7 @@ export const providerIcons: Record<string, string> = {
siliconflow,
'minimax-portal': minimaxPortal,
'minimax-portal-cn': minimaxPortal,
'qwen-portal': qwenPortal,
'modelstudio': qwenPortal,
ollama,
custom,
};

View File

@@ -1134,6 +1134,9 @@ function AddProviderDialog({
};
const availableTypes = PROVIDER_TYPE_INFO.filter((type) => {
// Skip providers that are temporarily hidden from the UI.
if (type.hidden) return false;
// MiniMax portal variants are mutually exclusive — hide BOTH variants
// when either one already exists (account may have vendorId of either variant).
const hasMinimax = existingVendorIds.has('minimax-portal') || existingVendorIds.has('minimax-portal-cn');

View File

@@ -16,7 +16,7 @@ export const PROVIDER_TYPES = [
'siliconflow',
'minimax-portal',
'minimax-portal-cn',
'qwen-portal',
'modelstudio',
'ollama',
'custom',
] as const;
@@ -32,7 +32,7 @@ export const BUILTIN_PROVIDER_TYPES = [
'siliconflow',
'minimax-portal',
'minimax-portal-cn',
'qwen-portal',
'modelstudio',
'ollama',
] as const;
@@ -79,6 +79,8 @@ export interface ProviderTypeInfo {
codePlanPresetBaseUrl?: string;
codePlanPresetModelId?: string;
codePlanDocsUrl?: string;
/** If true, this provider is not shown in the "Add Provider" dialog. */
hidden?: boolean;
}
export type ProviderAuthMode =
@@ -172,7 +174,7 @@ export const PROVIDER_TYPE_INFO: ProviderTypeInfo[] = [
{ id: 'moonshot', name: 'Moonshot (CN)', icon: '🌙', placeholder: 'sk-...', model: 'Kimi', requiresApiKey: true, defaultBaseUrl: 'https://api.moonshot.cn/v1', defaultModelId: 'kimi-k2.5', docsUrl: 'https://platform.moonshot.cn/' },
{ id: 'siliconflow', name: 'SiliconFlow (CN)', icon: '🌊', placeholder: 'sk-...', model: 'Multi-Model', requiresApiKey: true, defaultBaseUrl: 'https://api.siliconflow.cn/v1', showModelId: true, showModelIdInDevModeOnly: true, modelIdPlaceholder: 'deepseek-ai/DeepSeek-V3', defaultModelId: 'deepseek-ai/DeepSeek-V3', docsUrl: 'https://docs.siliconflow.cn/cn/userguide/introduction' },
{ id: 'minimax-portal', name: 'MiniMax (Global)', icon: '☁️', placeholder: 'sk-...', model: 'MiniMax', requiresApiKey: false, isOAuth: true, supportsApiKey: true, defaultModelId: 'MiniMax-M2.7', showModelId: true, showModelIdInDevModeOnly: true, modelIdPlaceholder: 'MiniMax-M2.7', apiKeyUrl: 'https://platform.minimax.io' },
{ id: 'qwen-portal', name: 'Qwen (Global)', icon: '☁️', placeholder: 'sk-...', model: 'Qwen', requiresApiKey: false, isOAuth: true, defaultModelId: 'coder-model', showModelId: true, showModelIdInDevModeOnly: true, modelIdPlaceholder: 'coder-model' },
{ id: 'modelstudio', name: 'Model Studio', icon: '☁️', placeholder: 'sk-...', model: 'Qwen', requiresApiKey: true, defaultBaseUrl: 'https://coding.dashscope.aliyuncs.com/v1', showBaseUrl: true, defaultModelId: 'qwen3.5-plus', showModelId: true, showModelIdInDevModeOnly: true, modelIdPlaceholder: 'qwen3.5-plus', apiKeyUrl: 'https://bailian.console.aliyun.com/', hidden: true },
{ id: 'ark', name: 'ByteDance Ark', icon: 'A', placeholder: 'your-ark-api-key', model: 'Doubao', requiresApiKey: true, defaultBaseUrl: 'https://ark.cn-beijing.volces.com/api/v3', showBaseUrl: true, showModelId: true, modelIdPlaceholder: 'ep-20260228000000-xxxxx', docsUrl: 'https://www.volcengine.com/', codePlanPresetBaseUrl: 'https://ark.cn-beijing.volces.com/api/coding/v3', codePlanPresetModelId: 'ark-code-latest', codePlanDocsUrl: 'https://www.volcengine.com/docs/82379/1928261?lang=zh' },
{ id: 'ollama', name: 'Ollama', icon: '🦙', placeholder: 'Not required', requiresApiKey: false, defaultBaseUrl: 'http://localhost:11434/v1', showBaseUrl: true, showModelId: true, modelIdPlaceholder: 'qwen3:latest' },
{

View File

@@ -10,6 +10,7 @@ import type { GatewayStatus } from '../types/gateway';
let gatewayInitPromise: Promise<void> | null = null;
let gatewayEventUnsubscribers: Array<() => void> | null = null;
let gatewayReconcileTimer: ReturnType<typeof setInterval> | null = null;
const gatewayEventDedupe = new Map<string, number>();
const GATEWAY_EVENT_DEDUPE_TTL_MS = 30_000;
const LOAD_SESSIONS_MIN_INTERVAL_MS = 1_200;
@@ -283,6 +284,45 @@ export const useGatewayStore = create<GatewayState>((set, get) => ({
},
));
gatewayEventUnsubscribers = unsubscribers;
// Periodic reconciliation safety net: every 30 seconds, check if the
// renderer's view of gateway state has drifted from main process truth.
// This catches any future one-off IPC delivery failures without adding
// a constant polling load (single lightweight IPC invoke per interval).
// Clear any previous timer first to avoid leaks during HMR reloads.
if (gatewayReconcileTimer !== null) {
clearInterval(gatewayReconcileTimer);
}
gatewayReconcileTimer = setInterval(() => {
const ipc = window.electron?.ipcRenderer;
if (!ipc) return;
ipc.invoke('gateway:status')
.then((result: unknown) => {
const latest = result as GatewayStatus;
const current = get().status;
if (latest.state !== current.state) {
console.info(
`[gateway-store] reconciled stale state: ${current.state}${latest.state}`,
);
set({ status: latest });
}
})
.catch(() => { /* ignore */ });
}, 30_000);
}
// Re-fetch status after IPC listeners are registered to close the race
// window: if the gateway transitioned (e.g. starting → running) between
// the initial fetch and the IPC listener setup, that event was lost.
// A second fetch guarantees we pick up the latest state.
try {
const refreshed = await hostApiFetch<GatewayStatus>('/api/gateway/status');
const current = get().status;
if (refreshed.state !== current.state) {
set({ status: refreshed });
}
} catch {
// Best-effort; the IPC listener will eventually reconcile.
}
} catch (error) {
console.error('Failed to initialize Gateway:', error);

View File

@@ -2,15 +2,13 @@ import { describe, expect, it } from 'vitest';
import { GatewayRestartGovernor } from '@electron/gateway/restart-governor';
describe('GatewayRestartGovernor', () => {
it('suppresses restart during exponential cooldown window', () => {
const governor = new GatewayRestartGovernor({
baseCooldownMs: 1000,
maxCooldownMs: 8000,
maxRestartsPerWindow: 10,
windowMs: 60000,
stableResetMs: 60000,
circuitOpenMs: 60000,
});
it('allows first restart unconditionally', () => {
const governor = new GatewayRestartGovernor();
expect(governor.decide(1000).allow).toBe(true);
});
it('suppresses restart during cooldown window', () => {
const governor = new GatewayRestartGovernor({ cooldownMs: 1000 });
expect(governor.decide(1000).allow).toBe(true);
governor.recordExecuted(1000);
@@ -18,76 +16,26 @@ describe('GatewayRestartGovernor', () => {
const blocked = governor.decide(1500);
expect(blocked.allow).toBe(false);
expect(blocked.allow ? '' : blocked.reason).toBe('cooldown_active');
expect(blocked.allow ? 0 : blocked.retryAfterMs).toBeGreaterThan(0);
expect(blocked.allow ? 0 : blocked.retryAfterMs).toBe(500);
expect(governor.decide(3000).allow).toBe(true);
// After cooldown expires, restart is allowed again
expect(governor.decide(2001).allow).toBe(true);
});
it('opens circuit after restart budget is exceeded', () => {
const governor = new GatewayRestartGovernor({
maxRestartsPerWindow: 2,
windowMs: 60000,
baseCooldownMs: 0,
maxCooldownMs: 0,
stableResetMs: 120000,
circuitOpenMs: 30000,
});
it('allows unlimited restarts as long as cooldown is respected', () => {
const governor = new GatewayRestartGovernor({ cooldownMs: 100 });
expect(governor.decide(1000).allow).toBe(true);
governor.recordExecuted(1000);
expect(governor.decide(2000).allow).toBe(true);
governor.recordExecuted(2000);
const budgetBlocked = governor.decide(3000);
expect(budgetBlocked.allow).toBe(false);
expect(budgetBlocked.allow ? '' : budgetBlocked.reason).toBe('budget_exceeded');
const circuitBlocked = governor.decide(4000);
expect(circuitBlocked.allow).toBe(false);
expect(circuitBlocked.allow ? '' : circuitBlocked.reason).toBe('circuit_open');
expect(governor.decide(62001).allow).toBe(true);
// 10 restarts in a row, each respecting cooldown — all should be allowed
for (let i = 0; i < 10; i++) {
const t = 1000 + i * 200;
expect(governor.decide(t).allow).toBe(true);
governor.recordExecuted(t);
}
});
it('resets consecutive backoff after stable running period', () => {
const governor = new GatewayRestartGovernor({
baseCooldownMs: 1000,
maxCooldownMs: 8000,
maxRestartsPerWindow: 10,
windowMs: 600000,
stableResetMs: 5000,
circuitOpenMs: 60000,
});
governor.recordExecuted(0);
governor.recordExecuted(1000);
const blockedBeforeStable = governor.decide(2500);
expect(blockedBeforeStable.allow).toBe(false);
expect(blockedBeforeStable.allow ? '' : blockedBeforeStable.reason).toBe('cooldown_active');
governor.onRunning(3000);
const allowedAfterStable = governor.decide(9000);
expect(allowedAfterStable.allow).toBe(true);
});
it('resets time-based state when clock moves backwards', () => {
const governor = new GatewayRestartGovernor({
maxRestartsPerWindow: 2,
windowMs: 60000,
baseCooldownMs: 1000,
maxCooldownMs: 8000,
stableResetMs: 60000,
circuitOpenMs: 30000,
});
governor.recordExecuted(10_000);
governor.recordExecuted(11_000);
const blocked = governor.decide(11_500);
expect(blocked.allow).toBe(false);
// Simulate clock rewind and verify stale guard state does not lock out restarts.
const afterRewind = governor.decide(9_000);
expect(afterRewind.allow).toBe(true);
it('onRunning is a no-op but does not throw', () => {
const governor = new GatewayRestartGovernor();
expect(() => governor.onRunning(1000)).not.toThrow();
});
it('wraps counters safely at MAX_SAFE_INTEGER', () => {
@@ -103,4 +51,12 @@ describe('GatewayRestartGovernor', () => {
suppressedTotal: 0,
});
});
it('getObservability returns circuit_open_until as always 0', () => {
const governor = new GatewayRestartGovernor();
governor.recordExecuted(1000);
const obs = governor.getObservability();
expect(obs.circuit_open_until).toBe(0);
expect(obs.executed_total).toBe(1);
});
});

View File

@@ -61,14 +61,22 @@ describe('provider-model-sync', () => {
});
});
it('returns null for oauth and multi-instance providers', () => {
it('builds modelstudio payload and returns null for multi-instance providers', () => {
expect(
buildNonOAuthAgentProviderUpdate(
providerConfig({ type: 'qwen-portal', id: 'qwen-portal' }),
'qwen-portal',
'qwen-portal/coder-model',
providerConfig({ type: 'modelstudio', id: 'modelstudio' }),
'modelstudio',
'modelstudio/qwen3.5-plus',
),
).toBeNull();
).toEqual({
providerKey: 'modelstudio',
entry: {
baseUrl: 'https://coding.dashscope.aliyuncs.com/v1',
api: 'openai-completions',
apiKey: 'MODELSTUDIO_API_KEY',
models: [{ id: 'qwen3.5-plus', name: 'qwen3.5-plus' }],
},
});
expect(
buildNonOAuthAgentProviderUpdate(

View File

@@ -58,7 +58,7 @@ describe('provider metadata', () => {
it('keeps builtin provider sources in sync', () => {
expect(BUILTIN_PROVIDER_TYPES).toEqual(
expect.arrayContaining(['anthropic', 'openai', 'google', 'openrouter', 'ark', 'moonshot', 'siliconflow', 'minimax-portal', 'minimax-portal-cn', 'qwen-portal', 'ollama'])
expect.arrayContaining(['anthropic', 'openai', 'google', 'openrouter', 'ark', 'moonshot', 'siliconflow', 'minimax-portal', 'minimax-portal-cn', 'modelstudio', 'ollama'])
);
});
@@ -125,13 +125,13 @@ describe('provider metadata', () => {
const google = PROVIDER_TYPE_INFO.find((provider) => provider.id === 'google');
const minimax = PROVIDER_TYPE_INFO.find((provider) => provider.id === 'minimax-portal');
const minimaxCn = PROVIDER_TYPE_INFO.find((provider) => provider.id === 'minimax-portal-cn');
const qwen = PROVIDER_TYPE_INFO.find((provider) => provider.id === 'qwen-portal');
const qwen = PROVIDER_TYPE_INFO.find((provider) => provider.id === 'modelstudio');
expect(openai).toMatchObject({ showModelId: true, showModelIdInDevModeOnly: true, defaultModelId: 'gpt-5.4' });
expect(google).toMatchObject({ showModelId: true, showModelIdInDevModeOnly: true, defaultModelId: 'gemini-3-pro-preview' });
expect(minimax).toMatchObject({ showModelId: true, showModelIdInDevModeOnly: true, defaultModelId: 'MiniMax-M2.7' });
expect(minimaxCn).toMatchObject({ showModelId: true, showModelIdInDevModeOnly: true, defaultModelId: 'MiniMax-M2.7' });
expect(qwen).toMatchObject({ showModelId: true, showModelIdInDevModeOnly: true, defaultModelId: 'coder-model' });
expect(qwen).toMatchObject({ showModelId: true, showModelIdInDevModeOnly: true, defaultModelId: 'qwen3.5-plus' });
expect(shouldShowProviderModelId(openai, false)).toBe(false);
expect(shouldShowProviderModelId(google, false)).toBe(false);
@@ -149,7 +149,7 @@ describe('provider metadata', () => {
expect(resolveProviderModelForSave(google, ' ', true)).toBe('gemini-3-pro-preview');
expect(resolveProviderModelForSave(minimax, ' ', true)).toBe('MiniMax-M2.7');
expect(resolveProviderModelForSave(minimaxCn, ' ', true)).toBe('MiniMax-M2.7');
expect(resolveProviderModelForSave(qwen, ' ', true)).toBe('coder-model');
expect(resolveProviderModelForSave(qwen, ' ', true)).toBe('qwen3.5-plus');
});
it('saves OpenRouter model overrides by default and SiliconFlow only in dev mode', () => {