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.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Harden connector refresh state
wyt296e9fed4a02
diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.tsindex f49f7bf0..4d9cb9c9 100644--- a/src/main/features/connectors/manager.ts+++ b/src/main/features/connectors/manager.ts@@ -155,7 +155,7 @@ async function _preserveEstablishedStateOnTransientFailure(error: (err as Error).message,});const current = registry.load(uid).connections[inst.id] || inst;- if (_isTransientStatusError(current)) {+ if (current.status?.kind !== 'connected') {const healed = await _patchStatus(uid, current, (cur) => ({..._asConnectedFromCache(cur),updated_at: _nowIso(),@@ -538,8 +538,7 @@ function _shouldForceRefreshAfterConnectFailure(if (!entry) return false;if (!inst.oauth_grant?.server_grant_id || !inst.oauth_grant.server_managed) return false;const msg = (err as Error).message || '';- return /\b(401|403|unauthorized|AuthenticateToken|authentication failed|invalid_token|invalid access token|missing_token)\b/i.test(msg)- || _isTransientConnectorFailure(err);+ return /\b(401|403|unauthorized|AuthenticateToken|authentication failed|invalid_token|invalid access token|missing_token)\b/i.test(msg);}export async function bootstrap(uid: string): Promise<void> {diff --git a/src/main/features/connectors/tools-adapter.ts b/src/main/features/connectors/tools-adapter.tsindex 6fbbed53..0578e124 100644--- a/src/main/features/connectors/tools-adapter.ts+++ b/src/main/features/connectors/tools-adapter.ts@@ -18,9 +18,9 @@* "no connectors" (intentionally stricter than `agent.skill_list`'s three-state — see* PC/CLAUDE.md §6.5 "Per-agent scope"). Only a non-empty `string[]` grants access.*- * Disconnected instances are still returned (with their stale `tools_cache` and current status)- * so callers can surface the situation to the user; `manager.callTool` auto-reconnects on use,- * but `list_connector_tools` refuses to advertise schemas for a non-`connected` instance.+ * Visibility resolution is intentionally side-effect free. It only reads local connector state;+ * Server/MCP restore, cache refresh, reconnect, and token checks happen during explicit connector+ * management flows or when `manager.callTool` actually needs to use the connector.*/import * as manager from './manager';import * as agents from '../agents';@@ -63,12 +63,6 @@ export async function resolveVisibleConnectors(agentId: string | undefined,): Promise<Array<{ instance: ConnectorInstance; tools: ToolSchema[] }>> {if (!uid) return [];- const maybeManager = manager as typeof manager & {- restoreComposioConnectionsFromServer?: (uid: string, reason: string) => Promise<number>;- refreshStaleToolCaches?: (uid: string, reason: string) => Promise<number>;- };- await maybeManager.restoreComposioConnectionsFromServer?.(uid, 'visible_connectors').catch(() => 0);- await maybeManager.refreshStaleToolCaches?.(uid, 'visible_connectors').catch(() => 0);const all = manager.listInstances(uid);if (!all.length) return [];// Live-state filter: only currently-connected instances surface to the LLM. A `connecting` /diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.jsindex dce5e820..da86a3ef 100644--- a/src/renderer/modules/connectors.js+++ b/src/renderer/modules/connectors.js@@ -17,6 +17,9 @@// "superseded" message is swallowed since it's caused by the user's own re-click).const _connectorsLog = createLogger('connectors');+const _CONNECTORS_RENDER_CACHE_VERSION = 2;+const _CONNECTORS_RENDER_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;+let _connectorsLegacyCachePurged = false;function _connectorsTrackClick(action, data) {}@@ -57,22 +60,97 @@ let _connectorsState = {* stays clickable; re-click supersedes the prior flow (see comment in `_runConnect`). */connecting: new Set(),};+let _connectorsLoadSeq = 0;++function _connectorsRenderCacheKey() {+ const uid = (typeof currentUserId === 'string' && currentUserId)+ ? currentUserId+ : ((typeof globalThis.currentUserId === 'string' && globalThis.currentUserId) ? globalThis.currentUserId : 'local');+ return `orkas.connectors.renderCache.v${_CONNECTORS_RENDER_CACHE_VERSION}.${uid}`;+}++function _purgeLegacyConnectorsRenderCaches() {+ if (_connectorsLegacyCachePurged) return;+ _connectorsLegacyCachePurged = true;+ try {+ const prefix = 'orkas.connectors.renderCache.v';+ const currentPrefix = `orkas.connectors.renderCache.v${_CONNECTORS_RENDER_CACHE_VERSION}.`;+ const doomed = [];+ for (let i = 0; i < localStorage.length; i += 1) {+ const key = localStorage.key(i);+ if (key && key.startsWith(prefix) && !key.startsWith(currentPrefix)) doomed.push(key);+ }+ for (const key of doomed) localStorage.removeItem(key);+ } catch (_) { /* localStorage unavailable / quota — skip */ }+}++function _sanitizeConnectorArray(value, options = {}) {+ const arr = Array.isArray(value) ? value.filter((item) => item && typeof item === 'object') : [];+ if (!options.dropErrored) return arr;+ return arr.filter((item) => !(item.status && item.status.kind === 'error'));+}++function _hydrateConnectorsRenderCache() {+ if (_connectorsState.catalog.length || _connectorsState.instances.length) return false;+ try {+ const raw = localStorage.getItem(_connectorsRenderCacheKey());+ if (!raw) return false;+ const parsed = JSON.parse(raw);+ if (!parsed || parsed.version !== _CONNECTORS_RENDER_CACHE_VERSION) return false;+ if (Date.now() - Number(parsed.updated_at || 0) > _CONNECTORS_RENDER_CACHE_TTL_MS) return false;+ const catalog = _sanitizeConnectorArray(parsed.catalog);+ const instances = _sanitizeConnectorArray(parsed.instances, { dropErrored: true });+ if (!catalog.length && !instances.length) return false;+ _connectorsState.catalog = catalog;+ _connectorsState.instances = instances;+ return true;+ } catch (_) {+ return false;+ }+}++function _persistConnectorsRenderCache() {+ if (!_connectorsState.catalog.length && !_connectorsState.instances.length) return;+ try {+ localStorage.setItem(_connectorsRenderCacheKey(), JSON.stringify({+ version: _CONNECTORS_RENDER_CACHE_VERSION,+ updated_at: Date.now(),+ catalog: _connectorsState.catalog,+ instances: _sanitizeConnectorArray(_connectorsState.instances, { dropErrored: true }),+ }));+ } catch (_) { /* localStorage unavailable / quota — skip */ }+}async function loadConnectors() {+ const seq = ++_connectorsLoadSeq;+ _purgeLegacyConnectorsRenderCaches();+ _hydrateConnectorsRenderCache();_connectorsState.loading = true;_renderConnectorsGrid();try {const [catRes, listRes] = await Promise.all([- window.orkas.invoke('connectors.catalog', {}),- window.orkas.invoke('connectors.list', {}),+ window.orkas.invoke('connectors.catalog', {}).catch((err) => ({ ok: false, error: err })),+ window.orkas.invoke('connectors.list', {}).catch((err) => ({ ok: false, error: err })),]);- _connectorsState.catalog = (catRes && catRes.ok && Array.isArray(catRes.catalog)) ? catRes.catalog : [];- _connectorsState.instances = (listRes && listRes.ok && Array.isArray(listRes.instances)) ? listRes.instances : [];+ if (seq !== _connectorsLoadSeq) return;+ if (catRes && catRes.ok && Array.isArray(catRes.catalog)) {+ _connectorsState.catalog = catRes.catalog;+ } else {+ _connectorsLog.warn('catalog failed', { error: catRes && (catRes.error && catRes.error.message || catRes.error) });+ }+ if (listRes && listRes.ok && Array.isArray(listRes.instances)) {+ _connectorsState.instances = listRes.instances;+ } else {+ _connectorsLog.warn('list failed', { error: listRes && (listRes.error && listRes.error.message || listRes.error) });+ }+ _persistConnectorsRenderCache();} catch (err) {_connectorsLog.warn('list failed', { error: err && err.message });} finally {- _connectorsState.loading = false;- _renderConnectorsGrid();+ if (seq === _connectorsLoadSeq) {+ _connectorsState.loading = false;+ _renderConnectorsGrid();+ }}}diff --git a/test/main/features/connectors/availability.test.ts b/test/main/features/connectors/availability.test.tsindex 5e8b2f32..1106a24e 100644--- a/test/main/features/connectors/availability.test.ts+++ b/test/main/features/connectors/availability.test.ts@@ -133,9 +133,11 @@ describe('Google connector remote switches', () => {it('filters disabled Google connectors from model-visible connector tools', async () => {await writeRemoteConfig({ google: 'enabled', gmail: 'disabled' });+ const restoreComposioConnectionsFromServer = vi.fn(async () => 0);+ const refreshStaleToolCaches = vi.fn(async () => 0);vi.doMock('../../../../src/main/features/connectors/manager', () => ({- restoreComposioConnectionsFromServer: vi.fn(async () => 0),- refreshStaleToolCaches: vi.fn(async () => 0),+ restoreComposioConnectionsFromServer,+ refreshStaleToolCaches,listInstances: vi.fn(() => [connectedInstance('google-workspace'),connectedInstance('gmail'),@@ -154,5 +156,7 @@ describe('Google connector remote switches', () => {const visible = await toolsAdapter.resolveVisibleConnectors(TEST_UID, undefined);expect(visible.map((item) => item.instance.id).sort()).toEqual(['gcal', 'notion']);+ expect(restoreComposioConnectionsFromServer).not.toHaveBeenCalled();+ expect(refreshStaleToolCaches).not.toHaveBeenCalled();});});diff --git a/test/main/features/connectors/manager.test.ts b/test/main/features/connectors/manager.test.tsindex 541c43cb..5580e066 100644--- a/test/main/features/connectors/manager.test.ts+++ b/test/main/features/connectors/manager.test.ts@@ -168,6 +168,26 @@ function githubGrant() {};}+function githubInstance() {+ const now = new Date().toISOString();+ return {+ id: 'github',+ display_name: 'GitHub',+ transport: {+ kind: 'streamable-http' as const,+ url: 'https://api.githubcopilot.com/mcp/',+ headers: { Authorization: 'Bearer ghu-token' },+ },+ enabled_subtools: null,+ tools_cache: [{ name: 'github_search_repositories', description: '', input_schema: {} }],+ tools_cached_at: Date.now(),+ status: { kind: 'connected' as const, since: 1 },+ oauth_grant: githubGrant(),+ created_at: now,+ updated_at: now,+ };+}+function discordGrant() {return {access_token: 'discord-user-access-token',@@ -536,17 +556,56 @@ describe('features/connectors/manager authorization recovery', () => {const tools = await manager.refreshTools(TEST_UID, 'notion');expect(tools).toEqual([{ name: 'notion_search', description: '', input_schema: {} }]);- // Despite every connect failing, the forced refresh ran and the established- // (connected, cached-tools) state is preserved rather than downgraded.+ // Despite every connect failing, this is still a network problem, not an+ // auth rejection. Keep the established state and do not force-refresh the+ // server-managed grant just because the MCP endpoint was unreachable.expect(connectMock).toHaveBeenCalled();- expect(refreshDcrServerManaged).toHaveBeenCalledWith(- 'notion',- expect.objectContaining({ server_grant_id: 'grant-1' }),- { force: true },- );+ expect(refreshDcrServerManaged).not.toHaveBeenCalled();expect(registry.load(TEST_UID).connections.notion.status).toMatchObject({ kind: 'connected' });});+ it('preserves established GitHub state when transient MCP failures continue after retry', async () => {+ const connectMock = vi.fn(async () => { throw new Error('fetch failed'); });+ mocks.mcp.connect = connectMock;+ mocks.mcp.close = vi.fn(async () => {});+ mocks.oauth.refreshIfStale = vi.fn(async (_uid: string, _entry: unknown, grant: unknown) => ({+ ...(grant as object),+ access_token: 'forced-ghu-token',+ expires_at: Date.now() + 60 * 60 * 1000,+ }));++ const registry = await import('../../../../src/main/features/connectors/registry');+ const manager = await import('../../../../src/main/features/connectors/manager');++ await registry.upsert(TEST_UID, githubInstance());+ const tools = await manager.refreshTools(TEST_UID, 'github');++ expect(tools).toEqual([{ name: 'github_search_repositories', description: '', input_schema: {} }]);+ expect(connectMock).toHaveBeenCalled();+ expect(mocks.oauth.refreshIfStale).not.toHaveBeenCalled();+ expect(registry.load(TEST_UID).connections.github.status).toMatchObject({ kind: 'connected' });+ expect(registry.load(TEST_UID).connections.github.oauth_grant?.access_token).toBe('ghu-token');+ });++ it('heals stale GitHub reconnect errors when the latest failure is transient', async () => {+ const connectMock = vi.fn(async () => { throw new Error('fetch failed'); });+ mocks.mcp.connect = connectMock;+ mocks.mcp.close = vi.fn(async () => {});++ const registry = await import('../../../../src/main/features/connectors/registry');+ const manager = await import('../../../../src/main/features/connectors/manager');++ const inst = githubInstance();+ (inst as any).status = { kind: 'error', message: 'Authorization expired, reconnect required', at: Date.now() };+ await registry.upsert(TEST_UID, inst);++ const tools = await manager.refreshTools(TEST_UID, 'github');++ expect(tools).toEqual([{ name: 'github_search_repositories', description: '', input_schema: {} }]);+ expect(connectMock).toHaveBeenCalled();+ expect(registry.load(TEST_UID).connections.github.status).toMatchObject({ kind: 'connected' });+ });+it('heals persisted transient Notion errors with cached tools on list', async () => {const registry = await import('../../../../src/main/features/connectors/registry');const manager = await import('../../../../src/main/features/connectors/manager');diff --git a/test/main/ipc/connectors.test.ts b/test/main/ipc/connectors.test.tsindex a96bca81..5d0296c1 100644--- a/test/main/ipc/connectors.test.ts+++ b/test/main/ipc/connectors.test.ts@@ -16,6 +16,9 @@ beforeEach(() => {afterEach(() => {if (prevWs === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;else process.env.ORKAS_WORKSPACE_ROOT = prevWs;+ vi.doUnmock('../../../src/main/features/connectors');+ vi.doUnmock('../../../src/main/features/component_enabled');+ vi.doUnmock('../../../src/main/features/connectors/availability');fs.rmSync(tmpDir, { recursive: true, force: true });});@@ -41,6 +44,33 @@ function baseInstance(transport: any): any {}describe('ipc/connectors renderer DTO', () => {+ it('lists local connector state without triggering Composio restore', async () => {+ const restoreComposioConnectionsFromServer = vi.fn(async () => 0);+ vi.doMock('../../../src/main/features/connectors', () => ({+ listInstances: vi.fn(() => [baseInstance({+ kind: 'streamable-http',+ url: 'https://example.com/mcp',+ headers: {},+ })]),+ restoreComposioConnectionsFromServer,+ }));+ vi.doMock('../../../src/main/features/component_enabled', () => ({+ isConnectorEnabled: vi.fn(() => true),+ setConnectorEnabled: vi.fn(),+ }));+ vi.doMock('../../../src/main/features/connectors/availability', () => ({+ catalogWithAvailability: vi.fn((catalog) => catalog),+ isConnectorRuntimeEnabled: vi.fn(() => true),+ }));++ const { invokeHandlers } = await import('../../../src/main/ipc/connectors');+ const out = await invokeHandlers['connectors.list']({}, { userId: 'u-ipc' });+ await new Promise((resolve) => setTimeout(resolve, 5));++ expect(out.instances.map((inst) => inst.id)).toEqual(['custom-secret']);+ expect(restoreComposioConnectionsFromServer).not.toHaveBeenCalled();+ });+it('does not expose stdio argv/env secrets', async () => {const { _toClientInstanceForTest } = await import('../../../src/main/ipc/connectors');const dto = _toClientInstanceForTest(baseInstance({diff --git a/test/renderer/connectors-render-cache.test.ts b/test/renderer/connectors-render-cache.test.tsnew file mode 100644index 00000000..ce6c197b--- /dev/null+++ b/test/renderer/connectors-render-cache.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as vm from 'node:vm';++function loadConnectorsRenderer() {+ const code = fs.readFileSync(+ path.join(__dirname, '../../src/renderer/modules/connectors.js'),+ 'utf8',+ );+ const storage = new Map<string, string>();+ const context: any = {+ console,+ currentUserId: 'u-cache',+ currentView: 'connectors',+ globalThis: { currentUserId: 'u-cache' },+ createLogger: () => ({ warn: () => {}, error: () => {}, info: () => {} }),+ localStorage: {+ getItem: (key: string) => storage.get(key) || null,+ setItem: (key: string, value: string) => { storage.set(key, value); },+ removeItem: (key: string) => { storage.delete(key); },+ key: (index: number) => Array.from(storage.keys())[index] || null,+ get length() { return storage.size; },+ },+ document: {+ getElementById: () => null,+ querySelectorAll: () => [],+ body: { appendChild: () => {} },+ addEventListener: () => {},+ removeEventListener: () => {},+ },+ window: {+ addEventListener: () => {},+ removeEventListener: () => {},+ innerWidth: 1200,+ innerHeight: 800,+ orkas: {+ invoke: async () => ({ ok: true, catalog: [], instances: [] }),+ onPushEvent: () => {},+ },+ },+ t: (key: string) => key,+ getLang: () => 'zh',+ pickDesc: (entry: any) => entry?.description_zh || entry?.description_en || '',+ formatChatUseLabel: ({ name }: { name: string }) => name,+ sanitizeSvgIconHtml: () => '',+ escapeHtml: (value: unknown) => String(value ?? ''),+ };+ context.window.window = context.window;+ context.window.globalThis = context.globalThis;+ vm.createContext(context);+ vm.runInContext(code, context, { filename: 'connectors.js' });+ return { context, storage };+}++describe('connectors renderer cache', () => {+ it('does not persist errored connector instances', () => {+ const { context, storage } = loadConnectorsRenderer();++ vm.runInContext(`+ _connectorsState.catalog = [{ id: 'github', display_name: 'GitHub' }];+ _connectorsState.instances = [+ { id: 'github', status: { kind: 'error', message: 'Authorization expired' } },+ { id: 'notion', status: { kind: 'connected', since: 1 } },+ ];+ _persistConnectorsRenderCache();+ `, context);++ const raw = storage.get('orkas.connectors.renderCache.v2.u-cache');+ expect(raw).toBeTruthy();+ const parsed = JSON.parse(raw!);+ expect(parsed.version).toBe(2);+ expect(parsed.instances).toEqual([{ id: 'notion', status: { kind: 'connected', since: 1 } }]);+ });++ it('drops errored connector instances while hydrating cached state', () => {+ const { context, storage } = loadConnectorsRenderer();+ storage.set('orkas.connectors.renderCache.v2.u-cache', JSON.stringify({+ version: 2,+ updated_at: Date.now(),+ catalog: [{ id: 'github', display_name: 'GitHub' }],+ instances: [+ { id: 'github', status: { kind: 'error', message: 'Authorization expired' } },+ { id: 'notion', status: { kind: 'connected', since: 1 } },+ ],+ }));++ const hydrated = vm.runInContext(`+ _connectorsState.catalog = [];+ _connectorsState.instances = [];+ _hydrateConnectorsRenderCache();+ JSON.stringify(_connectorsState.instances);+ `, context);++ expect(JSON.parse(hydrated)).toEqual([{ id: 'notion', status: { kind: 'connected', since: 1 } }]);+ });++ it('purges stale connector render cache versions', () => {+ const { context, storage } = loadConnectorsRenderer();+ storage.set('orkas.connectors.renderCache.v1.u-cache', JSON.stringify({+ version: 1,+ updated_at: Date.now(),+ instances: [{ id: 'github', status: { kind: 'error', message: 'Authorization expired' } }],+ }));+ storage.set('orkas.connectors.renderCache.v2.u-cache', JSON.stringify({+ version: 2,+ updated_at: Date.now(),+ instances: [{ id: 'notion', status: { kind: 'connected', since: 1 } }],+ }));+ storage.set('some.other.key', 'keep');++ vm.runInContext('_purgeLegacyConnectorsRenderCaches();', context);++ expect(storage.has('orkas.connectors.renderCache.v1.u-cache')).toBe(false);+ expect(storage.has('orkas.connectors.renderCache.v2.u-cache')).toBe(true);+ expect(storage.has('some.other.key')).toBe(true);+ });+});