Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Classify connector refresh failures precisely

wyt3a57ecf0f119
diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.ts
index 4d9cb9c9..656f9986 100644
--- a/src/main/features/connectors/manager.ts
+++ b/src/main/features/connectors/manager.ts
@@ -100,6 +100,16 @@ function _isMissingRequiredScopesError(err: unknown): boolean {
return code === 'missing_required_scopes' || /missing_required_scopes|missing required scopes/i.test(msg);
}
+function _connectorErrorCode(err: unknown): string {
+ const code = (err as { code?: unknown } | null)?.code;
+ return typeof code === 'string' ? code : '';
+}
+
+function _connectorRetryable(err: unknown): boolean | null {
+ const retryable = (err as { retryable?: unknown } | null)?.retryable;
+ return typeof retryable === 'boolean' ? retryable : null;
+}
+
function _isGoogleEntry(entry: CatalogEntry): boolean {
return entry.oauth?.provider_id === 'google';
}
@@ -111,19 +121,35 @@ function _isGitHubEntry(entry: CatalogEntry): boolean {
function _isGoogleAuthFailure(entry: CatalogEntry, err: unknown): boolean {
if (!_isGoogleEntry(entry)) return false;
if (_isMissingRequiredScopesError(err)) return true;
+ const code = _connectorErrorCode(err);
+ if (code === 'connector_reconnect_required') return true;
+ if (code === 'connector_refresh_failed') return false;
const msg = (err as Error | null)?.message || String(err || '');
- return /refresh HTTP\s+4\d\d|refresh_failed|invalid refresh response|access_token expired|no oauth_grant|transport unresolved|connector_unauthorized/i.test(msg);
+ return /refresh HTTP\s+4\d\d|invalid refresh response|access_token expired|no oauth_grant|transport unresolved|connector_unauthorized/i.test(msg);
}
function _isDcrAuthFailure(entry: CatalogEntry, err: unknown): boolean {
if (entry.auth_mode !== 'mcp_dcr') return false;
+ const code = _connectorErrorCode(err);
+ if (code === 'connector_reconnect_required') return true;
+ if (code === 'connector_refresh_failed') return false;
const msg = (err as Error | null)?.message || String(err || '');
- return /DCR refresh HTTP\s+4\d\d|invalid_grant|access_token expired|no oauth_grant|transport unresolved/i.test(msg);
+ return /DCR refresh HTTP\s+4\d\d|invalid_grant|connector_reconnect_required|access_token expired|no oauth_grant|transport unresolved/i.test(msg);
}
function _isTransientConnectorFailure(err: unknown): boolean {
+ const code = _connectorErrorCode(err);
+ const retryable = _connectorRetryable(err);
+ if (code === 'connector_reconnect_required') return false;
+ if (code === 'connector_refresh_failed') return retryable !== false;
+ if (retryable === true) return true;
const msg = (err as Error | null)?.message || String(err || '');
- return /fetch failed|network|timeout|timed out|econnreset|econnrefused|eai_again|enotfound|socket|connection (closed|reset|dropped)|terminated/i.test(msg);
+ if (/fetch failed|network|timeout|timed out|econnreset|econnrefused|eai_again|enotfound|socket|connection (closed|reset|dropped)|terminated/i.test(msg)) {
+ return true;
+ }
+ // Generic bridge refresh failures are not proof that the user's grant is dead;
+ // explicit reconnect signals use connector_reconnect_required / invalid_grant wording.
+ return /\brefresh_failed\b|刷新授权失败|failed to refresh authorization|認証の更新に失敗|Falha ao atualizar a autorização/i.test(msg);
}
function _hasEstablishedConnectorState(inst: ConnectorInstance): boolean {
diff --git a/src/main/features/connectors/oauth-dcr.ts b/src/main/features/connectors/oauth-dcr.ts
index ee1dd73f..abd8d6f7 100644
--- a/src/main/features/connectors/oauth-dcr.ts
+++ b/src/main/features/connectors/oauth-dcr.ts
@@ -75,6 +75,12 @@ interface AuthServerMetadata {
token_endpoint_auth_methods_supported?: string[];
}
+interface ConnectorRefreshErrorBody {
+ msg?: string;
+ error_code?: string;
+ retryable?: boolean;
+}
+
/** Format `fetch` errors so the underlying cause (DNS / TLS / refused / …) surfaces in logs.
* Node undici flattens every transport-level failure to `TypeError: fetch failed` with the
* real reason hung off `err.cause`; logging just `err.message` loses the diagnostic. */
@@ -102,6 +108,18 @@ function _fetchDcr(label: string, url: string, init: RequestInit = {}): Promise<
);
}
+function _refreshErrorFromBody(body: ConnectorRefreshErrorBody, fallback: string): Error {
+ const errorCode = typeof body.error_code === 'string' ? body.error_code : '';
+ const message = body.msg || fallback;
+ const err = new Error(errorCode ? `${errorCode}: ${message}` : message) as Error & {
+ code?: string;
+ retryable?: boolean;
+ };
+ if (errorCode) err.code = errorCode;
+ if (typeof body.retryable === 'boolean') err.retryable = body.retryable;
+ return err;
+}
+
/** Fetch `<base>/.well-known/<name>`, falling back to root-level discovery if path-suffixed
* fails (per MCP authorization spec — providers can serve discovery at either location). */
async function _fetchWellKnown<T>(mcpUrl: string, wellKnownName: string): Promise<T> {
@@ -545,6 +563,8 @@ export async function storeDcrServerManaged(
const body = await res.json() as {
code: number;
msg?: string;
+ error_code?: string;
+ retryable?: boolean;
access_token?: string;
grant_id?: string;
server_managed?: boolean;
@@ -553,7 +573,7 @@ export async function storeDcrServerManaged(
scope?: string;
account_label?: string;
};
- if (body.code !== 0) throw new Error(body.msg || 'DCR server-managed store failed');
+ if (body.code !== 0) throw _refreshErrorFromBody(body, 'DCR server-managed store failed');
return _grantFromServerPayload(provider, grant, body);
}
@@ -578,6 +598,8 @@ export async function refreshDcrServerManaged(
const body = await res.json() as {
code: number;
msg?: string;
+ error_code?: string;
+ retryable?: boolean;
access_token?: string;
grant_id?: string;
server_managed?: boolean;
@@ -586,7 +608,7 @@ export async function refreshDcrServerManaged(
scope?: string;
account_label?: string;
};
- if (body.code !== 0) throw new Error(body.msg || 'DCR server-managed refresh failed');
+ if (body.code !== 0) throw _refreshErrorFromBody(body, 'DCR server-managed refresh failed');
return _grantFromServerPayload(provider, grant, body);
}
diff --git a/src/main/features/connectors/oauth.ts b/src/main/features/connectors/oauth.ts
index 5b75eec9..d3264f1e 100644
--- a/src/main/features/connectors/oauth.ts
+++ b/src/main/features/connectors/oauth.ts
@@ -50,6 +50,12 @@ interface PendingFlow {
timer: NodeJS.Timeout;
}
+interface ConnectorRefreshErrorBody {
+ msg?: string;
+ error_code?: string;
+ retryable?: boolean;
+}
+
export interface GooglePickerResult {
grant: OAuthGrant;
pickedFileIds: string[];
@@ -79,6 +85,18 @@ function _missingRequiredScopes(requiredScopes: string[] | undefined, grantedSco
return requiredScopes.filter((scope) => !granted.has(scope));
}
+function _refreshErrorFromBody(body: ConnectorRefreshErrorBody, fallback: string): Error {
+ const errorCode = typeof body.error_code === 'string' ? body.error_code : '';
+ const message = body.msg || fallback;
+ const err = new Error(errorCode ? `${errorCode}: ${message}` : message) as Error & {
+ code?: string;
+ retryable?: boolean;
+ };
+ if (errorCode) err.code = errorCode;
+ if (typeof body.retryable === 'boolean') err.retryable = body.retryable;
+ return err;
+}
+
/** Externally callable cancel — wired to the renderer's "取消" link so a user who closed the
* browser without completing OAuth can unfreeze the card without waiting for the timeout. */
export function cancelInFlightOAuth(): boolean {
@@ -314,15 +332,16 @@ export async function refreshIfStale(
const body = await res.json() as {
code: number;
msg?: string;
+ error_code?: string;
+ retryable?: boolean;
access_token?: string;
refresh_token?: string;
expires_in?: number;
token_type?: string;
scope?: string;
};
- if (body.code !== 0 || !body.access_token) {
- throw new Error(body.msg || 'invalid refresh response');
- }
+ if (body.code !== 0) throw _refreshErrorFromBody(body, 'invalid refresh response');
+ if (!body.access_token) throw new Error('invalid refresh response');
const expires_at = typeof body.expires_in === 'number' ? Date.now() + body.expires_in * 1000 : null;
const scopes = body.scope ? body.scope.split(/[\s,]+/).filter(Boolean) : grant.scopes;
void uid;
@@ -409,6 +428,8 @@ async function refreshGithubServerManaged(
const body = await res.json() as {
code: number;
msg?: string;
+ error_code?: string;
+ retryable?: boolean;
access_token?: string;
grant_id?: string;
server_managed?: boolean;
@@ -417,9 +438,8 @@ async function refreshGithubServerManaged(
scope?: string;
account_label?: string;
};
- if (body.code !== 0 || !body.access_token || !body.grant_id) {
- throw new Error(body.msg || 'invalid github refresh response');
- }
+ if (body.code !== 0) throw _refreshErrorFromBody(body, 'invalid github refresh response');
+ if (!body.access_token || !body.grant_id) throw new Error('invalid github refresh response');
const expires_at = typeof body.expires_in === 'number' ? Date.now() + body.expires_in * 1000 : null;
return {
access_token: body.access_token,
diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.js
index da86a3ef..e8285c21 100644
--- a/src/renderer/modules/connectors.js
+++ b/src/renderer/modules/connectors.js
@@ -232,10 +232,10 @@ function _connectorErrorFallback(kind) {
function _formatConnectorStatusError(message) {
const msg = String(message || '');
- if (/fetch failed|network|timeout|timed out|econnreset|econnrefused|eai_again|enotfound|socket|connection (closed|reset|dropped)|terminated/i.test(msg)) {
+ if (/fetch failed|network|timeout|timed out|econnreset|econnrefused|eai_again|enotfound|socket|connection (closed|reset|dropped)|terminated|\brefresh_failed\b|刷新授权失败|failed to refresh authorization|認証の更新に失敗|Falha ao atualizar a autorização/i.test(msg)) {
return _connectorErrorFallback('network');
}
- if (/invalid_grant|connector_reconnect_required|reconnect required|grant not found/i.test(msg)) {
+ if (/invalid_grant|connector_reconnect_required|reconnect required|grant not found|授权已失效|Authorization expired|認証の有効期限|A autorização expirou/i.test(msg)) {
return _connectorErrorFallback('reconnect');
}
return msg;
diff --git a/test/main/features/connectors/manager.test.ts b/test/main/features/connectors/manager.test.ts
index 5580e066..150fda06 100644
--- a/test/main/features/connectors/manager.test.ts
+++ b/test/main/features/connectors/manager.test.ts
@@ -354,6 +354,81 @@ describe('features/connectors/manager authorization recovery', () => {
expect(registry.load(TEST_UID).connections['bing-webmaster'].status).toMatchObject({ kind: 'connected' });
});
+ it('preserves established server-bridge connectors when refresh_failed is localized by Server', async () => {
+ mocks.oauth.refreshIfStale = vi.fn(async () => {
+ throw new Error('刷新授权失败');
+ });
+
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ const manager = await import('../../../../src/main/features/connectors/manager');
+
+ const bing = bingWebmasterInstance(['webmaster.read']);
+ bing.oauth_grant.expires_at = Date.now() - 1;
+ await registry.upsert(TEST_UID, bing);
+ await manager.refreshTools(TEST_UID, 'bing-webmaster');
+ expect(registry.load(TEST_UID).connections['bing-webmaster'].status).toMatchObject({ kind: 'connected' });
+
+ const github = githubInstance();
+ github.oauth_grant.expires_at = Date.now() - 1;
+ mocks.oauth.refreshIfStale = vi.fn(async () => {
+ const err = new Error('Failed to refresh authorization') as Error & { code?: string; retryable?: boolean };
+ err.code = 'connector_refresh_failed';
+ err.retryable = true;
+ throw err;
+ });
+ await registry.upsert(TEST_UID, github);
+ await manager.refreshTools(TEST_UID, 'github');
+ expect(registry.load(TEST_UID).connections.github.status).toMatchObject({ kind: 'connected' });
+ });
+
+ it('preserves established DCR connectors when server-managed refresh returns generic refresh_failed', async () => {
+ mocks.dcr.refreshDcrServerManaged = vi.fn(async () => {
+ const err = new Error('Failed to refresh authorization') as Error & { code?: string; retryable?: boolean };
+ err.code = 'connector_refresh_failed';
+ err.retryable = true;
+ throw err;
+ });
+
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ const manager = await import('../../../../src/main/features/connectors/manager');
+
+ const inst = notionInstance();
+ inst.oauth_grant.refresh_token = null;
+ (inst.oauth_grant as any).server_managed = true;
+ (inst.oauth_grant as any).server_grant_id = 'grant-1';
+ delete (inst as any).dcr_client;
+ await registry.upsert(TEST_UID, inst);
+ await manager.refreshTools(TEST_UID, 'notion');
+
+ expect(registry.load(TEST_UID).connections.notion.status).toMatchObject({ kind: 'connected' });
+ });
+
+ it('keeps structured DCR reconnect-required rows visible for reconnect', async () => {
+ mocks.dcr.refreshDcrServerManaged = vi.fn(async () => {
+ const err = new Error('Authorization expired. Please reconnect') as Error & { code?: string; retryable?: boolean };
+ err.code = 'connector_reconnect_required';
+ err.retryable = false;
+ throw err;
+ });
+
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ const manager = await import('../../../../src/main/features/connectors/manager');
+
+ const inst = notionInstance();
+ inst.oauth_grant.refresh_token = null;
+ (inst.oauth_grant as any).server_managed = true;
+ (inst.oauth_grant as any).server_grant_id = 'grant-1';
+ delete (inst as any).dcr_client;
+ await registry.upsert(TEST_UID, inst);
+ await manager.refreshTools(TEST_UID, 'notion');
+
+ const row = manager.listInstances(TEST_UID).find((inst) => inst.id === 'notion');
+ expect(row?.status).toMatchObject({
+ kind: 'error',
+ message: expect.stringContaining('Authorization expired'),
+ });
+ });
+
it('removes the connector row if a refresh response no longer includes required scopes', async () => {
mocks.oauth.refreshIfStale = vi.fn(async (_uid, _entry, grant) => ({
...(grant as object),