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
feat(connectors): add shared API key setup and isolate open user profiles
wyt9e2cb37bce11
diff --git a/bin/composio-mcp-server.cjs b/bin/composio-mcp-server.cjsnew file mode 100644index 00000000..1ad6425d--- /dev/null+++ b/bin/composio-mcp-server.cjs@@ -0,0 +1,199 @@+#!/usr/bin/env node+require('./proxy-bootstrap.cjs');++const { Server } = require('@modelcontextprotocol/sdk/server/index.js');+const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');+const { ListToolsRequestSchema, CallToolRequestSchema } = require('@modelcontextprotocol/sdk/types.js');++const API_BASE = (process.env.ORKAS_API_BASE || '').replace(/\/+$/, '');+const API_KEY = process.env.ORKAS_API_KEY || '';+const CONNECTION_ID = process.env.COMPOSIO_CONNECTION_ID || '';+const CONNECTOR_ID = process.env.COMPOSIO_CONNECTOR_ID || '';+const TOOLS_REQUEST_TIMEOUT_MS = 25000;+const EXECUTE_REQUEST_TIMEOUT_MS = 100000;+const CREDIT_CONTEXT_ARG = '__orkas_credit_context';++class OrkasProxyResponseError extends Error {+ constructor(message, status, code) {+ super(message);+ this.name = 'OrkasProxyResponseError';+ this.status = Number(status) || 0;+ this.code = String(code || 'connector_proxy_failed');+ }+}++function splitComposioToolArguments(value) {+ const args = value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};+ const raw = args[CREDIT_CONTEXT_ARG];+ delete args[CREDIT_CONTEXT_ARG];+ const context = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};+ const bounded = (input) => String(input || '')+ .replace(/[\u0000-\u001f\u007f]+/g, ' ')+ .trim()+ .slice(0, 64)+ .trim();+ const fields = {+ orkas_conversation_id: bounded(context.conversationId || context.conversation_id),+ orkas_turn_id: bounded(context.turnId || context.turn_id),+ };+ return {+ args,+ creditContextBody: Object.fromEntries(Object.entries(fields).filter(([, field]) => field)),+ };+}++function clientHeaders() {+ try {+ const parsed = JSON.parse(process.env.ORKAS_CLIENT_HEADERS_JSON || '{}');+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};+ return Object.fromEntries(Object.entries(parsed)+ .filter(([key, value]) => key.startsWith('Orkas-') && typeof value === 'string'));+ } catch {+ return {};+ }+}++function assertConfigured() {+ if (!API_BASE) throw new Error('ORKAS_API_BASE env var not set');+ if (!API_KEY) throw new Error('ORKAS_API_KEY env var not set');+ if (!CONNECTION_ID || !CONNECTOR_ID) throw new Error('Composio connector env vars not set');+}++function boundedMessage(value, fallback) {+ const text = String(value || '')+ .replace(/[\u0000-\u001f\u007f]+/g, ' ')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, 500);+ return text || fallback;+}++function boundedErrorCode(value) {+ const code = String(value || '').trim();+ return /^[A-Za-z0-9_.:-]{1,80}$/.test(code) ? code : 'connector_proxy_failed';+}++async function orkasRequest(path, body, timeoutMs) {+ assertConfigured();+ const res = await fetch(`${API_BASE}${path}`, {+ method: 'POST',+ signal: AbortSignal.timeout(timeoutMs),+ headers: {+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ ...clientHeaders(),+ Authorization: `Bearer ${API_KEY}`,+ },+ body: JSON.stringify({+ connection_id: CONNECTION_ID,+ connector_id: CONNECTOR_ID,+ ...(body || {}),+ }),+ });+ const text = await res.text();+ let payload = {};+ let parsedJson = false;+ try {+ payload = text ? JSON.parse(text) : {};+ parsedJson = !!payload && typeof payload === 'object' && !Array.isArray(payload);+ if (!parsedJson) payload = {};+ } catch { payload = {}; }+ if (!res.ok || payload.code !== 0) {+ const err = payload.error && typeof payload.error === 'object' ? payload.error : {};+ throw new OrkasProxyResponseError(+ boundedMessage(parsedJson ? (payload.msg || err.message) : '', 'Connector action failed'),+ res.status,+ boundedErrorCode(parsedJson ? (err.code || err.type) : ''),+ );+ }+ return payload;+}++async function callComposioTool(name, value, request = orkasRequest) {+ const { args, creditContextBody } = splitComposioToolArguments(value);+ try {+ const body = await request('/connectors/composio/execute', {+ tool_slug: name,+ arguments: args,+ ...creditContextBody,+ }, EXECUTE_REQUEST_TIMEOUT_MS);+ return { content: [{ type: 'text', text: JSON.stringify(body.result ?? body, null, 2) }] };+ } catch (err) {+ if (!(err instanceof OrkasProxyResponseError)) throw err;+ return {+ isError: true,+ content: [{ type: 'text', text: JSON.stringify({ error_code: err.code, message: err.message }) }],+ };+ }+}++function normalizeTool(tool) {+ const slug = String(tool.slug || tool.name || '').trim();+ if (!slug) return null;+ const hints = tool.annotations && typeof tool.annotations === 'object'+ ? tool.annotations+ : {};+ const policy = tool.policy && typeof tool.policy === 'object' && !Array.isArray(tool.policy)+ ? tool.policy+ : null;+ return {+ name: slug,+ description: String(tool.description || tool.name || slug),+ inputSchema: tool.input_schema && typeof tool.input_schema === 'object'+ ? tool.input_schema+ : { type: 'object', properties: {} },+ ...(Object.keys(hints).length ? {+ annotations: {+ ...(typeof hints.title === 'string' ? { title: hints.title } : {}),+ ...(typeof hints.readOnlyHint === 'boolean' ? { readOnlyHint: hints.readOnlyHint } : {}),+ ...(typeof hints.destructiveHint === 'boolean' ? { destructiveHint: hints.destructiveHint } : {}),+ ...(typeof hints.idempotentHint === 'boolean' ? { idempotentHint: hints.idempotentHint } : {}),+ ...(typeof hints.openWorldHint === 'boolean' ? { openWorldHint: hints.openWorldHint } : {}),+ },+ } : {}),+ ...(policy ? {+ _meta: {+ orkas: {+ actionPolicy: {+ risk: String(policy.risk || ''),+ confirmation: String(policy.confirmation || ''),+ sensitiveOperation: String(policy.sensitive_operation || ''),+ maxBatchSize: Number(policy.max_batch_size || 0),+ },+ },+ },+ } : {}),+ };+}++async function main() {+ const server = new Server(+ { name: `orkas-composio-${CONNECTOR_ID || 'connector'}`, version: '1.0.0' },+ { capabilities: { tools: {} } },+ );+ server.setRequestHandler(ListToolsRequestSchema, async () => {+ const body = await orkasRequest('/connectors/composio/tools', {}, TOOLS_REQUEST_TIMEOUT_MS);+ return { tools: Array.isArray(body.tools) ? body.tools.map(normalizeTool).filter(Boolean) : [] };+ });+ server.setRequestHandler(CallToolRequestSchema, async (req) => (+ callComposioTool(req.params.name, req.params.arguments)+ ));+ await server.connect(new StdioServerTransport());+}++if (require.main === module) {+ main().catch((err) => {+ console.error('[orkas-composio-mcp] fatal:', err && err.stack || err);+ process.exit(1);+ });+}++module.exports = {+ CREDIT_CONTEXT_ARG,+ TOOLS_REQUEST_TIMEOUT_MS,+ EXECUTE_REQUEST_TIMEOUT_MS,+ OrkasProxyResponseError,+ splitComposioToolArguments,+ callComposioTool,+ normalizeTool,+};diff --git a/src/main/features/auth.ts b/src/main/features/auth.tsindex 5c06c0c8..c232d4fb 100644--- a/src/main/features/auth.ts+++ b/src/main/features/auth.ts@@ -282,6 +282,27 @@ export interface TtsProfile {createdAt: number;}+export interface OrkasApiCredential {+ key: string;+ keyId: string;+ name: string;+ prefix: string;+ scopes: string[];+ expiresAt: number;+ ownerRef: string;+ updatedAt: number;+}++export interface OrkasApiCredentialStatus {+ configured: boolean;+ keyMasked: string;+ keyId: string;+ name: string;+ scopes: string[];+ expiresAt: number;+ updatedAt: number;+}+interface ProfilesFile {/** v3 = chat profiles only. v4 adds BYO search / image / video / speech profiles. */version: number;@@ -291,8 +312,13 @@ interface ProfilesFile {imageProfiles?: ImageProfile[];videoProfiles?: VideoProfile[];ttsProfiles?: TtsProfile[];+ /** One user-owned Orkas credential shared by every public API feature. */+ orkasApiCredential?: OrkasApiCredential;}+// The shared credential is optional, so it remains wire-compatible with the v6 profiles file.+// Keeping the version stable avoids rewriting every existing installation solely to add an+// absent optional field; legacy Orkas rows are still promoted and rewritten on first read.const PROFILES_FILE_VERSION = 6;const AUTH_SECRET_NAMESPACE = 'auth.profiles';const AUTH_SECRET_RECORD_ID = 'auth-profiles.json';@@ -425,7 +451,42 @@ function loadProfiles(opts: { throwOnInvalidExisting?: boolean } = {}): Profilesconst imageProfiles = parseImageProfilesArray((data as any).imageProfiles);const videoProfiles = parseVideoProfilesArray((data as any).videoProfiles);const ttsProfiles = parseTtsProfilesArray((data as any).ttsProfiles);- const store = { version: PROFILES_FILE_VERSION, profiles, entries, searchProfiles, imageProfiles, videoProfiles, ttsProfiles };+ let orkasApiCredential = parseOrkasApiCredential((data as any).orkasApiCredential);+ if (!orkasApiCredential) {+ const legacyKeys = new Set<string>();+ for (const profile of Object.values(profiles)) {+ if (profile.provider === ORKAS_API_PROVIDER && profile.type === 'api_key' && profile.key) {+ legacyKeys.add(profile.key);+ }+ }+ for (const profile of [...searchProfiles, ...imageProfiles, ...videoProfiles, ...ttsProfiles]) {+ if (profile.provider === ORKAS_API_PROVIDER && profile.apiKey) legacyKeys.add(profile.apiKey);+ }+ if (legacyKeys.size === 1) {+ const [key] = legacyKeys;+ orkasApiCredential = {+ key,+ keyId: '',+ name: '',+ prefix: maskKey(key),+ scopes: [],+ expiresAt: 0,+ ownerRef: '',+ updatedAt: Date.now(),+ };+ shouldRewrite = true;+ }+ }+ const store = {+ version: PROFILES_FILE_VERSION,+ profiles,+ entries,+ searchProfiles,+ imageProfiles,+ videoProfiles,+ ttsProfiles,+ ...(orkasApiCredential ? { orkasApiCredential } : {}),+ };if (shouldRewrite || Number((data as any).version) !== PROFILES_FILE_VERSION) {try { saveProfiles(store); }catch (err) {@@ -445,6 +506,25 @@ function loadProfiles(opts: { throwOnInvalidExisting?: boolean } = {}): Profilesreturn { version: PROFILES_FILE_VERSION, profiles: {}, entries: [], searchProfiles: [], imageProfiles: [], videoProfiles: [], ttsProfiles: [] };}+function parseOrkasApiCredential(raw: unknown): OrkasApiCredential | undefined {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;+ const value = raw as Record<string, unknown>;+ const key = typeof value.key === 'string' ? value.key.trim() : '';+ if (!key) return undefined;+ return {+ key,+ keyId: typeof value.keyId === 'string' ? value.keyId : '',+ name: typeof value.name === 'string' ? value.name : '',+ prefix: typeof value.prefix === 'string' && value.prefix ? value.prefix : maskKey(key),+ scopes: Array.isArray(value.scopes)+ ? value.scopes.filter((scope): scope is string => typeof scope === 'string')+ : [],+ expiresAt: typeof value.expiresAt === 'number' ? value.expiresAt : 0,+ ownerRef: typeof value.ownerRef === 'string' ? value.ownerRef : '',+ updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : Date.now(),+ };+}+function parseSearchProfilesArray(arr: unknown): SearchProfile[] {if (!Array.isArray(arr)) return [];const out: SearchProfile[] = [];@@ -601,6 +681,7 @@ function updateOrAppendOrkasServiceProfile<T extends { provider: string; apiKey:export function configureAllOrkasApiServices(rawApiKey: string): { configured: true } {const apiKey = String(rawApiKey || '').trim();if (!apiKey) throw new Error('api key required');+ if (!isBearerTokenHeaderSafe(apiKey)) throw new Error('api key contains invalid characters');const store = loadProfiles({ throwOnInvalidExisting: true });const now = Date.now();@@ -694,6 +775,17 @@ export function configureAllOrkasApiServices(rawApiKey: string): { configured: tapiKey,}),);+ const existingCredential = store.orkasApiCredential;+ store.orkasApiCredential = {+ key: apiKey,+ keyId: existingCredential?.key === apiKey ? existingCredential.keyId : '',+ name: existingCredential?.key === apiKey ? existingCredential.name : '',+ prefix: existingCredential?.key === apiKey ? existingCredential.prefix : maskKey(apiKey),+ scopes: existingCredential?.key === apiKey ? existingCredential.scopes : [],+ expiresAt: existingCredential?.key === apiKey ? existingCredential.expiresAt : 0,+ ownerRef: existingCredential?.key === apiKey ? existingCredential.ownerRef : '',+ updatedAt: now,+ };saveProfiles(store);for (const [profileId] of existingProfileEntries) clearCooldown(profileId);@@ -702,6 +794,94 @@ export function configureAllOrkasApiServices(rawApiKey: string): { configured: treturn { configured: true };}+function orkasApiCredentialError(code: string, message: string): Error & { code: string } {+ return Object.assign(new Error(message), { code });+}++export function getOrkasApiKey(): string {+ return loadProfiles().orkasApiCredential?.key || '';+}++export function getOrkasApiCredentialStatus(): OrkasApiCredentialStatus {+ const credential = loadProfiles().orkasApiCredential;+ if (!credential?.key) {+ return {+ configured: false,+ keyMasked: '',+ keyId: '',+ name: '',+ scopes: [],+ expiresAt: 0,+ updatedAt: 0,+ };+ }+ return {+ configured: true,+ keyMasked: credential.prefix || maskKey(credential.key),+ keyId: credential.keyId,+ name: credential.name,+ scopes: [...credential.scopes],+ expiresAt: credential.expiresAt,+ updatedAt: credential.updatedAt,+ };+}++/** Prepare a local credential; authentication happens only when a service is used. */+export function prepareOrkasApiCredential(rawApiKey: string): OrkasApiCredential {+ const apiKey = String(rawApiKey || '').trim();+ if (!apiKey) throw orkasApiCredentialError('api_key_required', 'api key required');+ if (!isBearerTokenHeaderSafe(apiKey)) {+ throw orkasApiCredentialError('invalid_api_key', 'api key contains invalid characters');+ }+ return {+ key: apiKey,+ keyId: '',+ name: '',+ prefix: maskKey(apiKey),+ scopes: [],+ expiresAt: 0,+ ownerRef: '',+ updatedAt: Date.now(),+ };+}++export function saveOrkasApiCredential(credential: OrkasApiCredential): OrkasApiCredentialStatus {+ configureAllOrkasApiServices(credential.key);+ return getOrkasApiCredentialStatus();+}++export function removeOrkasApiCredential(): { removed: boolean } {+ const store = loadProfiles({ throwOnInvalidExisting: true });+ const removed = !!store.orkasApiCredential+ || Object.values(store.profiles).some((profile) => profile.provider === ORKAS_API_PROVIDER)+ || (store.searchProfiles || []).some((profile) => profile.provider === ORKAS_API_PROVIDER)+ || (store.imageProfiles || []).some((profile) => profile.provider === ORKAS_API_PROVIDER)+ || (store.videoProfiles || []).some((profile) => profile.provider === ORKAS_API_PROVIDER)+ || (store.ttsProfiles || []).some((profile) => profile.provider === ORKAS_API_PROVIDER);+ const removedProfileIds = new Set(+ Object.entries(store.profiles)+ .filter(([, profile]) => profile.provider === ORKAS_API_PROVIDER)+ .map(([profileId]) => profileId),+ );+ for (const profileId of removedProfileIds) {+ delete store.profiles[profileId];+ clearCooldown(profileId);+ }+ store.entries = store.entries.filter((entry) => (+ entry.provider !== ORKAS_API_PROVIDER && !removedProfileIds.has(entry.profileId)+ ));+ store.searchProfiles = (store.searchProfiles || []).filter((profile) => profile.provider !== ORKAS_API_PROVIDER);+ store.imageProfiles = (store.imageProfiles || []).filter((profile) => profile.provider !== ORKAS_API_PROVIDER);+ store.videoProfiles = (store.videoProfiles || []).filter((profile) => profile.provider !== ORKAS_API_PROVIDER);+ store.ttsProfiles = (store.ttsProfiles || []).filter((profile) => profile.provider !== ORKAS_API_PROVIDER);+ delete store.orkasApiCredential;+ if (removed) {+ saveProfiles(store);+ invalidateCoreAgentRunner();+ }+ return { removed };+}+function saveProfiles(store: ProfilesFile): void {const localId = getActiveUserId();const target = userAuthProfilesFile(localId);diff --git a/src/main/features/client_config.ts b/src/main/features/client_config.tsindex 2b661033..1bdd472f 100644--- a/src/main/features/client_config.ts+++ b/src/main/features/client_config.ts@@ -532,6 +532,31 @@ export interface GoogleConnectorsConfig {gmail: ConnectorSwitchState;}+export interface ServerComposioConnectorConfig {+ id: string;+ display_name: string;+ icon_svg?: string;+ category: 'developer' | 'productivity' | 'communication' | 'search' | 'data' | 'commerce';+ description_zh: string;+ description_en: string;+ description_ja?: string;+ description_pt?: string;+ requires_credits: true;+ auth_mode: 'composio';+ composio: {+ toolkit: string;+ auth_config_id: string;+ tools?: Array<{+ slug: string;+ name?: string;+ description?: string;+ input_schema?: Record<string, unknown>;+ }>;+ };+ transport_template: null;+ usage_metering: { provider: 'composio'; credits_milli_per_call: number };+}+export interface AppUpdatePolicyConfig {min_version: string;}@@ -779,6 +804,79 @@ function mergeGoogleConnectorsConfig(baseRaw: unknown, overrideRaw: unknown): Go};}+const CONNECTOR_CATEGORIES = new Set([+ 'developer', 'productivity', 'communication', 'search', 'data', 'commerce',+]);++function normalizeServerComposioConnector(raw: unknown): ServerComposioConnectorConfig | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const value = raw as Record<string, unknown>;+ const id = typeof value.id === 'string' ? value.id.trim().toLowerCase() : '';+ const category = typeof value.category === 'string' ? value.category.trim() : '';+ if (!/^[a-z0-9][a-z0-9_-]{1,62}$/.test(id) || !CONNECTOR_CATEGORIES.has(category)) return null;+ if (value.auth_mode !== 'composio') return null;+ const composio = value.composio && typeof value.composio === 'object' && !Array.isArray(value.composio)+ ? value.composio as Record<string, unknown>+ : value;+ const toolkit = typeof composio.toolkit === 'string' ? composio.toolkit.trim().toLowerCase() : '';+ const authConfigId = typeof composio.auth_config_id === 'string' ? composio.auth_config_id.trim() : '';+ if (!/^[a-z0-9][a-z0-9_-]{0,80}$/.test(toolkit) || !/^ac_[A-Za-z0-9_-]{6,}$/.test(authConfigId)) {+ return null;+ }+ const tools = Array.isArray(composio.tools)+ ? composio.tools.flatMap((item) => {+ if (!item || typeof item !== 'object' || Array.isArray(item)) return [];+ const tool = item as Record<string, unknown>;+ const slug = typeof tool.slug === 'string' ? tool.slug.trim() : '';+ if (!/^[A-Za-z0-9_.:-]{1,160}$/.test(slug)) return [];+ return [{+ slug,+ ...(typeof tool.name === 'string' && tool.name.trim() ? { name: tool.name.trim() } : {}),+ ...(typeof tool.description === 'string' && tool.description.trim()+ ? { description: tool.description.trim() }+ : {}),+ ...(tool.input_schema && typeof tool.input_schema === 'object' && !Array.isArray(tool.input_schema)+ ? { input_schema: tool.input_schema as Record<string, unknown> }+ : {}),+ }];+ })+ : [];+ return {+ id,+ display_name: typeof value.display_name === 'string' && value.display_name.trim()+ ? value.display_name.trim()+ : id,+ ...(typeof value.icon_svg === 'string' && value.icon_svg.trim() ? { icon_svg: value.icon_svg.trim() } : {}),+ category: category as ServerComposioConnectorConfig['category'],+ description_zh: typeof value.description_zh === 'string' ? value.description_zh.trim() : '',+ description_en: typeof value.description_en === 'string' ? value.description_en.trim() : '',+ ...(typeof value.description_ja === 'string' ? { description_ja: value.description_ja.trim() } : {}),+ ...(typeof value.description_pt === 'string' ? { description_pt: value.description_pt.trim() } : {}),+ requires_credits: true,+ auth_mode: 'composio',+ composio: { toolkit, auth_config_id: authConfigId, ...(tools.length ? { tools } : {}) },+ transport_template: null,+ usage_metering: { provider: 'composio', credits_milli_per_call: 250 },+ };+}++function normalizeServerComposioCatalog(raw: unknown): ServerComposioConnectorConfig[] {+ if (!Array.isArray(raw)) return [];+ const byId = new Map<string, ServerComposioConnectorConfig>();+ for (const item of raw) {+ const entry = normalizeServerComposioConnector(item);+ if (entry) byId.set(entry.id, entry);+ }+ return Array.from(byId.values());+}++function mergeServerComposioCatalog(baseRaw: unknown, overrideRaw: unknown): ServerComposioConnectorConfig[] {+ const byId = new Map<string, ServerComposioConnectorConfig>();+ for (const entry of normalizeServerComposioCatalog(baseRaw)) byId.set(entry.id, entry);+ for (const entry of normalizeServerComposioCatalog(overrideRaw)) byId.set(entry.id, entry);+ return Array.from(byId.values());+}+function normalizeAppUpdatePolicyConfig(raw: unknown): Partial<AppUpdatePolicyConfig> {if (typeof raw === 'string') return { min_version: raw.trim() };if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};@@ -886,6 +984,11 @@ clientConfig.registerDefault<GoogleConnectorsConfig>('google_connectors', DEFAULmerge: mergeGoogleConnectorsConfig,});+clientConfig.registerDefault<ServerComposioConnectorConfig[]>('connectors.catalog', [], {+ effect: 'immediate',+ merge: mergeServerComposioCatalog,+});+clientConfig.registerDefault<boolean>('model.deepseek.enabled', true, {effect: 'immediate',});@@ -945,6 +1048,10 @@ export function getGoogleConnectorsConfig(): GoogleConnectorsConfig {);}+export function getServerConnectorCatalogConfig(): ServerComposioConnectorConfig[] {+ return mergeServerComposioCatalog([], clientConfig.get('connectors.catalog', []));+}+export function isDeepSeekModelConfigEnabled(): boolean {return clientConfig.get<boolean>('model.deepseek.enabled', true) !== false;}diff --git a/src/main/features/connectors/_server_bridge.ts b/src/main/features/connectors/_server_bridge.tsindex 946abd68..cd1c80a5 100644--- a/src/main/features/connectors/_server_bridge.ts+++ b/src/main/features/connectors/_server_bridge.ts@@ -4,12 +4,13 @@* PC's `features/connectors/oauth*.ts` reaches into `features/account/{server,token_store}` for:* - `accountApiBase()` — the Orkas global prod Server base URL* - `tokenStore.getDeviceId()` — stable per-machine UUID- * - `tokenStore.authHeaders()` — `{user_id, session_id}` for the logged-in user+ * - `tokenStore.authHeaders()` — `{user_id, session_id}` for the logged-in PC user** `features/account/` is stripped from the public build (no account backend). Connectors still* need the first two pieces for the pinned global HTTPS callback/bridge. Server-bridge exchange* and refresh accept `channel=open` plus this stable device id; the third piece is always empty- * because this build never has an Orkas account session.+ * because this build never has an Orkas account session. Paid connector routes add the user's+ * separately stored Orkas API Key in their own connector modules.** Where each piece comes from:* - `accountApiBase` aliases `features/marketplace.apiBase()` (global prod only — singlediff --git a/src/main/features/connectors/api-key.ts b/src/main/features/connectors/api-key.tsnew file mode 100644index 00000000..549ca80d--- /dev/null+++ b/src/main/features/connectors/api-key.ts@@ -0,0 +1,20 @@+import { getOrkasApiKey } from '../auth';++export class OrkasApiCredentialRequiredError extends Error {+ readonly code = 'orkas_api_key_required';++ constructor(message = 'Configure an Orkas API Key before using this connector.') {+ super(message);+ this.name = 'OrkasApiCredentialRequiredError';+ }+}++export function requireConnectorApiKey(): string {+ const key = getOrkasApiKey();+ if (!key) throw new OrkasApiCredentialRequiredError();+ return key;+}++export function connectorApiKeyHeaders(): Record<string, string> {+ return { Authorization: `Bearer ${requireConnectorApiKey()}` };+}diff --git a/src/main/features/connectors/catalog.ts b/src/main/features/connectors/catalog.tsindex 791be9f3..a9f46597 100644--- a/src/main/features/connectors/catalog.ts+++ b/src/main/features/connectors/catalog.ts@@ -13,6 +13,7 @@* call surfaces a 401.*/import { GOOGLE_ENTRIES } from './catalog-google';+import { getServerConnectorCatalogConfig } from '../client_config';import type { CatalogEntry } from './types';export const CONNECTOR_CATALOG: CatalogEntry[] = [@@ -240,7 +241,13 @@ export const CONNECTOR_CATALOG: CatalogEntry[] = [];export function connectorCatalog(): CatalogEntry[] {- return CONNECTOR_CATALOG;+ const byId = new Map(CONNECTOR_CATALOG.map((entry) => [entry.id, entry]));+ for (const entry of getServerConnectorCatalogConfig()) {+ const existing = byId.get(entry.id);+ if (existing && existing.auth_mode !== 'composio') continue;+ byId.set(entry.id, existing ? { ...existing, ...entry } : entry);+ }+ return Array.from(byId.values());}export function findCatalogEntry(id: string): CatalogEntry | null {diff --git a/src/main/features/connectors/index.ts b/src/main/features/connectors/index.tsindex cee537a0..1207c8e6 100644--- a/src/main/features/connectors/index.ts+++ b/src/main/features/connectors/index.ts@@ -6,6 +6,7 @@ export {connectViaOAuth,addCustomInstance,removeInstance,+ removeApiKeyConnectors,refreshTools,verifyUsableConnectors,setEnabledSubtools,@@ -16,8 +17,8 @@ export {export { CustomTransportError } from './custom-transport';export { resolveVisibleConnectors, stringifyMcpResult } from './tools-adapter';export { isValidInstanceId } from './registry';-export { CONNECTOR_CATALOG, findCatalogEntry } from './catalog';-export { handleCallbackUrl, cancelInFlightOAuth, startGoogleSheetsPicker } from './oauth';+export { CONNECTOR_CATALOG, connectorCatalog, findCatalogEntry } from './catalog';+export { handleCallbackUrl, cancelInFlightOAuth, startComposioConnect, startGoogleSheetsPicker } from './oauth';export { handleDcrCallbackUrl } from './oauth-dcr';export type {Transport,@@ -31,4 +32,6 @@ export type {TransportTemplate,OAuthConfig,OAuthGrant,+ ComposioConfig,+ ComposioGrant,} from './types';diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.tsindex 8951a386..616bcb26 100644--- a/src/main/features/connectors/manager.ts+++ b/src/main/features/connectors/manager.ts@@ -7,29 +7,36 @@* so stdio subprocesses exit instead of leaking. Tool calls route here from the AgentRunner's* meta-tools via `tools-adapter.ts`.*- * Every instance uses OAuth — there is no API-key path. The `connectViaOAuth` entry point runs- * the full PKCE/browser/code-exchange flow, persists the grant, applies the catalog's transport- * template (which substitutes the fresh access_token into env / headers), and brings the live- * MCP connection up. Tokens are lazily refreshed at boot / refresh-tools / reconnect; mid-call- * expiry surfaces as a tool error and the user re-clicks "刷新工具".+ * Provider OAuth grants and API-key-backed Composio grants share `connectViaOAuth`. The manager+ * persists only opaque grants, applies the catalog transport, and brings the live MCP connection+ * up. Tokens are lazily refreshed at boot / refresh-tools / reconnect; mid-call expiry surfaces+ * as a tool error and the user re-clicks "刷新工具".*/import * as crypto from 'node:crypto';+import * as path from 'node:path';+import { app } from 'electron';import * as registry from './registry';+import * as paths from '../../paths';import { McpConnection } from './mcp-client';import { findCatalogEntry } from './catalog';import { applyTemplate } from './apply-template';import { assertConnectorRuntimeEnabled, isConnectorRuntimeEnabled } from './availability';-import { startOAuth, refreshIfStale, startGoogleSheetsPicker } from './oauth';+import { startComposioConnect, startOAuth, refreshIfStale, startGoogleSheetsPicker } from './oauth';import { startMcpDcrOAuth, refreshDcrIfStale } from './oauth-dcr';import { createLogger } from '../../logger';import { logErrorSummary } from '../../util/log-redact';import { resolveBackgroundNodeRuntime, withBackgroundNodeEnv } from '../../util/background-node';+import { fetchWithTimeout } from '../../util/abort';+import { commonHeaders, withCommonHeaders } from '../api_common';+import { accountApiBase } from './_server_bridge';+import { connectorApiKeyHeaders } from './api-key';+import { preflightConnectorCredits } from './usage-metering';import { registerUserSwitchHook } from '../user-switch-hooks';import { broadcastOAuthConnectOutcome } from './oauth-events';import { deriveCustomId, validateCustomTransport, validateDisplayName, type CustomConnectorInput } from './custom-transport';import { isConnectorUsable } from './types';-import type { CatalogEntry, ConnectorInstance, OAuthGrant, ToolSchema, Transport } from './types';+import type { CatalogEntry, ComposioGrant, ConnectorInstance, OAuthGrant, ToolSchema, Transport } from './types';const log = createLogger('connectors:manager');@@ -114,6 +121,7 @@ const BOOTSTRAP_CONNECT_CONCURRENCY = 3;const VERIFY_TTL_MS = 5 * 60 * 1000;const RETRY_BACKOFF_BASE_MS = 30 * 1000;const RETRY_BACKOFF_MAX_MS = 30 * 60 * 1000;+const COMPOSIO_CALL_TOOL_TIMEOUT_MS = 110 * 1000;type StatusPatchCollector = Map<string, registry.ConnectorInstancePatch[]>;@@ -149,6 +157,71 @@ function _tokPrefix(t: string | null | undefined): string {return crypto.createHash('sha256').update(t).digest('hex').slice(0, 12);}+function _pcDirForChild(): string {+ return app?.isPackaged+ ? paths.PC_ROOT.replace(/\bapp\.asar\b/, 'app.asar.unpacked')+ : paths.PC_ROOT;+}++function _composioTransport(inst: ConnectorInstance): Transport {+ if (!inst.composio_grant?.connection_id) throw new Error('no composio_grant');+ const nodeRuntime = resolveBackgroundNodeRuntime();+ return {+ kind: 'stdio',+ command: nodeRuntime.executable,+ args: [path.join(_pcDirForChild(), 'bin/composio-mcp-server.cjs')],+ proxyTargetUrl: accountApiBase(),+ env: withBackgroundNodeEnv({+ ORKAS_API_BASE: accountApiBase(),+ ORKAS_API_KEY: connectorApiKeyHeaders().Authorization.slice('Bearer '.length),+ ORKAS_CLIENT_HEADERS_JSON: JSON.stringify(commonHeaders()),+ COMPOSIO_CONNECTION_ID: inst.composio_grant.connection_id,+ COMPOSIO_CONNECTOR_ID: inst.id,+ }, nodeRuntime),+ };+}++function _composioInstanceDraft(entry: CatalogEntry, grant: ComposioGrant): ConnectorInstance {+ const nodeRuntime = resolveBackgroundNodeRuntime();+ const draft: ConnectorInstance = {+ id: entry.id,+ display_name: entry.display_name,+ transport: {+ kind: 'stdio',+ command: nodeRuntime.executable,+ args: [path.join(_pcDirForChild(), 'bin/composio-mcp-server.cjs')],+ env: {},+ },+ enabled_subtools: null,+ tools_cache: [],+ tools_cached_at: 0,+ status: { kind: 'connecting' },+ composio_grant: grant,+ created_at: _nowIso(),+ updated_at: _nowIso(),+ };+ draft.transport = _composioTransport(draft);+ return draft;+}++async function _deleteComposioConnectionOnServer(id: string): Promise<void> {+ if (findCatalogEntry(id)?.auth_mode !== 'composio') return;+ try {+ const response = await fetchWithTimeout(`${accountApiBase()}/connectors/composio/disconnect`, {+ method: 'POST',+ headers: withCommonHeaders({+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ ...connectorApiKeyHeaders(),+ }),+ body: JSON.stringify({ connector_id: id }),+ }, 60_000, undefined, 'Composio disconnect timed out after 60s');+ if (!response.ok) log.warn('Composio disconnect failed', { id, status: response.status });+ } catch (err) {+ log.warn('Composio disconnect failed', { id, error: logErrorSummary(err) });+ }+}+function _missingRequiredScopes(entry: CatalogEntry, grant: OAuthGrant | undefined): string[] {const required = Array.isArray(entry.required_oauth_scopes) ? entry.required_oauth_scopes : [];if (!required.length || !grant) return [];@@ -639,6 +712,9 @@ async function _resolveTransport(uid: string, inst: ConnectorInstance): Promise<log.warn('catalog entry missing for instance', { id: inst.id });return null;}+ if (entry.auth_mode === 'composio') {+ return { transport: _composioTransport(inst), grant: null };+ }if (!inst.oauth_grant) {log.warn('instance has no oauth_grant', { id: inst.id });return null;@@ -998,9 +1074,9 @@ export function getInstance(uid: string, id: string): ConnectorInstance | null {return inst;}-/** Drive the full OAuth flow for a catalog entry and bring the resulting MCP connection up.- * This is the **only** public install path — there is no free-form / API-key entry point.- * Dispatches to server-bridge or DCR depending on `entry.auth_mode`. */+/** Drive the provider authorization flow for a catalog entry and bring its MCP connection up.+ * Composio rows use the shared Orkas API Key for the Server hop; ordinary rows dispatch to the+ * existing server-bridge or DCR provider flow. */export async function connectViaOAuth(uid: string,catalogId: string,@@ -1010,8 +1086,16 @@ export async function connectViaOAuth(const entry = findCatalogEntry(catalogId);if (!entry) throw new Error('unknown catalog id');assertConnectorRuntimeEnabled(catalogId);+ await preflightConnectorCredits(entry, 'connect');log.info('connectViaOAuth: starting OAuth', { catalog_id: catalogId, auth_mode: entry.auth_mode });+ if (entry.auth_mode === 'composio') {+ const composioGrant = await startComposioConnect(+ entry,+ opts.attemptId ? { attemptId: opts.attemptId } : {},+ );+ return _provisionComposioInstance(uid, entry, composioGrant);+ }let grant: OAuthGrant;let dcrClient: ConnectorInstance['dcr_client'];if (entry.auth_mode === 'mcp_dcr') {@@ -1138,6 +1222,22 @@ export function beginOAuthConnect(uid: string, catalogId: string): OAuthConnectSreturn { attempt_id: attemptId };}+async function _provisionComposioInstance(+ uid: string,+ entry: CatalogEntry,+ grant: ComposioGrant,+): Promise<ConnectorInstance> {+ const runtimeKey = _runtimeKey(uid, entry.id);+ const prior = _conns.get(runtimeKey);+ if (prior) {+ try { await prior.close(); } catch { /* swallow */ }+ _conns.delete(runtimeKey);+ }+ const draft = _composioInstanceDraft(entry, grant);+ await registry.upsert(uid, draft);+ return _connectAndCacheTools(uid, draft);+}+/** Provision (or replace) a single instance for a non-bundle catalog entry. Pulled out of* `connectViaOAuth` so the bundle branch can loop over members. Caller has already obtained* the OAuth grant. */@@ -1229,7 +1329,9 @@ export async function addCustomInstance(uid: string, input: CustomConnectorInputreturn _connectAndCacheTools(uid, draft);}-export async function removeInstance(uid: string, id: string): Promise<boolean> {+export async function removeInstance(+ uid: string, id: string, options: { disconnectRemote?: boolean } = {},+): Promise<boolean> {if (!uid) return false;const runtimeKey = _runtimeKey(uid, id);const conn = _conns.get(runtimeKey);@@ -1237,15 +1339,31 @@ export async function removeInstance(uid: string, id: string): Promise<boolean>try { await conn.close(); } catch { /* swallow */ }_conns.delete(runtimeKey);}+ if (options.disconnectRemote !== false) await _deleteComposioConnectionOnServer(id);return registry.remove(uid, id);}+/** Clear local API-key connections without network access when changing credentials. */+export async function removeApiKeyConnectors(uid: string): Promise<number> {+ if (!uid) return 0;+ const ids = Object.values(registry.load(uid).connections)+ .filter((instance) => findCatalogEntry(instance.id)?.auth_mode === 'composio')+ .map((instance) => instance.id);+ let removed = 0;+ for (const id of ids) {+ if (await removeInstance(uid, id, { disconnectRemote: false })) removed += 1;+ }+ return removed;+}+export async function refreshTools(uid: string, id: string): Promise<ToolSchema[]> {if (!uid) throw new Error('uid required');assertConnectorRuntimeEnabled(id);const inst = getInstance(uid, id);if (!inst) throw new Error('instance not found');if (registry.hasUnavailableSecrets(inst)) throw _secretsUnavailableError(id);+ const entry = findCatalogEntry(id);+ if (entry) await preflightConnectorCredits(entry, 'tool_call');// Force refresh-token check by tearing the live conn down and reconnecting through// _connectAndCacheTools (which re-resolves transport with a fresh access_token).const runtimeKey = _runtimeKey(uid, id);@@ -1311,6 +1429,8 @@ export async function callTool(const inst = getInstance(uid, id);if (!inst) throw new Error('instance not found');if (registry.hasUnavailableSecrets(inst)) throw _secretsUnavailableError(id);+ const entry = findCatalogEntry(id);+ if (entry) await preflightConnectorCredits(entry, 'tool_call');const runtimeKey = _runtimeKey(uid, id);const liveConn = _conns.get(runtimeKey);const grantForCooldown = inst.oauth_grant;@@ -1366,8 +1486,12 @@ export async function callTool(}const startedAt = Date.now();try {- const result = opts.signal- ? await conn.callTool(name, args, { signal: opts.signal })+ const requestOpts = {+ ...(opts.signal ? { signal: opts.signal } : {}),+ ...(inst.composio_grant ? { timeoutMs: COMPOSIO_CALL_TOOL_TIMEOUT_MS } : {}),+ };+ const result = Object.keys(requestOpts).length+ ? await conn.callTool(name, args, requestOpts): await conn.callTool(name, args);log.info('connector tool call completed', {id,@@ -1378,7 +1502,6 @@ export async function callTool(} catch (err) {const cancelled = opts.signal?.aborted || (err as Error)?.name === 'AbortError';const transient = !cancelled && _isTransientConnectorFailure(err);- const entry = findCatalogEntry(id);const hardAuth = !cancelled && !!entry&& (_isGoogleAuthFailure(entry, err) || _isDcrAuthFailure(entry, err));if (cancelled || transient || hardAuth) {diff --git a/src/main/features/connectors/oauth.ts b/src/main/features/connectors/oauth.tsindex 785fd2a6..24c18ad0 100644--- a/src/main/features/connectors/oauth.ts+++ b/src/main/features/connectors/oauth.ts@@ -32,8 +32,10 @@ import { withCommonHeaders } from '../api_common';import { getLanguage } from '../config';import { createLogger } from '../../logger';import { fetchWithTimeout } from '../../util/abort';+import { safeExternalHttpUrl } from '../../util/window-security';import { broadcastOAuthConnectProgress } from './oauth-events';-import type { CatalogEntry, OAuthGrant } from './types';+import { connectorApiKeyHeaders } from './api-key';+import type { CatalogEntry, ComposioGrant, OAuthGrant } from './types';const log = createLogger('connectors:oauth');@@ -46,11 +48,11 @@ const OAUTH_RETRY_MAX_ATTEMPTS = 3;const OAUTH_RETRY_BASE_DELAY_MS = 400;interface PendingFlow {- kind: 'connector_oauth' | 'google_picker';+ kind: 'connector_oauth' | 'google_picker' | 'composio';catalogId: string;attemptId?: string;requiredScopes: string[];- resolve: (result: OAuthGrant | GooglePickerResult) => void;+ resolve: (result: OAuthGrant | GooglePickerResult | ComposioGrant) => void;reject: (err: Error) => void;timer: NodeJS.Timeout;}@@ -84,6 +86,18 @@ function _exchangeHttpCode(status: number): string {return _isRetryableBridgeStatus(status) ? 'exchange_http_5xx' : 'exchange_http_4xx';}+function _parseJsonObject(raw: string): Record<string, any> {+ if (!raw) return {};+ try {+ const parsed = JSON.parse(raw);+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)+ ? parsed as Record<string, any>+ : {};+ } catch {+ return {};+ }+}+function _cancelPending(reason: string, code?: string): void {if (!_pending) return;const p = _pending;@@ -152,6 +166,7 @@ async function postConnectorBridgeJson(label: string,url: string,body: Record<string, unknown>,+ extraHeaders: Record<string, string> = {},): Promise<Response> {for (let attempt = 1; attempt <= OAUTH_RETRY_MAX_ATTEMPTS; attempt += 1) {const last = attempt === OAUTH_RETRY_MAX_ATTEMPTS;@@ -163,6 +178,7 @@ async function postConnectorBridgeJson('Content-Type': 'application/json',Accept: 'application/json',...tokenStore.authHeaders(),+ ...extraHeaders,}),body: JSON.stringify(body),});@@ -183,6 +199,56 @@ async function postConnectorBridgeJson(throw new Error(`${label} exhausted attempts`);}+/** Start the same Server-owned Composio flow used by the hosted desktop, authenticated with the+ * user-owned Orkas API Key instead of an Orkas login session. */+export async function startComposioConnect(+ entry: CatalogEntry,+ opts: { attemptId?: string } = {},+): Promise<ComposioGrant> {+ if (entry.auth_mode !== 'composio') throw new Error(`catalog entry ${entry.id} is not Composio-backed`);+ _cancelPending('superseded by a new OAuth start', 'superseded');+ const headers = connectorApiKeyHeaders();+ const res = await postConnectorBridgeJson(+ 'Composio connector start',+ `${accountApiBase()}/connectors/composio/start`,+ {+ catalog_id: entry.id,+ device_id: tokenStore.getDeviceId(),+ lang: getLanguage(),+ },+ headers,+ );+ const raw = await res.text();+ const body = _parseJsonObject(raw);+ if (!res.ok || Number(body.code || 0) !== 0 || typeof body.redirect_url !== 'string') {+ const nested = body.error && typeof body.error === 'object' && !Array.isArray(body.error)+ ? body.error as Record<string, unknown>+ : {};+ throw _flowError(+ String(nested.message || body.msg || `Composio start HTTP ${res.status}`),+ String(nested.code || 'composio_start_failed'),+ );+ }+ const redirectUrl = safeExternalHttpUrl(body.redirect_url);+ if (!redirectUrl) throw _flowError('invalid Composio redirect URL', 'invalid_redirect_url');+ return new Promise<ComposioGrant>((resolve, reject) => {+ const timer = setTimeout(() => _cancelPending('OAuth flow timed out', 'flow_timeout'), FLOW_TIMEOUT_MS);+ timer.unref?.();+ _pending = {+ kind: 'composio',+ catalogId: entry.id,+ ...(opts.attemptId ? { attemptId: opts.attemptId } : {}),+ requiredScopes: [],+ resolve: resolve as PendingFlow['resolve'],+ reject,+ timer,+ };+ shell.openExternal(redirectUrl).catch((err) => {+ _cancelPending(`failed to open browser: ${(err as Error).message}`, 'browser_open_failed');+ });+ });+}+/** 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 {@@ -304,6 +370,38 @@ export async function handleCallbackUrl(rawUrl: string): Promise<void> {}try {+ if (pending.kind === 'composio') {+ const res = await postConnectorBridgeJson(+ 'Composio connector exchange',+ `${accountApiBase()}/connectors/composio/exchange`,+ { exchange_code: exchangeCode, device_id: tokenStore.getDeviceId() },+ connectorApiKeyHeaders(),+ );+ const raw = await res.text();+ const body = _parseJsonObject(raw);+ if (!res.ok || Number(body.code || 0) !== 0) {+ throw _flowError(+ String(body.msg || `Composio exchange HTTP ${res.status}`),+ _exchangeHttpCode(res.status),+ );+ }+ const connectionId = String(body.connection_id || '');+ const toolkit = String(body.toolkit || '');+ const authConfigId = String(body.auth_config_id || '');+ if (!connectionId || !toolkit || !authConfigId) {+ throw _flowError('invalid Composio exchange response', 'invalid_exchange_response');+ }+ const grant: ComposioGrant = {+ connection_id: connectionId,+ toolkit,+ auth_config_id: authConfigId,+ ...(body.account_label ? { account_label: String(body.account_label) } : {}),+ };+ _pending = null;+ clearTimeout(pending.timer);+ pending.resolve(grant);+ return;+ }const res = await postConnectorBridgeJson('connector OAuth exchange',`${accountApiBase()}/connectors/oauth/exchange`,diff --git a/src/main/features/connectors/types.ts b/src/main/features/connectors/types.tsindex d14e6f1d..8ba6c7b8 100644--- a/src/main/features/connectors/types.ts+++ b/src/main/features/connectors/types.ts@@ -110,6 +110,7 @@ export interface ConnectorInstance {* reconnect. Refreshed on every successful `list_tools` call. */tools_cache: ToolSchema[];tools_cached_at: number;+ tools_cache_key?: string;status: ConnectorStatus;/** Sticky non-sensitive auth failure marker. When a provider has definitively* rejected a grant, boot/list/refresh paths must not keep retrying it. */@@ -122,6 +123,8 @@ export interface ConnectorInstance {* stores this with the grant inside the encrypted local registry and never uploads it to the* Orkas account service. */dcr_client?: DcrClientCredentials;+ /** Opaque Server connection handle. Provider credentials never leave Composio/Orkas Server. */+ composio_grant?: ComposioGrant;created_at: string;updated_at: string;}@@ -232,14 +235,40 @@ export interface OAuthGrant {account_label?: string;}+export interface ComposioGrant {+ connection_id: string;+ toolkit: string;+ auth_config_id: string;+ account_label?: string;+}++export interface ComposioToolConfig {+ slug: string;+ name?: string;+ description?: string;+ input_schema?: Record<string, unknown>;+}++export interface ComposioConfig {+ toolkit: string;+ auth_config_id: string;+ tools?: ComposioToolConfig[];+}++export interface ConnectorUsageMetering {+ provider: 'composio';+ credits_milli_per_call: number;+}+export type CatalogCategory =| 'developer'| 'productivity'| 'communication'| 'search'- | 'data';+ | 'data'+ | 'commerce';-export type AuthMode = 'server_bridge' | 'mcp_dcr';+export type AuthMode = 'server_bridge' | 'mcp_dcr' | 'composio';export interface CatalogEntry {/** Stable id; doubles as the installed instance id (one install per catalog entry in Phase 0).@@ -257,10 +286,15 @@ export interface CatalogEntry {category: CatalogCategory;description_zh: string;description_en: string;+ description_ja?: string;+ description_pt?: string;+ requires_credits?: boolean;/** Which OAuth pathway this provider needs — see the `// ── OAuth ──` section above. */auth_mode: AuthMode;/** Required when `auth_mode === 'server_bridge'`; absent for `'mcp_dcr'` (no pre-registration). */oauth?: OAuthConfig;+ composio?: ComposioConfig;+ usage_metering?: ConnectorUsageMetering;/** OAuth scopes that must be present in the provider's returned grant for the connector to* function. Google lets users uncheck individual requested permissions on the consent screen;* when that happens the token exchange still succeeds but downstream APIs fail with 403s.diff --git a/src/main/features/connectors/usage-metering.ts b/src/main/features/connectors/usage-metering.tsnew file mode 100644index 00000000..792436c5--- /dev/null+++ b/src/main/features/connectors/usage-metering.ts@@ -0,0 +1,59 @@+import { fetchWithTimeout } from '../../util/abort';+import { withCommonHeaders } from '../api_common';+import { accountApiBase } from './_server_bridge';+import { connectorApiKeyHeaders } from './api-key';+import type { CatalogEntry, ConnectorUsageMetering } from './types';++export const COMPOSIO_CONNECTOR_CREDITS_MILLI_PER_CALL = 250;+export type ConnectorUsageStage = 'connect' | 'tool_call';++export function usageMeteringForEntry(entry: CatalogEntry | null | undefined): ConnectorUsageMetering | null {+ const metering = entry?.usage_metering || null;+ if (!metering || metering.provider !== 'composio') return null;+ const creditsMilli = Number(metering.credits_milli_per_call || COMPOSIO_CONNECTOR_CREDITS_MILLI_PER_CALL);+ if (!Number.isFinite(creditsMilli) || creditsMilli <= 0) return null;+ return { ...metering, credits_milli_per_call: Math.floor(creditsMilli) };+}++function parseJson(text: string): Record<string, unknown> {+ try {+ const body = JSON.parse(text);+ return body && typeof body === 'object' && !Array.isArray(body) ? body : {};+ } catch {+ return {};+ }+}++export async function preflightConnectorCredits(+ entry: CatalogEntry,+ stage: ConnectorUsageStage,+ calls = 1,+): Promise<Record<string, unknown> | null> {+ const metering = usageMeteringForEntry(entry);+ if (!metering) return null;+ const response = await fetchWithTimeout(`${accountApiBase()}/connectors/usage/preflight`, {+ method: 'POST',+ headers: withCommonHeaders({+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ ...connectorApiKeyHeaders(),+ }),+ body: JSON.stringify({+ provider: metering.provider,+ connector_id: entry.id,+ stage,+ calls: Math.max(1, Math.floor(Number(calls) || 1)),+ }),+ }, 60_000, undefined, 'connector usage preflight timed out after 60s');+ const body = parseJson(await response.text());+ if (!response.ok || Number(body.code || 0) !== 0) {+ const nested = body.error && typeof body.error === 'object' && !Array.isArray(body.error)+ ? body.error as Record<string, unknown>+ : {};+ const error = new Error(String(nested.message || body.msg || 'Connector credit check failed')) as Error & { code?: string };+ const code = String(nested.code || '').trim();+ if (/^[A-Za-z0-9_.:-]{1,80}$/.test(code)) error.code = code;+ throw error;+ }+ return body;+}diff --git a/src/main/features/users.ts b/src/main/features/users.tsindex 507b2d68..bcddf15b 100644--- a/src/main/features/users.ts+++ b/src/main/features/users.ts@@ -11,8 +11,9 @@* - `anonymous` while logged out.* - the server account uid while logged in.*- * the open-source build still calls `initActiveUser()` without options, so first boot- * creates a random 32-character local id.+ * Open-source boot uses `open-users.json::open_current_user_id`. The shared+ * registry is only a read-only source for the first migration; hosted markers+ * cause a fresh 32-character local id instead of adopting another product's data.** Boot sequence:* 1. Read users.json; if absent, create the first profile id and point the@@ -31,6 +32,7 @@ import * as path from 'node:path';import {USERS_FILE,+ OPEN_USERS_FILE,WS_ROOT,userLocalConfigDir,userToolResultsDir,@@ -67,7 +69,9 @@ interface UsersRegistry {}export interface InitActiveUserOptions {- /** Hosted Orkas passes `anonymous`; the open-source build omits this and gets a generated 32-character uid. */+ /** Use the independent open-source registry and migrate compatible legacy profiles. */+ openSource?: boolean;+ /** Hosted Orkas passes `anonymous`; open-source first boot generates a 32-character uid. */defaultLocalId?: string;}@@ -91,6 +95,7 @@ export interface LegacyAccountLocalIdMigrationResult {let ACTIVE_UID: string | null = null;type CurrentUserField = 'current_user_id' | 'dev_current_user_id';let CURRENT_USER_FIELD: CurrentUserField = 'current_user_id';+let USE_OPEN_REGISTRY = false;function rollbackUserRootAfterRekeyFailure(toRoot: string, fromRoot: string): void {try {@@ -135,6 +140,7 @@ export function hasActiveUser(): boolean {// ── Registry IO ──────────────────────────────────────────────────────────function readRegistry(): UsersRegistry | null {+ if (USE_OPEN_REGISTRY) return readOpenRegistry();if (!fs.existsSync(USERS_FILE)) return null;const data = readJsonSync<Partial<UsersRegistry>>(USERS_FILE);if (!data || typeof data !== 'object') return null;@@ -180,9 +186,64 @@ function isValidRecord(v: unknown): v is UserRecord {}function writeRegistry(reg: UsersRegistry): void {+ if (USE_OPEN_REGISTRY) {+ writeJsonSync(OPEN_USERS_FILE, {+ open_current_user_id: reg.current_user_id,+ users: reg.users,+ });+ return;+ }writeJsonSync(USERS_FILE, reg);}+/** Inspect format markers only; never decrypt or rewrite a hosted user's secrets. */+function hasHostedProfileData(uid: string): boolean {+ if (uid === ANONYMOUS_LOCAL_ID) return true;+ const configDir = userLocalConfigDir(uid);+ if (fs.existsSync(path.join(configDir, ACCOUNT_FILE_NAME))) return true;+ const authFile = path.join(configDir, 'auth-profiles.json');+ try {+ const fd = fs.openSync(authFile, 'r');+ try {+ const prefix = Buffer.alloc(9);+ fs.readSync(fd, prefix, 0, prefix.length, 0);+ if (prefix.toString('utf8') === 'ORKLSEC1:') return true;+ } finally { fs.closeSync(fd); }+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ throw new Error('Cannot inspect existing credentials. Restore access to the profile and restart.');+ }+ }+ return false;+}++function readOpenRegistry(): UsersRegistry | null {+ if (fs.existsSync(OPEN_USERS_FILE)) {+ let data: any;+ try { data = JSON.parse(fs.readFileSync(OPEN_USERS_FILE, 'utf8')); }+ catch { throw new Error('Cannot read the open-source user registry. Restore open-users.json and restart.'); }+ const uid = data?.open_current_user_id;+ if (!safeId(uid) || !Array.isArray(data?.users)+ || !data.users.every(isValidRecord)+ || !data.users.some((user: UserRecord) => user.user_id === uid)) {+ throw new Error('Invalid open-source user registry. Restore open-users.json and restart.');+ }+ return { current_user_id: uid, dev_current_user_id: uid, users: data.users };+ }++ // The shared registry is a read-only migration source. An absent login record+ // alone is not enough: hosted-format credentials also make a profile ineligible.+ const legacy = readJsonSync<Partial<UsersRegistry>>(USERS_FILE);+ const uid = legacy?.current_user_id;+ const record = Array.isArray(legacy?.users)+ ? legacy.users.find((user) => isValidRecord(user) && user.user_id === uid)+ : undefined;+ if (!record || !safeId(uid) || hasHostedProfileData(record.user_id)) return null;+ const reg = { current_user_id: record.user_id, dev_current_user_id: record.user_id, users: [record] };+ writeRegistry(reg);+ return reg;+}+function recordForLocalId(localId: string): UserRecord {const reg = readRegistry();return reg?.users.find((u) => u.user_id === localId) || { user_id: localId, created_at: nowIso() };@@ -443,6 +504,10 @@ export function activateUser(uid: string): void {* anonymous) or generate a random 32-character uid (the open-source build).*/export function initActiveUser(opts: InitActiveUserOptions = {}): UserRecord {+ if (opts.openSource) {+ USE_OPEN_REGISTRY = true;+ CURRENT_USER_FIELD = 'current_user_id';+ }const reg = readRegistry();if (reg) {const activeUid = reg[CURRENT_USER_FIELD];diff --git a/src/main/index.ts b/src/main/index.tsindex 4236ce4e..64a77345 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -509,7 +509,7 @@ function registerIpc(): void {appRoot: paths.APP_ROOT,pcRoot: paths.PC_ROOT,wsRoot: paths.WS_ROOT,- usersFile: paths.USERS_FILE,+ usersFile: paths.OPEN_USERS_FILE,},storage: sample,prompts: {@@ -548,7 +548,7 @@ async function runBootSelfCheck(): Promise<void> {// feature touches user-scoped paths (every feature goes through// `getActiveUserId()`).try {- const rec = users.initActiveUser();+ const rec = users.initActiveUser({ openSource: true });log.info('active user', { user_id: rec.user_id });} catch (err) {log.error('failed to activate user', { error: (err as Error).message });diff --git a/src/main/ipc/connectors.ts b/src/main/ipc/connectors.tsindex f1ed77bd..01281bd3 100644--- a/src/main/ipc/connectors.ts+++ b/src/main/ipc/connectors.ts@@ -10,9 +10,9 @@* connectors.refresh → { tools, instance }* connectors.set_subtools → { instance }*- * Catalog installs are OAuth-only — no API-key fallback. Server-bridge providers use an- * Orkas-registered OAuth app; MCP DCR providers issue a per-device client whose credentials stay- * in the encrypted local registry. Custom MCP servers are the separate, explicitly user-authored+ * Catalog installs use provider OAuth. Paid Composio rows authenticate Orkas Server with the+ * user's shared Orkas API Key, while ordinary server-bridge and MCP DCR providers keep their+ * existing open-device flow. Custom MCP servers are the separate, explicitly user-authored* path: `connectors.add_custom` is the single validated route* (features/connectors/custom-transport.ts), the renderer form is the consent surface, and the* stored transport lives inside `secrets_enc`. See docs/plans/open-ecosystem-architecture.md §C.@@ -23,6 +23,7 @@ import * as connectors from '../features/connectors';import type { ConnectorInstance, ConnectorStatus, ToolSchema } from '../features/connectors';import { isConnectorEnabled, setConnectorEnabled } from '../features/component_enabled';import { catalogWithAvailability, isConnectorRuntimeEnabled } from '../features/connectors/availability';+import { requireConnectorApiKey } from '../features/connectors/api-key';/*** Renderer-safe view of a connector instance. The hydrated `ConnectorInstance`@@ -89,6 +90,8 @@ function toClientInstance(inst: ConnectorInstance, enabled?: boolean): ClientCon};if (inst.oauth_grant?.account_label) {out.oauth_grant = { account_label: inst.oauth_grant.account_label };+ } else if (inst.composio_grant?.account_label) {+ out.oauth_grant = { account_label: inst.composio_grant.account_label };}if (typeof enabled === 'boolean') out.enabled = enabled;return out;@@ -96,8 +99,12 @@ function toClientInstance(inst: ConnectorInstance, enabled?: boolean): ClientConexport const _toClientInstanceForTest = toClientInstance;+export async function removeApiKeyConnectorsForCredentialChange(userId: string): Promise<number> {+ return connectors.removeApiKeyConnectors(userId);+}+export const invokeHandlers = {- 'connectors.catalog': async () => ({ catalog: catalogWithAvailability(connectors.CONNECTOR_CATALOG) }),+ 'connectors.catalog': async () => ({ catalog: catalogWithAvailability(connectors.connectorCatalog()) }),'connectors.list': async (_payload: unknown, ctx: { userId: string }) => {// Attach the per-user `enabled` flag so the renderer can render the "停用 / 启用" toggle@@ -132,6 +139,20 @@ export const invokeHandlers = {'connectors.start_oauth': async (payload: { catalog_id?: unknown }, ctx: { userId: string }) => {if (typeof payload?.catalog_id !== 'string') throw new Error('invalid catalog_id');+ const entry = connectors.findCatalogEntry(payload.catalog_id);+ if (entry?.auth_mode === 'composio' || entry?.requires_credits) {+ try {+ requireConnectorApiKey();+ } catch (err) {+ return {+ ok: false,+ code: String((err as { code?: unknown }).code || 'orkas_api_key_required'),+ error: String((err as Error).message || 'Configure an Orkas API Key first.'),+ requires_api_key: true,+ settings_tab: 'credentials',+ };+ }+ }const started = connectors.beginOAuthConnect(ctx.userId, payload.catalog_id);return { started: true, attempt_id: started.attempt_id };},diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex 08ce1fa7..36b50297 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -65,7 +65,10 @@ import {import * as userWorkspace from '../features/user_workspace';import { invokeHandlers as localAgentsHandlers } from './local_agents';import { invokeHandlers as qualityHandlers } from './quality';-import { invokeHandlers as connectorsHandlers } from './connectors';+import {+ invokeHandlers as connectorsHandlers,+ removeApiKeyConnectorsForCredentialChange,+} from './connectors';import { invokeHandlers as memoryHandlers } from './memory';import { safeId } from '../storage';import { createLogger, logFromRenderer } from '../logger';@@ -2727,6 +2730,19 @@ const invokeHandlers: Record<string, InvokeHandler> = {// ── Orkas public API key quick setup (open-source build only) ──'orkasApi.configureAll': async ({ apiKey }) => auth.configureAllOrkasApiServices(apiKey),+ 'orkasApi.getStatus': async () => auth.getOrkasApiCredentialStatus(),+ 'orkasApi.save': async ({ apiKey }, ctx) => {+ const credential = auth.prepareOrkasApiCredential(apiKey);+ const previousKey = auth.getOrkasApiKey();+ if (previousKey && previousKey !== credential.key) {+ await removeApiKeyConnectorsForCredentialChange(ctx.userId);+ }+ return auth.saveOrkasApiCredential(credential);+ },+ 'orkasApi.remove': async (_payload, ctx) => {+ await removeApiKeyConnectorsForCredentialChange(ctx.userId);+ return auth.removeOrkasApiCredential();+ },// ── Image-generation API key (independent from chat entries) ──// `list` strips raw apiKey and replaces it with `apiKeyMasked` sodiff --git a/src/main/paths.ts b/src/main/paths.tsindex 734a4a03..b0baaece 100644--- a/src/main/paths.ts+++ b/src/main/paths.ts@@ -15,6 +15,7 @@* <container>/ ← ~/.orkas (mac/linux) or <drive>:\.orkas (Windows, pinned)* data/ ← WS_ROOT* users.json ← Local uid registry + current_user_id / dev_current_user_id+ * open-users.json ← Open-source registry + open_current_user_id* window-state.json ← Last desktop window bounds (machine-local)* logs/ ← Local logs (rolled daily, global)* venv/ ← Machine-global dependency envs/caches@@ -80,6 +81,8 @@ export const WS_ROOT = path.resolve(process.env.ORKAS_WORKSPACE_ROOT);// Dev builds use dev_current_user_id so they do not overwrite the packaged// active profile pointer in the shared install-container users.json.export const USERS_FILE = path.join(WS_ROOT, 'users.json');+// OpenSource owns a separate pointer so older hosted builds cannot discard it.+export const OPEN_USERS_FILE = path.join(WS_ROOT, 'open-users.json');export const DEVICE_FILE = path.join(WS_ROOT, 'device.json');export const WINDOW_STATE_FILE = path.join(WS_ROOT, 'window-state.json');// Machine-local logs (daily rolling, single global file shared across uids).diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex 0b4581ce..a11f1499 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -1108,14 +1108,27 @@<div class="settings-group settings-orkas-api-group" id="settings-orkas-api-group"><div class="settings-group-head settings-orkas-api-head"><div class="settings-group-head-main">- <div class="settings-group-title" data-i18n="settings.orkas_api.title">Orkas official services</div>- <div class="settings-group-sub" data-i18n="settings.orkas_api.sub">Use one API Key to quickly configure models, search, images, speech, and video.</div>+ <div class="settings-group-title" data-i18n="settings.orkas_api.title">Orkas API Key</div>+ <div class="settings-group-sub" data-i18n="settings.orkas_api.sub">This shared credential is used by Orkas models, media, search, and credit-based connectors.</div></div><button type="button" class="btn btn-sm" id="settings-orkas-api-create-key" data-i18n="settings.orkas_api.create_key">Create API Key</button></div>- <div class="settings-row settings-orkas-api-configure-row">+ <div class="settings-orkas-api-saved" id="settings-orkas-api-saved" hidden>+ <div class="settings-orkas-api-key-summary">+ <code id="settings-orkas-api-key-masked"></code>+ <span class="settings-orkas-api-key-meta" id="settings-orkas-api-key-meta"></span>+ </div>+ <div class="settings-orkas-api-actions">+ <button type="button" class="btn btn-sm" id="settings-orkas-api-edit" data-i18n="settings.orkas_api.edit">Edit</button>+ <button type="button" class="btn btn-sm btn-danger" id="settings-orkas-api-delete" data-i18n="settings.orkas_api.delete">Delete</button>+ </div>+ </div>+ <div class="settings-row settings-orkas-api-configure-row" id="settings-orkas-api-editor"><input type="password" class="form-input" id="settings-orkas-api-key-input" autocomplete="new-password" spellcheck="false" data-i18n-placeholder="settings.orkas_api.key_placeholder" placeholder="Enter API Key" />- <button type="button" class="btn btn-primary" id="settings-orkas-api-configure" data-i18n="settings.orkas_api.configure">Configure</button>+ <div class="settings-orkas-api-editor-actions">+ <button type="button" class="btn" id="settings-orkas-api-cancel" data-i18n="common.cancel" hidden>Cancel</button>+ <button type="button" class="btn btn-primary" id="settings-orkas-api-configure" data-i18n="settings.orkas_api.configure">Configure</button>+ </div></div><div class="settings-status settings-orkas-api-status" id="settings-orkas-api-status" aria-live="polite"></div></div>diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex 9a2557fb..be66f56a 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -129,7 +129,9 @@"connectors.errors.connect_failed": "Authorization failed","connectors.errors.missing_required_scopes": "You did not select all required permissions. Reconnect and select every required permission on the authorization page, otherwise the connector cannot be used.","connectors.errors.storage_unavailable": "The authorization service is temporarily unavailable. Reconnect later.",+ "connectors.errors.api_key_required": "Configure an Orkas API key with connector access in the Models settings first.","connectors.errors.remove_failed": "Uninstall failed",+ "connectors.badge.credits_required": "Credits","connectors.toast.unsupported": "Not supported yet","connectors.use_label": "Connector: {connector}","connectors.inline_text": "{connector} connector",@@ -1335,16 +1337,22 @@"settings.section.general": "General","settings.section.models": "Models & credentials","settings.section.models_note": "API keys and authorization data are stored only on this device — never synced or sent elsewhere.",- "settings.orkas_api.title": "Orkas official services",- "settings.orkas_api.sub": "Use one API Key to quickly configure models, search, images, speech, and video.",+ "settings.orkas_api.title": "Orkas API Key",+ "settings.orkas_api.sub": "Shared by Orkas models, search, images, speech, video, and credit-based connectors. The key is encrypted on this device.","settings.orkas_api.create_key": "Create API Key","settings.orkas_api.key_placeholder": "Enter API Key","settings.orkas_api.configure": "Configure","settings.orkas_api.key_required": "Enter an API Key first","settings.orkas_api.configuring": "Configuring…",- "settings.orkas_api.configure_ok": "Orkas official services configured",- "settings.orkas_api.configure_failed": "Configuration failed",+ "settings.orkas_api.configure_ok": "API Key saved and verified",+ "settings.orkas_api.configure_failed": "API Key validation or save failed","settings.orkas_api.open_failed": "Could not open the API Key page",+ "settings.orkas_api.saved": "Configured",+ "settings.orkas_api.edit": "Edit",+ "settings.orkas_api.delete": "Delete",+ "settings.orkas_api.delete_confirm": "Deleting this key stops Orkas services and credit-based connectors from using it. Delete it?",+ "settings.orkas_api.delete_ok": "API Key deleted",+ "settings.orkas_api.delete_failed": "Could not delete the API Key","settings.orkas_api.recommended": "Recommended","settings.orkas_api.includes": "Includes: {models}","settings.section.tools": "Tool capabilities",diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.jsonindex a9ac11e7..e46f51a4 100644--- a/src/renderer/locales/ja.json+++ b/src/renderer/locales/ja.json@@ -129,7 +129,9 @@"connectors.errors.connect_failed": "認証に失敗しました","connectors.errors.missing_required_scopes": "必要な権限がすべて選択されていません。再接続し、認可ページで必要な権限をすべて選択してください。選択しないとコネクターは利用できません。","connectors.errors.storage_unavailable": "認証サービスは一時的に利用できません。後ほど再接続してください。",+ "connectors.errors.api_key_required": "先に設定のモデル画面でコネクター権限付きの Orkas API キーを設定してください。","connectors.errors.remove_failed": "アンインストールに失敗しました",+ "connectors.badge.credits_required": "クレジット","connectors.toast.unsupported": "現在はサポートされていません","connectors.use_label": "コネクター: {connector}","connectors.inline_text": "{connector} コネクター",@@ -1335,16 +1337,22 @@"settings.section.general": "一般","settings.section.models": "モデルと認証情報","settings.section.models_note": "API キーと認証情報はこの端末にのみ保存され、同期や外部送信はされません。",- "settings.orkas_api.title": "Orkas 公式サービス",- "settings.orkas_api.sub": "1 つの API Key でモデル、検索、画像、音声、動画をまとめて設定できます。",+ "settings.orkas_api.title": "Orkas API Key",+ "settings.orkas_api.sub": "Orkas のモデル、検索、画像、音声、動画、クレジット制コネクタで共有します。キーはこの端末で暗号化されます。","settings.orkas_api.create_key": "API Key を作成","settings.orkas_api.key_placeholder": "API Key を入力","settings.orkas_api.configure": "設定","settings.orkas_api.key_required": "先に API Key を入力してください","settings.orkas_api.configuring": "設定中…",- "settings.orkas_api.configure_ok": "Orkas 公式サービスを設定しました",- "settings.orkas_api.configure_failed": "設定に失敗しました",+ "settings.orkas_api.configure_ok": "API Key を保存して検証しました",+ "settings.orkas_api.configure_failed": "API Key の検証または保存に失敗しました","settings.orkas_api.open_failed": "API Key 作成ページを開けませんでした",+ "settings.orkas_api.saved": "設定済み",+ "settings.orkas_api.edit": "編集",+ "settings.orkas_api.delete": "削除",+ "settings.orkas_api.delete_confirm": "削除すると、Orkas サービスとクレジット制コネクタでこの API Key を使用できなくなります。削除しますか?",+ "settings.orkas_api.delete_ok": "API Key を削除しました",+ "settings.orkas_api.delete_failed": "API Key を削除できませんでした","settings.orkas_api.recommended": "おすすめ","settings.orkas_api.includes": "含まれるモデル:{models}","settings.section.tools": "ツール機能",diff --git a/src/renderer/locales/pt.json b/src/renderer/locales/pt.jsonindex 23877cbf..cf265e35 100644--- a/src/renderer/locales/pt.json+++ b/src/renderer/locales/pt.json@@ -124,7 +124,9 @@"connectors.errors.connect_failed": "Falha na autorização","connectors.errors.missing_required_scopes": "Você não selecionou todas as permissões necessárias. Reconecte e selecione todas as permissões necessárias na página de autorização, caso contrário, o conector não poderá ser usado.","connectors.errors.storage_unavailable": "O serviço de autorização está temporariamente indisponível. Reconecte mais tarde.",+ "connectors.errors.api_key_required": "Configure primeiro uma chave de API Orkas com acesso a conectores nas definições de Modelos.","connectors.errors.remove_failed": "Falha na desinstalação",+ "connectors.badge.credits_required": "Créditos","connectors.toast.unsupported": "Ainda não suportado","connectors.use_label": "Conector: {connector}","connectors.inline_text": "conector {connector}",@@ -1327,16 +1329,22 @@"settings.section.general": "Geral","settings.section.models": "Modelos e credenciais","settings.section.models_note": "As chaves de API e os dados de autorização ficam apenas neste dispositivo; não são sincronizados nem enviados para outros lugares.",- "settings.orkas_api.title": "Serviços oficiais da Orkas",- "settings.orkas_api.sub": "Use uma API Key para configurar rapidamente modelos, pesquisa, imagens, voz e vídeo.",+ "settings.orkas_api.title": "API Key da Orkas",+ "settings.orkas_api.sub": "Compartilhada por modelos, pesquisa, imagens, voz, vídeo e conectores por créditos da Orkas. A chave fica criptografada neste dispositivo.","settings.orkas_api.create_key": "Criar API Key","settings.orkas_api.key_placeholder": "Insira a API Key","settings.orkas_api.configure": "Configurar","settings.orkas_api.key_required": "Insira primeiro uma API Key","settings.orkas_api.configuring": "Configurando…",- "settings.orkas_api.configure_ok": "Serviços oficiais da Orkas configurados",- "settings.orkas_api.configure_failed": "Falha na configuração",+ "settings.orkas_api.configure_ok": "API Key salva e verificada",+ "settings.orkas_api.configure_failed": "Falha ao verificar ou salvar a API Key","settings.orkas_api.open_failed": "Não foi possível abrir a página de API Key",+ "settings.orkas_api.saved": "Configurada",+ "settings.orkas_api.edit": "Editar",+ "settings.orkas_api.delete": "Excluir",+ "settings.orkas_api.delete_confirm": "Ao excluir esta chave, os serviços da Orkas e os conectores por créditos deixarão de usá-la. Excluir?",+ "settings.orkas_api.delete_ok": "API Key excluída",+ "settings.orkas_api.delete_failed": "Não foi possível excluir a API Key","settings.orkas_api.recommended": "Recomendado","settings.orkas_api.includes": "Inclui: {models}","settings.section.tools": "Capacidades da ferramenta",diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex 466a8e25..9ca622e1 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -129,7 +129,9 @@"connectors.errors.connect_failed": "授权失败","connectors.errors.missing_required_scopes": "你未勾选该连接器所需的全部权限。请重新连接,并在授权页勾选所需权限,否则连接器无法使用。","connectors.errors.storage_unavailable": "授权服务暂时不可用,请稍后重新连接。",+ "connectors.errors.api_key_required": "请先在设置的模型页配置带连接器权限的 Orkas API Key。","connectors.errors.remove_failed": "卸载失败",+ "connectors.badge.credits_required": "积分","connectors.toast.unsupported": "暂不支持","connectors.use_label": "连接器:{connector}","connectors.inline_text": "{connector} 连接器",@@ -1335,16 +1337,22 @@"settings.section.general": "通用","settings.section.models": "模型与凭证","settings.section.models_note": "所有 API Key 与授权信息只保存在本机,不上云、不外发。",- "settings.orkas_api.title": "Orkas 官方服务",- "settings.orkas_api.sub": "一个 API Key 可快速配置模型、搜索、图片、语音和视频。",+ "settings.orkas_api.title": "Orkas API Key",+ "settings.orkas_api.sub": "统一用于 Orkas 模型、搜索、图片、语音、视频和需要积分的连接器;密钥仅加密保存在本机。","settings.orkas_api.create_key": "创建 API Key","settings.orkas_api.key_placeholder": "输入 API Key","settings.orkas_api.configure": "配置","settings.orkas_api.key_required": "请先输入 API Key","settings.orkas_api.configuring": "配置中…",- "settings.orkas_api.configure_ok": "Orkas 官方服务配置成功",- "settings.orkas_api.configure_failed": "配置失败",+ "settings.orkas_api.configure_ok": "API Key 已保存并通过验证",+ "settings.orkas_api.configure_failed": "API Key 验证或保存失败","settings.orkas_api.open_failed": "无法打开 API Key 创建页面",+ "settings.orkas_api.saved": "已配置",+ "settings.orkas_api.edit": "编辑",+ "settings.orkas_api.delete": "删除",+ "settings.orkas_api.delete_confirm": "删除后,Orkas 官方服务和需要积分的连接器将停止使用此 API Key。确定删除吗?",+ "settings.orkas_api.delete_ok": "API Key 已删除",+ "settings.orkas_api.delete_failed": "API Key 删除失败","settings.orkas_api.recommended": "推荐","settings.orkas_api.includes": "包含:{models}","settings.section.tools": "工具能力",diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.jsindex 04ef0643..ec62fd20 100644--- a/src/renderer/modules/connectors.js+++ b/src/renderer/modules/connectors.js@@ -618,7 +618,10 @@ function _renderCatalogCard(entry, instance) {${menuHtml}</div><div class="connector-card-desc muted"></div>- <div class="connector-card-foot">${action}</div>+ <div class="connector-card-foot">+ ${e.requires_credits === true ? `<span class="connector-credit-badge">${escapeHtml(t('connectors.badge.credits_required'))}</span>` : ''}+ ${action}+ </div>`;card.querySelector('.connector-card-name').textContent = e.display_name;card.querySelector('.connector-card-desc').textContent = desc;@@ -876,6 +879,18 @@ async function _runConnect(entry) {|| (activeLaunch && activeLaunch.throttled)|| _oauthCallbackAttempts.has(entry.id)) return;+ if (entry.requires_credits === true || entry.auth_mode === 'composio') {+ const credential = await window.orkas.invoke('orkasApi.getStatus');+ if (!credential || !credential.ok || !credential.configured) {+ setView('settings');+ if (typeof window.activateSettingsTab === 'function') window.activateSettingsTab('credentials');+ const input = document.getElementById('settings-orkas-api-key-input');+ setTimeout(() => input && input.focus(), 0);+ if (typeof uiToast === 'function') uiToast(t('connectors.errors.api_key_required'));+ return;+ }+ }+const payload = _connectorTrackPayload(entry, null);const startedAt = performance.now();const launchToken = ++_oauthLaunchToken;@@ -905,6 +920,12 @@ async function _runConnect(entry) {// The browser can take focus before IPC returns. Do not recreate feedback already cleared by// that blur; only correlate a launch phase that is still visible.if (launch && launch.token === launchToken) launch.attemptId = res.attempt_id;+ } else if (res && !res.ok && res.requires_api_key) {+ setView('settings');+ if (typeof window.activateSettingsTab === 'function') window.activateSettingsTab('credentials');+ const input = document.getElementById('settings-orkas-api-key-input');+ setTimeout(() => input && input.focus(), 0);+ if (typeof uiToast === 'function') uiToast(t('connectors.errors.api_key_required'));} else if (res && !res.ok) {_handleConnectFailure(payload, startedAt, res);} else {diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.jsindex cbac8dff..7f969847 100644--- a/src/renderer/modules/settings.js+++ b/src/renderer/modules/settings.js@@ -61,6 +61,8 @@ let _settingsState = {taskNotificationPermissionTelemetryKey: '',clientConfigBound: false,recycleBound: false,+ orkasApiCredential: null,+ orkasApiEditing: false,};function _settingsTrackClick() {}@@ -130,6 +132,7 @@ async function loadSettings() {_settingsSafeCall('settings image refresh', _settingsRefreshImageProfiles),_settingsSafeCall('settings video refresh', _settingsRefreshVideoProfiles),_settingsSafeCall('settings tts refresh', _settingsRefreshTtsProfiles),+ _settingsSafeCall('settings Orkas API credential refresh', _settingsRefreshOrkasApiCredential),_settingsSafeCall('settings task notifications refresh', _settingsRefreshTaskNotifications),_settingsSafeCall('settings metacognition refresh', _settingsRefreshMetacognition),_settingsSafeCall('settings data root refresh', _settingsRefreshDataRoot),@@ -1011,11 +1014,32 @@ async function _settingsRefreshEntries() {}function _settingsRenderOrkasApiCard() {+ const credential = _settingsState.orkasApiCredential;+ const configured = !!(credential && credential.configured);+ const saved = document.getElementById('settings-orkas-api-saved');+ const editor = document.getElementById('settings-orkas-api-editor');+ const masked = document.getElementById('settings-orkas-api-key-masked');+ const meta = document.getElementById('settings-orkas-api-key-meta');+ const cancel = document.getElementById('settings-orkas-api-cancel');+ if (saved) saved.hidden = !configured;+ if (editor) editor.hidden = configured && !_settingsState.orkasApiEditing;+ if (cancel) cancel.hidden = !configured || !_settingsState.orkasApiEditing;+ if (masked) masked.textContent = configured ? String(credential.keyMasked || '') : '';+ if (meta) {+ const name = configured && credential.name ? String(credential.name) : t('settings.orkas_api.saved');+ meta.textContent = configured ? name : '';+ }const status = document.getElementById('settings-orkas-api-status');const key = status && status.getAttribute('data-i18n');if (status && key) status.textContent = t(key);}+async function _settingsRefreshOrkasApiCredential() {+ const res = await window.orkas.invoke('orkasApi.getStatus');+ _settingsState.orkasApiCredential = res && res.ok ? res : null;+ _settingsRenderOrkasApiCard();+}+async function _settingsRefreshAllCredentialSections() {await Promise.all([_settingsRefreshProviders(),@@ -1024,6 +1048,7 @@ async function _settingsRefreshAllCredentialSections() {_settingsRefreshImageProfiles(),_settingsRefreshVideoProfiles(),_settingsRefreshTtsProfiles(),+ _settingsRefreshOrkasApiCredential(),]);await _settingsRenderPicker();await _settingsRenderEntries();@@ -1038,8 +1063,11 @@ function _settingsBindOrkasApiOnce() {if (_settingsState.orkasApiBound) return;const createBtn = document.getElementById('settings-orkas-api-create-key');const configureBtn = document.getElementById('settings-orkas-api-configure');+ const editBtn = document.getElementById('settings-orkas-api-edit');+ const deleteBtn = document.getElementById('settings-orkas-api-delete');+ const cancelBtn = document.getElementById('settings-orkas-api-cancel');const keyInput = document.getElementById('settings-orkas-api-key-input');- if (!createBtn || !configureBtn || !keyInput) return;+ if (!createBtn || !configureBtn || !editBtn || !deleteBtn || !cancelBtn || !keyInput) return;_settingsState.orkasApiBound = true;createBtn.addEventListener('click', async () => {@@ -1050,6 +1078,43 @@ function _settingsBindOrkasApiOnce() {}});+ editBtn.addEventListener('click', () => {+ _settingsState.orkasApiEditing = true;+ keyInput.value = '';+ _settingsRenderOrkasApiCard();+ keyInput.focus();+ });++ cancelBtn.addEventListener('click', () => {+ _settingsState.orkasApiEditing = false;+ keyInput.value = '';+ _settingsRenderOrkasApiCard();+ });++ deleteBtn.addEventListener('click', async () => {+ if (!(await uiConfirm(t('settings.orkas_api.delete_confirm')))) return;+ deleteBtn.disabled = true;+ try {+ const res = await window.orkas.invoke('orkasApi.remove');+ if (!res || !res.ok) throw new Error((res && res.error) || t('settings.orkas_api.delete_failed'));+ _settingsState.orkasApiCredential = null;+ _settingsState.orkasApiEditing = false;+ await _settingsRefreshAllCredentialSections();+ if (typeof refreshModelGuard === 'function') {+ await Promise.resolve(refreshModelGuard()).catch(() => {});+ }+ _settingsSetI18nStatus('settings-orkas-api-status', 'ok', 'settings.orkas_api.delete_ok');+ } catch (err) {+ _settingsSetStatus(+ 'settings-orkas-api-status',+ 'error',+ (err && err.message) || t('settings.orkas_api.delete_failed'),+ );+ } finally {+ deleteBtn.disabled = false;+ }+ });+const configure = async () => {const apiKey = String(keyInput.value || '').trim();if (!apiKey) {@@ -1059,7 +1124,7 @@ function _settingsBindOrkasApiOnce() {configureBtn.disabled = true;_settingsSetI18nStatus('settings-orkas-api-status', 'busy', 'settings.orkas_api.configuring');try {- const res = await window.orkas.invoke('orkasApi.configureAll', { apiKey });+ const res = await window.orkas.invoke('orkasApi.save', { apiKey });if (!res || !res.ok) {if (res && res.error) {_settingsSetStatus('settings-orkas-api-status', 'error', res.error);@@ -1069,6 +1134,8 @@ function _settingsBindOrkasApiOnce() {return;}keyInput.value = '';+ _settingsState.orkasApiCredential = res;+ _settingsState.orkasApiEditing = false;await _settingsRefreshAllCredentialSections();if (typeof refreshModelGuard === 'function') {await Promise.resolve(refreshModelGuard()).catch(() => {});diff --git a/src/renderer/style.css b/src/renderer/style.cssindex bffc6ee8..df8066b3 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -12895,8 +12895,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }line-height: 38px;background: var(--surface);}-.settings-orkas-api-configure-row .btn {+.settings-orkas-api-editor-actions {grid-column: 2;+ display: flex;+ gap: 8px;+}+.settings-orkas-api-configure-row .btn {width: 100%;height: 40px;padding: 0 18px;@@ -12904,6 +12908,34 @@ body.is-sidebar-resizing iframe { pointer-events: none; }white-space: nowrap;box-shadow: 0 2px 5px rgba(73, 69, 192, 0.16);}+.settings-orkas-api-saved {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ min-height: 44px;+ padding: 10px 12px;+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--surface-subtle, var(--surface));+}+.settings-orkas-api-saved[hidden] { display: none; }+.settings-orkas-api-key-summary {+ display: flex;+ flex-direction: column;+ gap: 3px;+ min-width: 0;+}+.settings-orkas-api-key-summary code {+ color: var(--text);+ font-size: 13px;+}+.settings-orkas-api-key-meta {+ color: var(--muted);+ font-size: 12px;+}+.settings-orkas-api-actions { display: flex; gap: 8px; }.settings-orkas-api-status {grid-column: 1 / -1;display: block;@@ -12934,6 +12966,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }grid-template-columns: minmax(0, 1fr);gap: 10px;}+ .settings-orkas-api-saved {+ align-items: stretch;+ flex-direction: column;+ }+ .settings-orkas-api-actions,+ .settings-orkas-api-editor-actions { width: 100%; }.settings-orkas-api-head .btn,.settings-orkas-api-configure-row .btn {width: 100%;@@ -12941,6 +12979,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }.settings-orkas-api-configure-row .btn {grid-column: 1;}+ .settings-orkas-api-editor-actions { grid-column: 1; }}.settings-group-head-main {min-width: 0;@@ -15418,6 +15457,18 @@ body.is-sidebar-resizing iframe { pointer-events: none; }align-items: center;min-width: 0;}+.connector-credit-badge {+ margin-right: auto;+ padding: 3px 7px;+ border: 1px solid color-mix(in srgb, var(--warn) 42%, transparent);+ border-radius: 999px;+ background: color-mix(in srgb, var(--warn) 10%, transparent);+ color: color-mix(in srgb, var(--warn) 78%, var(--text));+ font-size: 10px;+ font-weight: 600;+ line-height: 1.2;+ white-space: nowrap;+}.connector-card-foot .btn {flex: 0 0 auto;}diff --git a/test/main/features/connectors/api-key-metering.test.ts b/test/main/features/connectors/api-key-metering.test.tsnew file mode 100644index 00000000..5f82ff3d--- /dev/null+++ b/test/main/features/connectors/api-key-metering.test.ts@@ -0,0 +1,106 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({+ key: 'orkas-test-key',+ status: {+ configured: true,+ scopes: ['connectors'],+ connectorAccess: true,+ },+}));++vi.mock('../../../../src/main/features/auth', () => ({+ getOrkasApiKey: () => state.key,+ getOrkasApiCredentialStatus: () => state.status,+}));++vi.mock('../../../../src/main/features/connectors/_server_bridge', () => ({+ accountApiBase: () => 'https://api.example.test/api',+}));++vi.mock('../../../../src/main/features/api_common', () => ({+ withCommonHeaders: (headers: Record<string, string>) => ({+ 'X-Orkas-Client-Channel': 'open',+ ...headers,+ }),+}));++describe('connector API-key metering', () => {+ beforeEach(() => {+ state.key = 'orkas-test-key';+ state.status = {+ configured: true,+ scopes: ['connectors'],+ connectorAccess: true,+ };+ vi.unstubAllGlobals();+ });++ it('blocks a paid connector before any request when no API key is configured', async () => {+ state.key = '';+ state.status = { configured: false, scopes: [], connectorAccess: false };+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ const { preflightConnectorCredits } = await import(+ '../../../../src/main/features/connectors/usage-metering'+ );++ await expect(preflightConnectorCredits({+ id: 'gmail',+ usage_metering: { provider: 'composio', credits_milli_per_call: 250 },+ } as any, 'connect')).rejects.toMatchObject({ code: 'orkas_api_key_required' });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('uses a locally saved key and reports scope rejection from the service', async () => {+ state.status = { configured: true, scopes: [], connectorAccess: false };+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({+ error: { code: 'insufficient_scope', message: 'Connector access required' },+ }), { status: 403 }));+ vi.stubGlobal('fetch', fetchMock);+ const { preflightConnectorCredits } = await import(+ '../../../../src/main/features/connectors/usage-metering'+ );++ await expect(preflightConnectorCredits({+ id: 'gmail',+ usage_metering: { provider: 'composio', credits_milli_per_call: 250 },+ } as any, 'connect')).rejects.toMatchObject({ code: 'insufficient_scope' });+ expect(fetchMock).toHaveBeenCalledOnce();+ });++ it('reuses the connector preflight route with Bearer auth and open client headers', async () => {+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({+ code: 0,+ credits_milli_per_call: 250,+ available_credits_milli: 5_000,+ }), { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);+ const { preflightConnectorCredits } = await import(+ '../../../../src/main/features/connectors/usage-metering'+ );++ await expect(preflightConnectorCredits({+ id: 'gmail',+ usage_metering: { provider: 'composio', credits_milli_per_call: 250 },+ } as any, 'tool_call')).resolves.toMatchObject({ code: 0 });++ expect(fetchMock).toHaveBeenCalledWith(+ 'https://api.example.test/api/connectors/usage/preflight',+ expect.objectContaining({+ method: 'POST',+ headers: expect.objectContaining({+ Authorization: 'Bearer orkas-test-key',+ 'X-Orkas-Client-Channel': 'open',+ }),+ }),+ );+ const init = fetchMock.mock.calls[0]![1] as RequestInit;+ expect(JSON.parse(String(init.body))).toEqual({+ provider: 'composio',+ connector_id: 'gmail',+ stage: 'tool_call',+ calls: 1,+ });+ });+});diff --git a/test/main/features/connectors/composio-stdio-adapter.test.ts b/test/main/features/connectors/composio-stdio-adapter.test.tsnew file mode 100644index 00000000..a2570ada--- /dev/null+++ b/test/main/features/connectors/composio-stdio-adapter.test.ts@@ -0,0 +1,219 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createRequire } from 'node:module';+import * as path from 'node:path';++const requireCjs = createRequire(import.meta.url);++type Adapter = {+ TOOLS_REQUEST_TIMEOUT_MS: number;+ EXECUTE_REQUEST_TIMEOUT_MS: number;+ OrkasProxyResponseError: new (message: string, status: number, code: string) => Error;+ splitComposioToolArguments: (value: Record<string, unknown>) => {+ args: Record<string, unknown>;+ creditContextBody: Record<string, string>;+ };+ callComposioTool: (+ name: string,+ value: Record<string, unknown>,+ request?: (path: string, body: Record<string, unknown>, timeoutMs: number) => Promise<Record<string, unknown>>,+ ) => Promise<Record<string, unknown>>;+ normalizeTool: (tool: Record<string, unknown>) => Record<string, unknown> | null;+};++const ORIGINAL_ENV = {+ ORKAS_API_BASE: process.env.ORKAS_API_BASE,+ ORKAS_API_KEY: process.env.ORKAS_API_KEY,+ ORKAS_CLIENT_HEADERS_JSON: process.env.ORKAS_CLIENT_HEADERS_JSON,+ COMPOSIO_CONNECTION_ID: process.env.COMPOSIO_CONNECTION_ID,+ COMPOSIO_CONNECTOR_ID: process.env.COMPOSIO_CONNECTOR_ID,+};++function configureAdapterEnv(): void {+ process.env.ORKAS_API_BASE = 'https://orkas.example/api';+ process.env.ORKAS_API_KEY = 'orkas-user-key';+ process.env.ORKAS_CLIENT_HEADERS_JSON = JSON.stringify({+ 'Orkas-Channel': 'open',+ 'Orkas-App-Version': '2026.9.7',+ 'Accept-Language': 'zh-CN',+ session_id: 'must-not-forward',+ });+ process.env.COMPOSIO_CONNECTION_ID = 'connection-1';+ process.env.COMPOSIO_CONNECTOR_ID = 'gmail';+}++afterEach(() => {+ vi.unstubAllGlobals();+ for (const [key, value] of Object.entries(ORIGINAL_ENV)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+});++function loadAdapter(): Adapter {+ const full = path.join(process.cwd(), 'bin', 'composio-mcp-server.cjs');+ delete requireCjs.cache[full];+ return requireCjs(full) as Adapter;+}++describe('Composio stdio proxy adapter', () => {+ it('keeps the Server execution deadline inside the adapter deadline', () => {+ const adapter = loadAdapter();+ expect(adapter.TOOLS_REQUEST_TIMEOUT_MS).toBe(25_000);+ expect(adapter.EXECUTE_REQUEST_TIMEOUT_MS).toBe(100_000);+ });++ it('strips host credit context from third-party tool arguments and promotes bounded metadata', () => {+ configureAdapterEnv();+ const adapter = loadAdapter();+ expect(adapter.splitComposioToolArguments({+ query: 'plan',+ __orkas_credit_context: {+ conversationId: 'conv-1',+ conversationTitle: 'Cross-capability task',+ conversationTitleUpdatedAt: 1234,+ turnId: 'turn-2',+ agentId: 'agent-3',+ agentName: 'Researcher',+ },+ })).toEqual({+ args: { query: 'plan' },+ creditContextBody: {+ orkas_conversation_id: 'conv-1',+ orkas_turn_id: 'turn-2',+ },+ });+ });++ it('preserves standardized MCP safety annotations and drops vendor metadata', () => {+ const adapter = loadAdapter();+ expect(adapter.normalizeTool({+ slug: 'SHOPEE_LIST_ORDERS',+ description: 'List orders',+ input_schema: { type: 'object' },+ annotations: {+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: true,+ vendorSecret: 'drop',+ },+ policy: {+ risk: 'D',+ confirmation: 'destructive',+ max_batch_size: 25,+ sensitive_operation: 'delete',+ },+ })).toEqual({+ name: 'SHOPEE_LIST_ORDERS',+ description: 'List orders',+ inputSchema: { type: 'object' },+ annotations: {+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: true,+ },+ _meta: {+ orkas: {+ actionPolicy: {+ risk: 'D',+ confirmation: 'destructive',+ sensitiveOperation: 'delete',+ maxBatchSize: 25,+ },+ },+ },+ });+ });++ it('forwards an approved desktop action directly with only business arguments', async () => {+ configureAdapterEnv();+ const adapter = loadAdapter();+ const requests: Array<{ path: string; body: Record<string, unknown> }> = [];+ const request = vi.fn(async (requestPath: string, body: Record<string, unknown>) => {+ requests.push({ path: requestPath, body });+ return { result: { ok: true } };+ });++ await expect(adapter.callComposioTool('SHOP_CREATE_REFUND', {+ amount: 12.5,+ }, request)).resolves.toMatchObject({ content: [{ type: 'text' }] });++ expect(requests).toEqual([+ {+ path: '/connectors/composio/execute',+ body: {+ tool_slug: 'SHOP_CREATE_REFUND',+ arguments: { amount: 12.5 },+ },+ },+ ]);+ });++ it('calls the reused connector API with Bearer auth and no account-session headers', async () => {+ configureAdapterEnv();+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({+ code: 0,+ result: { ok: true },+ }), { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);+ const adapter = loadAdapter();++ await adapter.callComposioTool('GMAIL_FETCH_EMAILS', { query: 'inbox' });++ const init = fetchMock.mock.calls[0][1];+ expect(init.headers).toMatchObject({+ Authorization: 'Bearer orkas-user-key',+ 'Orkas-Channel': 'open',+ 'Orkas-App-Version': '2026.9.7',+ });+ expect(init.headers).not.toHaveProperty('session_id');+ expect(init.headers).not.toHaveProperty('user_id');+ expect(init.headers).not.toHaveProperty('Accept-Language');+ });++ it('returns a completed Server failure as an MCP tool error with a stable safe code', async () => {+ configureAdapterEnv();+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({+ code: 1,+ msg: 'Connector action took too long. Please try again',+ error: { code: 'composio_upstream_timeout' },+ }), { status: 504 })));+ const adapter = loadAdapter();++ await expect(adapter.callComposioTool('GMAIL_FETCH_EMAILS', { query: 'inbox' }))+ .resolves.toEqual({+ isError: true,+ content: [{+ type: 'text',+ text: JSON.stringify({+ error_code: 'composio_upstream_timeout',+ message: 'Connector action took too long. Please try again',+ }),+ }],+ });+ });++ it('still throws when no Server response exists so the transport circuit can react', async () => {+ configureAdapterEnv();+ vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('fetch failed'); }));+ const adapter = loadAdapter();++ await expect(adapter.callComposioTool('GMAIL_FETCH_EMAILS', { query: 'inbox' }))+ .rejects.toThrow('fetch failed');+ });++ it('does not expose an unstructured Server body through the MCP tool error', async () => {+ configureAdapterEnv();+ vi.stubGlobal('fetch', vi.fn(async () => new Response(+ '[email protected] confidential provider failure',+ { status: 502 },+ )));+ const adapter = loadAdapter();++ const result = await adapter.callComposioTool('GMAIL_FETCH_EMAILS', { query: 'inbox' });++ expect(result).toMatchObject({ isError: true });+ expect(JSON.stringify(result)).toContain('connector_proxy_failed');+ expect(JSON.stringify(result)).not.toContain('[email protected]');+ expect(JSON.stringify(result)).not.toContain('confidential provider failure');+ });+});diff --git a/test/main/features/connectors/manager.test.ts b/test/main/features/connectors/manager.test.tsindex 8d2d1f3f..c3416269 100644--- a/test/main/features/connectors/manager.test.ts+++ b/test/main/features/connectors/manager.test.ts@@ -40,6 +40,9 @@ const mocks = vi.hoisted(() => ({events: {broadcastOAuthConnectOutcome: undefined as any,},+ metering: {+ preflightConnectorCredits: undefined as any,+ },}));vi.mock('../../../../src/main/features/connectors/mcp-client', () => ({@@ -72,6 +75,14 @@ vi.mock('../../../../src/main/features/connectors/oauth-events', () => ({broadcastOAuthConnectOutcome: (...args: any[]) => mocks.events.broadcastOAuthConnectOutcome(...args),}));+vi.mock('../../../../src/main/features/connectors/usage-metering', () => ({+ preflightConnectorCredits: (...args: any[]) => mocks.metering.preflightConnectorCredits(...args),+}));++vi.mock('../../../../src/main/features/connectors/api-key', () => ({+ connectorApiKeyHeaders: () => ({ Authorization: 'Bearer orkas-connector-key' }),+}));+vi.mock('../../../../src/main/util/bundled-runtime', async (importOriginal) => {const actual = await importOriginal<typeof import('../../../../src/main/util/bundled-runtime')>();return {@@ -92,6 +103,7 @@ function resetMockBehaviors() {mocks.oauth.refreshIfStale = vi.fn(async (_uid: string, _entry: unknown, grant: unknown) => grant);mocks.dcr.startMcpDcrOAuth = vi.fn();mocks.dcr.refreshDcrIfStale = vi.fn(async (_client: unknown, grant: unknown) => grant);+ mocks.metering.preflightConnectorCredits = vi.fn(async () => null);}async function writeGoogleConnectorsConfig(value: unknown): Promise<void> {@@ -108,6 +120,33 @@ async function writeGoogleConnectorsConfig(value: unknown): Promise<void> {});}+async function writeComposioCatalog(): Promise<void> {+ const users = await import('../../../../src/main/features/users');+ const paths = await import('../../../../src/main/paths');+ const storage = await import('../../../../src/main/storage');+ users.activateUser(TEST_UID);+ storage.writeJsonSync(paths.userRemoteConfigFile(TEST_UID), {+ version: 1,+ active: {+ immediate: {+ 'connectors.catalog': [{+ id: 'composio-mail',+ display_name: 'Mail',+ icon_svg: '<svg viewBox="0 0 24 24"></svg>',+ category: 'productivity',+ description_zh: '邮件',+ description_en: 'Mail',+ auth_mode: 'composio',+ toolkit: 'gmail',+ auth_config_id: 'ac_public_123',+ tools: [{ slug: 'GMAIL_FETCH_EMAILS' }],+ }],+ },+ restart: {},+ },+ });+}+function googleInstance(id: 'gmail' | 'gsheets', scopes: string[]) {const now = new Date().toISOString();return {@@ -344,6 +383,39 @@ afterEach(() => {});describe('features/connectors/manager authorization recovery', () => {+ it('connects a server-catalog Composio connector through the API-key adapter', async () => {+ await writeComposioCatalog();+ mocks.oauth.startComposioConnect.mockResolvedValue({+ connection_id: 'connection-1',+ toolkit: 'gmail',+ auth_config_id: 'ac_public_123',+ account_label: '[email protected]',+ });+ mocks.mcp.listTools.mockResolvedValue([+ { name: 'GMAIL_FETCH_EMAILS', description: 'Fetch email', input_schema: {} },+ ]);+ const manager = await import('../../../../src/main/features/connectors/manager');++ await expect(manager.connectViaOAuth(TEST_UID, 'composio-mail')).resolves.toMatchObject({+ id: 'composio-mail',+ composio_grant: { connection_id: 'connection-1', toolkit: 'gmail' },+ status: { kind: 'connected' },+ transport: {+ kind: 'stdio',+ env: {+ ORKAS_API_KEY: 'orkas-connector-key',+ COMPOSIO_CONNECTION_ID: 'connection-1',+ COMPOSIO_CONNECTOR_ID: 'composio-mail',+ },+ },+ });+ expect(mocks.metering.preflightConnectorCredits).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'composio-mail', auth_mode: 'composio' }),+ 'connect',+ );+ expect(mocks.oauth.startComposioConnect).toHaveBeenCalledOnce();+ });+it('keeps persisted server-bridge auth error rows visible for reconnect', async () => {const registry = await import('../../../../src/main/features/connectors/registry');const manager = await import('../../../../src/main/features/connectors/manager');diff --git a/test/main/features/connectors/oauth.test.ts b/test/main/features/connectors/oauth.test.tsindex c8265abf..c2bbe668 100644--- a/test/main/features/connectors/oauth.test.ts+++ b/test/main/features/connectors/oauth.test.ts@@ -31,6 +31,9 @@ beforeEach(() => {vi.doMock('../../../../src/main/features/connectors/oauth-events', () => ({broadcastOAuthConnectProgress: oauthProgress,}));+ vi.doMock('../../../../src/main/features/connectors/api-key', () => ({+ connectorApiKeyHeaders: () => ({ Authorization: 'Bearer orkas-connector-key' }),+ }));vi.doMock('../../../../src/main/logger', () => ({createLogger: () => ({error: vi.fn(),@@ -47,9 +50,47 @@ afterEach(() => {vi.doUnmock('../../../../src/main/features/connectors/_server_bridge');vi.doUnmock('../../../../src/main/features/config');vi.doUnmock('../../../../src/main/features/connectors/oauth-events');+ vi.doUnmock('../../../../src/main/features/connectors/api-key');});describe('features/connectors/oauth', () => {+ it('uses Bearer auth for the existing Composio start and exchange routes', async () => {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(new Response(JSON.stringify({+ code: 0,+ redirect_url: 'https://provider.example/connect',+ }), { status: 200 }))+ .mockResolvedValueOnce(new Response(JSON.stringify({+ code: 0,+ connection_id: 'conn-1',+ toolkit: 'gmail',+ auth_config_id: 'auth-config-public-id',+ account_label: '[email protected]',+ }), { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);++ const oauth = await import('../../../../src/main/features/connectors/oauth');+ const { shell } = await import('electron');+ const pending = oauth.startComposioConnect({+ id: 'gmail',+ display_name: 'Gmail',+ auth_mode: 'composio',+ composio: { toolkit: 'gmail', auth_config_id: 'auth-config-public-id', tools: [] },+ } as any);+ await vi.waitFor(() => expect(shell.openExternal).toHaveBeenCalledWith('https://provider.example/connect'));+ await oauth.handleCallbackUrl('orkas://connectors/oauth/callback?exchange_code=exchange-1');++ await expect(pending).resolves.toMatchObject({+ connection_id: 'conn-1',+ toolkit: 'gmail',+ auth_config_id: 'auth-config-public-id',+ account_label: '[email protected]',+ });+ for (const [, init] of fetchMock.mock.calls) {+ expect(init.headers).toMatchObject({ Authorization: 'Bearer orkas-connector-key' });+ }+ });+it('rejects a server-bridge connector grant when the user unchecked a required scope', async () => {vi.stubGlobal('fetch', vi.fn(async () => ({ok: true,diff --git a/test/main/features/open-user-registry.test.ts b/test/main/features/open-user-registry.test.tsnew file mode 100644index 00000000..d4dbf98f--- /dev/null+++ b/test/main/features/open-user-registry.test.ts@@ -0,0 +1,159 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++let root: string;+let previousRoot: string | undefined;+let previousAuth: string | undefined;++beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-open-registry-'));+ previousRoot = process.env.ORKAS_WORKSPACE_ROOT;+ previousAuth = process.env.CORE_AGENT_AUTH_DIR;+ process.env.ORKAS_WORKSPACE_ROOT = root;+ delete process.env.CORE_AGENT_AUTH_DIR;+ vi.resetModules();+});++afterEach(() => {+ if (previousRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;+ else process.env.ORKAS_WORKSPACE_ROOT = previousRoot;+ if (previousAuth === undefined) delete process.env.CORE_AGENT_AUTH_DIR;+ else process.env.CORE_AGENT_AUTH_DIR = previousAuth;+ vi.unstubAllGlobals();+ fs.rmSync(root, { recursive: true, force: true });+});++function seedLegacy(uid: string) {+ const registry = JSON.stringify({+ current_user_id: uid, dev_current_user_id: uid,+ users: [{ user_id: uid, created_at: '2026-01-01T00:00:00' }],+ });+ fs.writeFileSync(path.join(root, 'users.json'), registry);+ const config = path.join(root, uid, 'local', 'config');+ fs.mkdirSync(config, { recursive: true });+ return { registry, config };+}++async function boot() {+ const users = await import('../../../src/main/features/users');+ return users.initActiveUser({ openSource: true });+}++function openRegistry() {+ return JSON.parse(fs.readFileSync(path.join(root, 'open-users.json'), 'utf8'));+}++describe('open-source user directory selection', () => {+ it.each(['login-record', 'hosted-encryption', 'anonymous'])(+ 'isolates %s data and allows offline Key setup without changing hosted files', async (kind) => {+ const oldUid = kind === 'anonymous' ? 'anonymous' : 'commercial-user';+ const { registry, config } = seedLegacy(oldUid);+ if (kind === 'login-record') {+ fs.writeFileSync(path.join(config, 'account.json'), JSON.stringify({ user_id: oldUid }));+ }+ // A hosted encrypted file is enough evidence even after account.json was removed.+ const oldAuth = 'ORKLSEC1:hosted-fixture';+ if (kind === 'hosted-encryption') fs.writeFileSync(path.join(config, 'auth-profiles.json'), oldAuth);+ const before = fs.readdirSync(config);+ const fetchMock = vi.fn(async () => { throw new Error('offline'); });+ vi.stubGlobal('fetch', fetchMock);++ const rec = await boot();+ expect(rec.user_id).toMatch(/^[a-f0-9]{32}$/);+ expect(rec.user_id).not.toBe(oldUid);+ expect(openRegistry().open_current_user_id).toBe(rec.user_id);+ expect(process.env.CORE_AGENT_AUTH_DIR).toBe(path.join(root, rec.user_id, 'local', 'config'));++ const auth = await import('../../../src/main/features/auth');+ expect(auth.saveOrkasApiCredential(auth.prepareOrkasApiCredential('open-test-key-xxxxxxxx')))+ .toMatchObject({ configured: true });+ expect(auth.getOrkasApiKey()).toBe('open-test-key-xxxxxxxx');+ expect(fs.readFileSync(path.join(root, 'users.json'), 'utf8')).toBe(registry);+ expect(fs.readdirSync(config)).toEqual(before);+ if (kind === 'hosted-encryption') {+ expect(fs.readFileSync(path.join(config, 'auth-profiles.json'), 'utf8')).toBe(oldAuth);+ }+ expect(fetchMock).not.toHaveBeenCalled();+ },+ );++ it.each(['12345678', '0123456789abcdef0123456789abcdef'])(+ 'reuses legacy open user %s in place and can still decrypt its credentials', async (uid) => {+ const { registry, config } = seedLegacy(uid);+ const secrets = await import('../../../src/main/util/local-secret-store');+ const plaintext = JSON.stringify({+ version: 6, profiles: {+ 'openai:default': { type: 'api_key', provider: 'openai', key: 'legacy-test-key', label: 'default' },+ }, entries: [], searchProfiles: [], imageProfiles: [], videoProfiles: [], ttsProfiles: [],+ });+ const encrypted = secrets.encryptLocalSecret({+ namespace: 'auth.profiles', ownerId: uid, recordId: 'auth-profiles.json',+ }, plaintext);+ fs.writeFileSync(path.join(config, 'auth-profiles.json'), encrypted);+ fs.writeFileSync(path.join(config, 'retained-marker'), 'keep');++ expect((await boot()).user_id).toBe(uid);+ expect(openRegistry().open_current_user_id).toBe(uid);+ expect(fs.readFileSync(path.join(root, 'users.json'), 'utf8')).toBe(registry);+ expect(fs.readFileSync(path.join(config, 'retained-marker'), 'utf8')).toBe('keep');+ expect(secrets.decryptLocalSecret({+ namespace: 'auth.profiles', ownerId: uid, recordId: 'auth-profiles.json',+ }, fs.readFileSync(path.join(config, 'auth-profiles.json'), 'utf8'))).toBe(plaintext);+ },+ );++ it('retains its own user after an old commercial app rewrites the shared registry', async () => {+ const { config } = seedLegacy('commercial-first');+ fs.writeFileSync(path.join(config, 'account.json'), '{}');+ const first = await boot();+ const next = seedLegacy('commercial-next').registry;+ vi.resetModules();++ expect((await boot()).user_id).toBe(first.user_id);+ expect(fs.readFileSync(path.join(root, 'users.json'), 'utf8')).toBe(next);+ expect(openRegistry().users).toHaveLength(1);+ });++ it('creates only its own registry on a clean install and keeps the same user on restart', async () => {+ const first = await boot();+ expect(fs.existsSync(path.join(root, 'users.json'))).toBe(false);+ vi.resetModules();+ expect((await boot()).user_id).toBe(first.user_id);+ });++ it('uses the saved open pointer directly without repeating legacy ownership detection', async () => {+ seedLegacy('legacy-open');+ const first = await boot();+ // Once migration is complete, an unrelated account file must not select a+ // different data directory. Credential validation remains with its own reader.+ fs.writeFileSync(path.join(root, first.user_id, 'local', 'config', 'account.json'), '{}');+ vi.resetModules();+ expect((await boot()).user_id).toBe(first.user_id);+ });++ it('persists later local user changes only through the open pointer', async () => {+ const { registry, config } = seedLegacy('commercial-user');+ fs.writeFileSync(path.join(config, 'account.json'), '{}');+ await boot();+ const users = await import('../../../src/main/features/users');+ users.activateUser('another-open-user');+ expect(openRegistry().open_current_user_id).toBe('another-open-user');+ expect(fs.readFileSync(path.join(root, 'users.json'), 'utf8')).toBe(registry);+ vi.resetModules();+ expect((await boot()).user_id).toBe('another-open-user');+ });++ it.each(['{broken', JSON.stringify({ open_current_user_id: '../outside', users: [] })])(+ 'preserves an invalid open registry and refuses to fall back to another user', async (raw) => {+ const { registry } = seedLegacy('legacy-user');+ fs.writeFileSync(path.join(root, 'open-users.json'), raw);+ await expect(boot()).rejects.toThrow(/open-source user registry/);+ expect(fs.readFileSync(path.join(root, 'open-users.json'), 'utf8')).toBe(raw);+ expect(fs.readFileSync(path.join(root, 'users.json'), 'utf8')).toBe(registry);+ const users = await import('../../../src/main/features/users');+ expect(users.hasActiveUser()).toBe(false);+ },+ );+});diff --git a/test/main/ipc/connectors.test.ts b/test/main/ipc/connectors.test.tsindex d53852d5..82192989 100644--- a/test/main/ipc/connectors.test.ts+++ b/test/main/ipc/connectors.test.ts@@ -19,6 +19,7 @@ afterEach(() => {vi.doUnmock('../../../src/main/features/connectors');vi.doUnmock('../../../src/main/features/component_enabled');vi.doUnmock('../../../src/main/features/connectors/availability');+ vi.doUnmock('../../../src/main/features/connectors/api-key');fs.rmSync(tmpDir, { recursive: true, force: true });});@@ -46,7 +47,10 @@ function baseInstance(transport: any): any {describe('ipc/connectors renderer DTO', () => {it('accepts OAuth start without waiting for the browser callback', async () => {const beginOAuthConnect = vi.fn(() => ({ attempt_id: 'attempt-1' }));- vi.doMock('../../../src/main/features/connectors', () => ({ beginOAuthConnect }));+ vi.doMock('../../../src/main/features/connectors', () => ({+ beginOAuthConnect,+ findCatalogEntry: () => ({ id: 'github', auth_mode: 'server_bridge' }),+ }));vi.doMock('../../../src/main/features/component_enabled', () => ({isConnectorEnabled: vi.fn(() => true),setConnectorEnabled: vi.fn(),@@ -66,6 +70,41 @@ describe('ipc/connectors renderer DTO', () => {expect(out).toEqual({ started: true, attempt_id: 'attempt-1' });});+ it('returns a settings redirect contract before starting a paid connector without an API key', async () => {+ const beginOAuthConnect = vi.fn();+ vi.doMock('../../../src/main/features/connectors', () => ({+ beginOAuthConnect,+ findCatalogEntry: () => ({ id: 'composio-mail', auth_mode: 'composio', requires_credits: true }),+ }));+ vi.doMock('../../../src/main/features/connectors/api-key', () => ({+ requireConnectorApiKey: () => {+ throw Object.assign(new Error('Configure an Orkas API Key first.'), {+ code: 'orkas_api_key_required',+ });+ },+ }));+ 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');+ await expect(invokeHandlers['connectors.start_oauth'](+ { catalog_id: 'composio-mail' },+ { userId: 'u-ipc' },+ )).resolves.toMatchObject({+ ok: false,+ code: 'orkas_api_key_required',+ requires_api_key: true,+ settings_tab: 'credentials',+ });+ expect(beginOAuthConnect).not.toHaveBeenCalled();+ });+it('lists local connector state without triggering Composio restore', async () => {const restoreComposioConnectionsFromServer = vi.fn(async () => 0);vi.doMock('../../../src/main/features/connectors', () => ({diff --git a/test/main/ipc/orkas-api-quick-setup.test.ts b/test/main/ipc/orkas-api-quick-setup.test.tsindex e2cad58e..93ecfdad 100644--- a/test/main/ipc/orkas-api-quick-setup.test.ts+++ b/test/main/ipc/orkas-api-quick-setup.test.ts@@ -40,6 +40,7 @@ beforeEach(async () => {});afterEach(() => {+ vi.unstubAllGlobals();if (previousWorkspaceRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;else process.env.ORKAS_WORKSPACE_ROOT = previousWorkspaceRoot;fs.rmSync(tmpDir, { recursive: true, force: true });@@ -105,4 +106,53 @@ describe('ipc › Orkas API quick setup', () => {profiles: expect.arrayContaining([expect.objectContaining({ provider: 'orkas-api' })]),});});++ it('saves, replaces and deletes the shared key offline without exposing it or revoking remote connections', async () => {+ const fetchMock = vi.fn(async () => { throw new Error('offline'); });+ vi.stubGlobal('fetch', fetchMock);+ const auth = await import('../../../src/main/features/auth');+ const registry = await import('../../../src/main/features/connectors/registry');+ const { CONNECTOR_CATALOG } = await import('../../../src/main/features/connectors/catalog');+ CONNECTOR_CATALOG.push({ id: 'offline-paid', auth_mode: 'composio' } as any);+ const seedConnection = async () => registry.upsert('u_model_config', {+ id: 'offline-paid', display_name: 'Paid', origin: 'catalog',+ transport: { kind: 'stdio', command: 'node', args: [] },+ enabled_subtools: null, tools_cache: [], tools_cached_at: 0,+ status: { kind: 'connected' }, created_at: '', updated_at: '',+ } as any);++ const firstKey = 'orkas-connector-key-xxxxxxxx';+ const saved = await call('orkasApi.save', { apiKey: firstKey });+ expect(saved).toMatchObject({ ok: true, configured: true });+ expect(JSON.stringify(saved)).not.toContain(firstKey);+ expect(auth.getOrkasApiKey()).toBe(firstKey);+ expect(await call('orkasApi.getStatus')).toMatchObject({+ ok: true, configured: true, keyMasked: saved.keyMasked,+ });++ await seedConnection();+ expect(await call('orkasApi.save', { apiKey: 'replacement-key-xxxxxxxx' }))+ .toMatchObject({ ok: true, configured: true });+ expect(auth.getOrkasApiKey()).toBe('replacement-key-xxxxxxxx');+ expect(registry.load('u_model_config').connections['offline-paid']).toBeUndefined();++ await seedConnection();+ expect(await call('orkasApi.remove')).toMatchObject({ ok: true, removed: true });+ expect(await call('orkasApi.getStatus')).toMatchObject({ ok: true, configured: false });+ expect(registry.load('u_model_config').connections['offline-paid']).toBeUndefined();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('rejects blank or header-unsafe input locally while preserving the saved key', async () => {+ const fetchMock = vi.fn(async () => { throw new Error('offline'); });+ vi.stubGlobal('fetch', fetchMock);+ expect(await call('orkasApi.save', { apiKey: 'existing-key-xxxxxxxx' }))+ .toMatchObject({ ok: true, configured: true });+ for (const apiKey of ['', 'unsafe\r\nheader']) {+ expect(await call('orkasApi.save', { apiKey })).toMatchObject({ ok: false });+ }+ const auth = await import('../../../src/main/features/auth');+ expect(auth.getOrkasApiKey()).toBe('existing-key-xxxxxxxx');+ expect(fetchMock).not.toHaveBeenCalled();+ });});diff --git a/test/renderer/connectors-card.test.ts b/test/renderer/connectors-card.test.tsindex 0ec2f98a..14ed59c4 100644--- a/test/renderer/connectors-card.test.ts+++ b/test/renderer/connectors-card.test.ts@@ -32,18 +32,16 @@ describe('connectors card surface', () => {expect(js).not.toContain('connectors.google_sheets_authorize_files');});- it('continues filtering PC credit-gated connector UI', () => {+ it('renders the API-key-backed credit connector marker and settings guard', () => {const js = read('src/renderer/modules/connectors.js');const css = read('src/renderer/style.css');const locales = ['en', 'zh', 'ja', 'pt'].map((lang) => read(`src/renderer/locales/${lang}.json`)).join('\n');- const meteringKey = ['usage', '_metering'].join('');- const pricingKey = ['credits', '_milli_per_call'].join('');const copyKey = ['connectors.badge.', 'credits', '_required'].join('');- expect(js).not.toContain(meteringKey);- expect(js).not.toContain(pricingKey);- expect(js).not.toContain('_connectorCreditBadge');- expect(css).not.toContain('connector-card-credit-badge');- expect(locales).not.toContain(copyKey);+ expect(js).toContain('entry.requires_credits === true');+ expect(js).toContain("window.orkas.invoke('orkasApi.getStatus')");+ expect(js).toContain("window.activateSettingsTab('credentials')");+ expect(css).toContain('.connector-credit-badge');+ expect(locales).toContain(copyKey);});});diff --git a/test/renderer/connectors-degraded-card.test.ts b/test/renderer/connectors-degraded-card.test.tsindex e4599c19..5192bead 100644--- a/test/renderer/connectors-degraded-card.test.ts+++ b/test/renderer/connectors-degraded-card.test.ts@@ -60,6 +60,10 @@ function loadConnectorsRenderer(const clicks: Array<[string, Record<string, unknown>]> = [];const events: Array<[string, Record<string, unknown>]> = [];const errors: Array<[string, Record<string, unknown>]> = [];+ const views: string[] = [];+ const settingsTabs: string[] = [];+ const toasts: string[] = [];+ const apiKeyInput = { focus: vi.fn() };const pushHandlers = new Map<string, (payload: any) => void>();const windowHandlers = new Map<string, Array<(payload?: any) => void>>();const timers = new Map<number, { at: number; handler: () => void }>();@@ -93,7 +97,7 @@ function loadConnectorsRenderer(},document: {createElement: (tag: string) => makeElement(tag),- getElementById: () => null,+ getElementById: (id: string) => id === 'settings-orkas-api-key-input' ? apiKeyInput : null,querySelectorAll: () => [],body: { appendChild: () => {} },addEventListener: () => {},@@ -111,6 +115,7 @@ function loadConnectorsRenderer(innerWidth: 1200,innerHeight: 800,Monitor: monitor,+ activateSettingsTab: (tab: string) => { settingsTabs.push(tab); },orkas: {invoke,onPushEvent: (channel: string, handler: (payload: any) => void) => { pushHandlers.set(channel, handler); },@@ -120,7 +125,8 @@ function loadConnectorsRenderer(uiAlert: (message: string) => { alerts.push(message); },uiConfirmDanger: async () => true,uiConfirm: confirmInstall,- setView: () => {},+ uiToast: (message: string) => { toasts.push(message); },+ setView: (view: string) => { views.push(view); },setChatRecipient: () => {},setChatConnector: () => {},// Echo the key so assertions can match on it without depending on locale copy.@@ -146,6 +152,10 @@ function loadConnectorsRenderer(context.__clicks = clicks;context.__events = events;context.__errors = errors;+ context.__views = views;+ context.__settingsTabs = settingsTabs;+ context.__toasts = toasts;+ context.__apiKeyInput = apiKeyInput;context.__emitPush = (channel: string, payload: any) => pushHandlers.get(channel)?.(payload);context.__emitWindow = (name: string, payload?: any) => {for (const handler of windowHandlers.get(name) || []) handler(payload);@@ -189,6 +199,40 @@ function degradedGscInstance(lastVerifiedAt: number) {}describe('connectors panel — degraded cards never claim 已连接', () => {+ it('routes a paid connector to Settings → Models before OAuth when the API key is missing', async () => {+ const invoke = vi.fn(async (channel: string) => {+ if (channel === 'orkasApi.getStatus') {+ return { ok: true, configured: false, connectorAccess: false };+ }+ return { ok: true };+ });+ const ctx = loadConnectorsRenderer(invoke);++ await ctx._runConnect({+ id: 'composio-mail',+ display_name: 'Mail',+ auth_mode: 'composio',+ requires_credits: true,+ });+ ctx.__advanceTimers(0);++ expect(ctx.__views).toEqual(['settings']);+ expect(ctx.__settingsTabs).toEqual(['credentials']);+ expect(ctx.__apiKeyInput.focus).toHaveBeenCalledOnce();+ expect(ctx.__toasts).toEqual(['connectors.errors.api_key_required']);+ expect(invoke).not.toHaveBeenCalledWith('connectors.start_oauth', expect.anything());+ });++ it('starts a paid connection with a locally configured key without requiring cached permissions', async () => {+ const invoke = vi.fn(async (channel: string) => channel === 'orkasApi.getStatus'+ ? { ok: true, configured: true, scopes: [] }+ : { ok: true, started: true, attempt_id: 'offline-configured' });+ const ctx = loadConnectorsRenderer(invoke);+ await ctx._runConnect({ id: 'composio-mail', auth_mode: 'composio', requires_credits: true });+ expect(invoke).toHaveBeenCalledWith('connectors.start_oauth', { catalog_id: 'composio-mail' });+ expect(ctx.__views).toEqual([]);+ });+it('renders the failure reason and staleness instead of the connected treatment', () => {const ctx = loadConnectorsRenderer();const sixDaysAgo = Date.now() - 6 * 24 * 60 * 60 * 1000;diff --git a/test/renderer/settings-orkas-api.test.ts b/test/renderer/settings-orkas-api.test.tsindex a9e98cb7..a57ebb5a 100644--- a/test/renderer/settings-orkas-api.test.ts+++ b/test/renderer/settings-orkas-api.test.ts@@ -21,6 +21,7 @@ class FakeElement {removeAttribute(name: string) { this.attributes.delete(name); }appendChild(child: FakeElement) { this.children.push(child); return child; }querySelector() { return null; }+ focus() { this.setAttribute('data-focused', 'true'); }addEventListener(type: string, handler: (event?: any) => unknown) {const handlers = this.listeners.get(type) || [];@@ -46,6 +47,13 @@ function loadQuickSetupHarness(language = 'en') {'settings-orkas-api-key-input','settings-orkas-api-configure','settings-orkas-api-status',+ 'settings-orkas-api-saved',+ 'settings-orkas-api-key-masked',+ 'settings-orkas-api-key-meta',+ 'settings-orkas-api-edit',+ 'settings-orkas-api-delete',+ 'settings-orkas-api-editor',+ 'settings-orkas-api-cancel','settings-entries','settings-search-entries','settings-image-entries',@@ -53,7 +61,24 @@ function loadQuickSetupHarness(language = 'en') {'settings-tts-entries',]) elements.set(id, new FakeElement());- const invoke = vi.fn(async () => ({ ok: true }));+ const invoke = vi.fn(async (channel: string) => {+ if (channel === 'orkasApi.getStatus') return {+ ok: true,+ configured: false,+ keyMasked: '',+ name: '',+ connectorAccess: false,+ };+ if (channel === 'orkasApi.save') return {+ ok: true,+ configured: true,+ keyMasked: 'orka…-key',+ name: 'Desktop key',+ connectorAccess: true,+ };+ if (channel === 'orkasApi.remove') return { ok: true, removed: true };+ return { ok: true };+ });const refreshModelGuard = vi.fn(async () => true);const context: any = {console,@@ -78,6 +103,7 @@ function loadQuickSetupHarness(language = 'en') {clearInterval,URL,refreshModelGuard,+ uiConfirm: vi.fn(async () => true),};vm.createContext(context);vm.runInContext(source, context, { filename: 'settings.js' });@@ -112,12 +138,13 @@ describe('Orkas public API quick setup', () => {expect(css).not.toMatch(/\.settings-orkas-api-group\s*{[^}]*(?:linear-gradient|border-color)/s);});- it('keeps the configure action as wide as the create-key action', () => {+ it('lays out saved credentials and editing actions without exposing the raw key', () => {const css = readFileSync(resolve(__dirname, '../../src/renderer/style.css'), 'utf8');expect(css).toMatch(/\.settings-orkas-api-group\s*{[^}]*display:\s*grid;[^}]*grid-template-columns:\s*minmax\(0,\s*1fr\)\s+max-content;/s);expect(css).toMatch(/\.settings-orkas-api-head\s*{[^}]*display:\s*contents;/s);- expect(css).toMatch(/\.settings-orkas-api-group\s+\.settings-orkas-api-configure-row\s*{[^}]*display:\s*contents;/s);- expect(css).toMatch(/\.settings-orkas-api-configure-row\s+\.btn\s*{[^}]*grid-column:\s*2;[^}]*width:\s*100%;/s);+ expect(css).toContain('.settings-orkas-api-saved');+ expect(css).toContain('.settings-orkas-api-key-summary code');+ expect(css).toContain('.settings-orkas-api-actions');});it('uses the complete Orkas service labels in pickers and configured rows', () => {@@ -189,15 +216,16 @@ describe('Orkas public API quick setup', () => {.toContain('GPT-5.6 Sol · Claude Opus 5 · Kimi K3');});- it('configures all services from the real card click binding without exposing a clear action', async () => {+ it('validates and saves the shared credential from the real card click binding', async () => {const { context, elements, html, source, invoke, refreshModelGuard } = loadQuickSetupHarness();for (const id of ['settings-orkas-api-group','settings-orkas-api-key-input','settings-orkas-api-configure',+ 'settings-orkas-api-edit',+ 'settings-orkas-api-delete',]) expect(html).toContain(`id="${id}"`);- expect(html).not.toContain('settings-orkas-api-clear');- expect(source).not.toContain('orkasApi.clearAll');+ expect(source).toContain('orkasApi.remove');expect(source).not.toContain('/v1/capabilities');elements.get('settings-orkas-api-key-input')!.value = ' public-orkas-key ';@@ -207,7 +235,7 @@ describe('Orkas public API quick setup', () => {expect(invoke).toHaveBeenCalledWith('auth.openExternal', {url: 'https://orkas.ai/views/account/account.html?lang=en#api-keys',});- expect(invoke).toHaveBeenCalledWith('orkasApi.configureAll', {+ expect(invoke).toHaveBeenCalledWith('orkasApi.save', {apiKey: 'public-orkas-key',});expect(elements.get('settings-orkas-api-key-input')!.value).toBe('');@@ -215,6 +243,33 @@ describe('Orkas public API quick setup', () => {expect(refreshModelGuard).toHaveBeenCalledOnce();});+ it('keeps the masked credential visible and supports edit and delete', async () => {+ const { context, elements, invoke } = loadQuickSetupHarness();+ vm.runInContext(`+ _settingsState.orkasApiCredential = {+ configured: true,+ keyMasked: 'orka…1234',+ name: 'Desktop key',+ connectorAccess: true,+ };+ _settingsRenderOrkasApiCard();+ `, context);++ expect(elements.get('settings-orkas-api-saved')!.hidden).toBe(false);+ expect(elements.get('settings-orkas-api-editor')!.hidden).toBe(true);+ expect(elements.get('settings-orkas-api-key-masked')!.textContent).toBe('orka…1234');+ expect(elements.get('settings-orkas-api-key-meta')!.textContent).toBe('Desktop key');++ await elements.get('settings-orkas-api-edit')!.click();+ expect(elements.get('settings-orkas-api-editor')!.hidden).toBe(false);+ expect(elements.get('settings-orkas-api-key-input')!.getAttribute('data-focused')).toBe('true');++ await elements.get('settings-orkas-api-delete')!.click();+ expect(invoke).toHaveBeenCalledWith('orkasApi.remove');+ expect(elements.get('settings-orkas-api-status')!.getAttribute('data-i18n'))+ .toBe('settings.orkas_api.delete_ok');+ });+it.each(['zh', 'en', 'ja', 'pt'])('carries the %s desktop language to the API-key page', async (language) => {const { elements, invoke } = loadQuickSetupHarness(language);@@ -254,10 +309,10 @@ describe('Orkas public API quick setup', () => {const { elements, invoke } = loadQuickSetupHarness();const keyInput = elements.get('settings-orkas-api-key-input')!;await keyInput.dispatch('keydown', { key: 'Enter', isComposing: false });- expect(invoke).not.toHaveBeenCalledWith('orkasApi.configureAll', expect.anything());+ expect(invoke).not.toHaveBeenCalledWith('orkasApi.save', expect.anything());keyInput.value = 'enter-key';await keyInput.dispatch('keydown', { key: 'Enter', isComposing: false });- expect(invoke).toHaveBeenCalledWith('orkasApi.configureAll', { apiKey: 'enter-key' });+ expect(invoke).toHaveBeenCalledWith('orkasApi.save', { apiKey: 'enter-key' });});});