Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Harden connector discovery, downloads and OAuth lifetimes
wytc185215ccd1e
diff --git a/bin/connector-discovery-contract.cjs b/bin/connector-discovery-contract.cjsindex f163939b..1a444704 100644--- a/bin/connector-discovery-contract.cjs+++ b/bin/connector-discovery-contract.cjs@@ -29,7 +29,15 @@ exports.shape = z => Object.fromEntries(Object.entries(exports.inputSchema.prope// exact-schema conflicts and the search-versus-browse default choice.if (context.input === undefined) return undefined;if (defaultNumericRange(context.input, undefined, 1, 50) !== context.input) return context.input;- throw context.error;+ // Zod 4 catch contexts carry a plain issue object with child-local paths.+ // Preserve the previous Error envelope, field name and integer wording+ // so MCP callers receive an actionable refusal before host discovery.+ throw new z.ZodError(context.error.issues.map(issue => ({+ ...issue,+ path: [key, ...issue.path],+ ...(issue.code === 'invalid_type' && issue.expected === 'int'+ ? { message: 'Expected integer, received float' } : {}),+ })));}): value.optional()).describe(field.description)];}));diff --git a/bin/proxy-bootstrap.cjs b/bin/proxy-bootstrap.cjsindex be810404..29e07a20 100644--- a/bin/proxy-bootstrap.cjs+++ b/bin/proxy-bootstrap.cjs@@ -90,7 +90,11 @@ function createBridgeFetch(nativeFetch, bridgeUrl, bridgeToken) {throw new Error(`system fetch bridge failed: ${detail}`);}const responseMeta = decodeMeta(response.headers.get('x-orkas-fetch-meta'));- return new Response(response.body, {+ // Lock the transport body into its own pipe before wrapping it. Undici's+ // Response finalizer can cancel a shared, unlocked stream when the+ // transport Response is collected before the caller reads this wrapper.+ const body = response.body?.pipeThrough(new TransformStream()) ?? null;+ return new Response(body, {status: responseMeta.status,statusText: responseMeta.statusText,headers: responseMeta.headers,diff --git a/src/main/features/connectors/bootstrap.ts b/src/main/features/connectors/bootstrap.tsindex eb840255..cb1ae571 100644--- a/src/main/features/connectors/bootstrap.ts+++ b/src/main/features/connectors/bootstrap.ts@@ -4,11 +4,9 @@* tool schemas; only uncached, stale, or repair-needed rows connect during bootstrap. The first* real tool call reconnects a cached instance on demand.*- * Process-quit hook calls `manager.shutdownAll()` so stdio subprocesses (MCP servers) exit- * cleanly instead of becoming zombies — symmetrical to the cleanup that `local_agents/runner.ts`- * runs for its own spawned CLIs.+ * The shared app shutdown coordinator awaits `shutdown()` before installer+ * handoff; an asynchronous before-quit listener cannot delay Electron exit.*/-import { app } from 'electron';import * as manager from './manager';import { createLogger } from '../../logger';@@ -16,7 +14,6 @@ const log = createLogger('connectors');let _bootPromise: Promise<void> | null = null;let _bootUid: string | null = null;-let _quitHookInstalled = false;async function _doBootstrap(uid: string): Promise<void> {try {@@ -26,18 +23,19 @@ async function _doBootstrap(uid: string): Promise<void> {}}-function _installQuitHook(): void {- if (_quitHookInstalled) return;- _quitHookInstalled = true;- app.on('before-quit', () => {- manager.shutdownAll().catch((err) => {- log.warn('connectors shutdownAll failed', { error: (err as Error).message });- });- });+export async function shutdown(): Promise<void> {+ let timer: NodeJS.Timeout | undefined;+ try {+ await Promise.race([+ manager.shutdownAll(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('Connector shutdown timed out')), 5_000);+ }),+ ]);+ } finally { if (timer) clearTimeout(timer); }}export function bootstrap(uid: string): Promise<void> {- _installQuitHook();if (!_bootPromise || _bootUid !== uid) {_bootUid = uid;_bootPromise = _doBootstrap(uid);diff --git a/src/main/features/connectors/catalog.ts b/src/main/features/connectors/catalog.tsindex 3c74ba55..1cd7613f 100644--- a/src/main/features/connectors/catalog.ts+++ b/src/main/features/connectors/catalog.ts@@ -527,6 +527,11 @@ export function connectorCatalog(): CatalogEntry[] {return structuredClone(Array.from(catalogIndex().values()));}+/** Membership checks must not clone catalog transport, policy or icon data. */+export function isCatalogConnectorId(id: string): boolean {+ return catalogIndex().has(id);+}+export function findCatalogEntry(id: string): CatalogEntry | null {const entry = catalogIndex().get(id);// Callers may prepare transport/policy data locally without changing future lookups.diff --git a/src/main/features/connectors/index.ts b/src/main/features/connectors/index.tsindex 0512a85a..4243ddb2 100644--- a/src/main/features/connectors/index.ts+++ b/src/main/features/connectors/index.ts@@ -1,4 +1,4 @@-export { bootstrap } from './bootstrap';+export { bootstrap, shutdown } from './bootstrap';export {listInstances,getInstance,diff --git a/src/main/features/connectors/local-cli-downloads.ts b/src/main/features/connectors/local-cli-downloads.tsnew file mode 100644index 00000000..3d8fc158--- /dev/null+++ b/src/main/features/connectors/local-cli-downloads.ts@@ -0,0 +1,79 @@+import * as fs from 'node:fs/promises';+import * as os from 'node:os';+import * as path from 'node:path';+import { isPathAllowed } from '../../util/path-sandbox';+import { createLogger } from '../../logger';+import { logErrorSummary } from '../../util/log-redact';++const log = createLogger('connectors:local-cli-downloads');++/** Download receipts use the pinned Lark message-resource contract. Other+ * provider actions are left untouched; names alone do not authorize file IO. */+export function isLarkMessageDownload(name: string, args: Record<string, unknown>): boolean {+ return name === 'execute_write' && typeof args.action === 'string'+ && args.action.trim().split(/[. ]+/).join('.') === 'im.+messages-resources-download';+}++export async function receiveLocalCliDownload(+ userId: string,+ conversationId: string | undefined,+ invoke: (directory: string) => Promise<unknown>,+ assertActive: () => void,+): Promise<unknown> {+ if (!conversationId || conversationId.includes('/') || conversationId.includes('\\')+ || conversationId.includes('\0') || conversationId === '.' || conversationId === '..') {+ throw new Error('A current conversation is required to receive this download.');+ }+ assertActive();+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'orkas-cli-download-')).catch(() => {+ throw new Error('A temporary directory could not be created for this download.');+ });+ try {+ assertActive();+ const raw = await invoke(directory);+ assertActive();+ if (raw && typeof raw === 'object' && (raw as { isError?: boolean }).isError) return raw;+ const receipt = raw as { content?: Array<{ type?: string; text?: string }> } | null;+ const text = receipt?.content?.find(part => part.type === 'text' && typeof part.text === 'string');+ let payload;+ try { payload = JSON.parse(text?.text || ''); }+ catch { throw new Error('The download did not return a valid file receipt.'); }+ const data = payload?.result?.data;+ const source = data?.saved_path;+ if (payload?.result?.ok !== true || typeof source !== 'string'+ || !Number.isSafeInteger(data?.size_bytes) || data.size_bytes < 0) {+ throw new Error('The download did not return a complete file receipt.');+ }+ const sourcePath = path.resolve(directory, source);+ if (!isPathAllowed(sourcePath, [directory])) throw new Error('The download returned a file outside its staging directory.');+ const stat = await fs.lstat(sourcePath).catch(() => {+ throw new Error('The downloaded file is unavailable.');+ });+ if (!stat.isFile() || stat.nlink !== 1 || stat.size !== data.size_bytes) {+ throw new Error('The downloaded file could not be verified.');+ }+ assertActive();+ // Reuse attachment locking, size/type limits, project layout, atomic+ // publication, collision handling and cloud-sync ownership.+ const attachments = await import('../chat_attachments');+ assertActive();+ const imported = await attachments.importAttachmentFromPath(userId, conversationId, sourcePath);+ if (!imported.ok) throw new Error('The downloaded file could not be saved as a conversation attachment.');+ const resolved = attachments.resolveAttachmentAbsPath(userId, conversationId, imported.info.name);+ if (!resolved.ok) throw new Error('The downloaded attachment could not be opened.');+ attachments.recordGeneratedAttachment(userId, conversationId, resolved.absPath);+ data.saved_path = resolved.absPath;+ data.size_bytes = imported.info.bytes;+ return {+ ...receipt,+ content: receipt!.content!.map(part => part === text ? { ...part, text: JSON.stringify(payload, null, 2) } : part),+ };+ } finally {+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 2, retryDelay: 20 }).catch(error => {+ // Publication may already be durable. Cleanup must preserve the receipt+ // (or the provider's original failure), so callers never replay it.+ const { message_hash, message_chars } = logErrorSummary(error);+ log.warn('temporary download cleanup failed', { error: { message_hash, message_chars } });+ });+ }+}diff --git a/src/main/features/connectors/local-cli.ts b/src/main/features/connectors/local-cli.tsindex b884a113..8be835a9 100644--- a/src/main/features/connectors/local-cli.ts+++ b/src/main/features/connectors/local-cli.ts@@ -221,6 +221,9 @@ function localCliEnv(uid: string, entry: CatalogEntry): Record<string, string> {fs.mkdirSync(runtimeDir, { recursive: true, mode: 0o700 });fs.mkdirSync(workDir, { recursive: true, mode: 0o700 });return withBackgroundNodeEnv({+ // npm lifecycle scripts and Windows command shims invoke bare `node`.+ // Keep their runtime aligned with the explicitly selected helper runtime.+ PATH: [path.dirname(runtime.executable), buildSandboxEnv(undefined).PATH].join(path.delimiter),ORKAS_LOCAL_CLI_PROVIDER: config.provider,ORKAS_LOCAL_CLI_BRAND: config.brand || '',ORKAS_LOCAL_CLI_PACKAGE: `${config.package_name}@${config.package_version}`,diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.tsindex 9846f05b..f3ddd2f7 100644--- a/src/main/features/connectors/manager.ts+++ b/src/main/features/connectors/manager.ts@@ -20,6 +20,7 @@ import { app } from 'electron';import * as registry from './registry';import * as paths from '../../paths';import { McpConnection } from './mcp-client';+import { isLarkMessageDownload, receiveLocalCliDownload } from './local-cli-downloads';import { connectorCatalog, findCatalogEntry } from './catalog';import { applyTemplate } from './apply-template';import { resolveCatalogConnection } from './connection-parameters';@@ -568,10 +569,12 @@ async function _markDegradedOnTransientFailure(error: logErrorSummary(err),});const current = registry.load(uid).connections[inst.id] || inst;- return _patchStatus(uid, current, (cur) => ({- ..._asDegradedFromCache(cur, message),- updated_at: _nowIso(),- }), statusPatches);+ return _patchStatus(uid, current, (cur) => {+ const degraded = _asDegradedFromCache(cur, message);+ return { ...degraded,+ updated_at: _nowIso(),+ };+ }, statusPatches);}function _normalizeTransientStatusForList(inst: ConnectorInstance): ConnectorInstance {@@ -1995,7 +1998,7 @@ export async function callTool(id: string,name: string,args: Record<string, unknown>,- opts: { signal?: AbortSignal } = {},+ opts: { signal?: AbortSignal; conversationId?: string } = {},): Promise<unknown> {if (!uid) throw new Error('uid required');if (isConnectorActionBlocked(id, name)) throw new Error('E_CONNECTOR_ACTION_UNAVAILABLE: this action is not available in Orkas');@@ -2063,16 +2066,26 @@ export async function callTool(_connectAndCacheTools(uid, inst, undefined, runtimeEpoch), opts.signal,);conn = _conns.get(runtimeKey);- if (!conn?.isConnected) throw new Error(_connectFailureMessage(id, updated));+ if (!conn?.isConnected) {+ throw new Error(_connectFailureMessage(id, updated));+ }}_assertRuntimeEpoch(runtimeEpoch);try {const requestOpts = {...(opts.signal ? { signal: opts.signal } : {}),};- const result = Object.keys(requestOpts).length- ? await conn.callTool(name, args, requestOpts)- : await conn.callTool(name, args);+ const invoke = (localFileOutputDirectory?: string) => {+ const options = { ...requestOpts, ...(localFileOutputDirectory ? { localFileOutputDirectory } : {}) };+ return Object.keys(options).length ? conn.callTool(name, args, options) : conn.callTool(name, args);+ };+ const result = entry?.auth_mode === 'local_cli' && entry.local_cli?.provider === 'lark'+ && isLarkMessageDownload(name, args)+ ? await receiveLocalCliDownload(uid, opts.conversationId, invoke, () => {+ _assertRuntimeEpoch(runtimeEpoch);+ if (opts.signal?.aborted) throw _connectorCancelledError(opts.signal.reason);+ })+ : await invoke();_assertRuntimeEpoch(runtimeEpoch);const adapterResult = result as { isError?: boolean; _meta?: { orkas?: { errorCode?: string } } } | null;const adapterCode = adapterResult?._meta?.orkas?.errorCode;diff --git a/src/main/features/connectors/mcp-client.ts b/src/main/features/connectors/mcp-client.tsindex 00191d02..0189734f 100644--- a/src/main/features/connectors/mcp-client.ts+++ b/src/main/features/connectors/mcp-client.ts@@ -80,11 +80,15 @@ export function normalizeMcpToolSchema(tool: McpToolLike): ToolSchema {import { createLogger } from '../../logger';import { buildChildProxyEnvironment } from '../../util/proxy-dispatcher';import { logErrorSummary } from '../../util/log-redact';+import { captureWindowsShutdownProcesses, hasCapturedWindowsAppProcess } from '../../util/windows-shutdown-processes';+import type { ShutdownProcesses } from '../../util/shutdown';const log = createLogger('connectors:mcp');interface SdkBundle {Client: typeof import('@modelcontextprotocol/sdk/client/index.js').Client;+ StreamableHTTPError: typeof import('@modelcontextprotocol/sdk/client/streamableHttp.js').StreamableHTTPError;+ SseError: typeof import('@modelcontextprotocol/sdk/client/sse.js').SseError;StdioClientTransport: typeof import('@modelcontextprotocol/sdk/client/stdio.js').StdioClientTransport;StreamableHTTPClientTransport: typeof import('@modelcontextprotocol/sdk/client/streamableHttp.js').StreamableHTTPClientTransport;SSEClientTransport: typeof import('@modelcontextprotocol/sdk/client/sse.js').SSEClientTransport;@@ -102,6 +106,8 @@ async function _loadSdk(): Promise<SdkBundle> {]);_sdk = {Client: clientMod.Client,+ StreamableHTTPError: httpMod.StreamableHTTPError,+ SseError: sseMod.SseError,StdioClientTransport: stdioMod.StdioClientTransport,StreamableHTTPClientTransport: httpMod.StreamableHTTPClientTransport,SSEClientTransport: sseMod.SSEClientTransport,@@ -109,6 +115,21 @@ async function _loadSdk(): Promise<SdkBundle> {return _sdk;}+/** Preserve HTTP meaning from SDK-owned error classes without parsing provider text.+ * The SDK numeric code remains untouched for its transport fallback decisions. */+function tagTransportFailure(error: unknown): void {+ if (!_sdk || !(error instanceof _sdk.StreamableHTTPError || error instanceof _sdk.SseError)) return;+ const status = error.code;+ const diagnosticCode = status === 401 || status === 403 ? 'E_TOOL_CALL_AUTH'+ : status === 429 ? 'E_TOOL_CALL_RATE_LIMIT'+ : status === 408 || status === 504 ? 'E_TOOL_CALL_TIMEOUT'+ : typeof status === 'number' && status >= 500 && status <= 599 ? 'E_TOOL_CALL_UPSTREAM'+ : undefined;+ if (diagnosticCode && Object.isExtensible(error)) {+ Object.defineProperty(error, 'orkasErrorCode', { value: diagnosticCode, configurable: true });+ }+}+const CLIENT_INFO = { name: 'orkas-pc', version: '0.1.0' };const DEFAULT_CONNECT_TIMEOUT_MS = 30 * 1000;const DEFAULT_LIST_TOOLS_TIMEOUT_MS = 30 * 1000;@@ -131,10 +152,37 @@ function resolveMcpConnectTimeoutMs(kind: Transport['kind']): number {export interface McpRequestOptions {signal?: AbortSignal;timeoutMs?: number;+ /** Host-owned staging directory, supplied only to the local CLI adapter. */+ localFileOutputDirectory?: string;+}++async function closeOwnedTransport(+ transport: import('@modelcontextprotocol/sdk/shared/transport.js').Transport,+ close: () => Promise<void>,+): Promise<void> {+ let processes: ShutdownProcesses | undefined;+ try {+ try {+ if (process.platform === 'win32' && _sdk && transport instanceof _sdk.StdioClientTransport+ && transport.pid && !hasCapturedWindowsAppProcess(transport.pid)) {+ // SDK close ends stdin before killing its direct child. Pin descendants+ // first: an EOF-aware wrapper can otherwise orphan a persistent server+ // long before the application's final shutdown snapshot is taken.+ processes = await captureWindowsShutdownProcesses('win32', transport.pid);+ }+ } finally {+ // Always release the SDK channel, including when discovery is unavailable.+ await close();+ }+ await processes?.terminate();+ } finally {+ processes?.dispose();+ }}export class McpConnection {private _client: import('@modelcontextprotocol/sdk/client/index.js').Client | null = null;+ private _closing: Promise<void> | null = null;private _connected = false;constructor(private readonly id: string, private readonly transport: Transport) {}@@ -142,6 +190,7 @@ export class McpConnection {get isConnected(): boolean { return this._connected; }async connect(): Promise<void> {+ if (this._closing) await this._closing;if (this._connected) return;const startedAt = Date.now();const sdk = await _loadSdk();@@ -166,6 +215,18 @@ export class McpConnection {stderr: 'pipe',...(this.transport.cwd ? { cwd: this.transport.cwd } : {}),});+ if (process.platform === 'win32') {+ const close = stdioTransport.close.bind(stdioTransport);+ let closing: Promise<void> | null = null;+ // The SDK also closes on failed initialization, before connect rejects.+ // Guard the transport itself so every close pins the same process tree.+ stdioTransport.close = () => closing ||= closeOwnedTransport(stdioTransport, close).catch(err => {+ log.warn('stdio process cleanup failed', {+ id: this.id.startsWith('custom-') ? 'custom' : this.id,+ error: logErrorSummary(err),+ });+ });+ }// Provider diagnostics can contain credentials or user data. Drain without// retaining them; lifecycle and request errors use the host's structured logs.stdioTransport.stderr?.on('data', () => {});@@ -234,13 +295,14 @@ export class McpConnection {timeout_ms: connectTimeoutMs,});} catch (err) {+ tagTransportFailure(err);log.warn('connect failed', {id: this.id.startsWith('custom-') ? 'custom' : this.id,transport: activeTransportKind,duration_ms: Date.now() - startedAt,error: logErrorSummary(err),});- try { await transport.close?.(); } catch (closeErr) {+ try { await transport.close(); } catch (closeErr) {log.warn('transport close after connect failure failed', {id: this.id.startsWith('custom-') ? 'custom' : this.id,error: logErrorSummary(closeErr),@@ -265,7 +327,7 @@ export class McpConnection {const res = await this._client.listTools(cursor === undefined ? undefined : { cursor }, {timeout: remaining,...(opts.signal ? { signal: opts.signal } : {}),- });+ }).catch(error => { tagTransportFailure(error); throw error; });for (const tool of res.tools || []) tools.push(normalizeMcpToolSchema(tool));cursor = res.nextCursor;if (cursor !== undefined) {@@ -279,7 +341,9 @@ export class McpConnection {async callTool(name: string, args: Record<string, unknown>, opts: McpRequestOptions = {}): Promise<unknown> {if (!this._client || !this._connected) throw new Error('not connected');const res = await this._client.callTool(- { name, arguments: args },+ { name, arguments: args, ...(opts.localFileOutputDirectory ? {+ _meta: { 'orkas/local-file-output-directory': opts.localFileOutputDirectory },+ } : {}) },undefined,{timeout: opts.timeoutMs || DEFAULT_CALL_TOOL_TIMEOUT_MS,@@ -287,19 +351,21 @@ export class McpConnection {onprogress: () => {},...(opts.signal ? { signal: opts.signal } : {}),},- );+ ).catch(error => { tagTransportFailure(error); throw error; });return res;}- async close(): Promise<void> {- if (!this._client) return;- try {- await this._client.close();- } catch (err) {- log.warn('close failed', { id: this.id.startsWith('custom-') ? 'custom' : this.id, error: logErrorSummary(err) });- } finally {- this._client = null;- this._connected = false;- }+ close(): Promise<void> {+ if (this._closing) return this._closing;+ const client = this._client;+ if (!client) return Promise.resolve();+ this._client = null;+ this._connected = false;+ // Share the whole cleanup lifetime across disconnect/shutdown callers.+ this._closing = Promise.resolve().then(() => client.close())+ .catch(err => {+ log.warn('close failed', { id: this.id.startsWith('custom-') ? 'custom' : this.id, error: logErrorSummary(err) });+ }).finally(() => { this._closing = null; });+ return this._closing;}}diff --git a/src/main/features/connectors/oauth-dcr.ts b/src/main/features/connectors/oauth-dcr.tsindex 2e371c0b..9baf770b 100644--- a/src/main/features/connectors/oauth-dcr.ts+++ b/src/main/features/connectors/oauth-dcr.ts@@ -655,7 +655,7 @@ async function _startDcrOAuth(};_pending = pending;shell.openExternal(authUrl.toString()).catch(() => {- if (_pending === pending) _cancelPending('failed to open authorization browser');+ if (_pending === pending) _cancelPending('failed to open authorization browser', 'browser_open_failed');});});}diff --git a/src/main/features/connectors/tool-discovery.ts b/src/main/features/connectors/tool-discovery.tsindex 78bbfdde..3bf3fe70 100644--- a/src/main/features/connectors/tool-discovery.ts+++ b/src/main/features/connectors/tool-discovery.ts@@ -36,35 +36,38 @@ export interface DiscoveryResult {tools?: DiscoveredTool[];connectors?: { id: string; name: string; tool_count: number }[];}+export type DiscoveryValidationReason = 'unknown_field' | 'invalid_connector_id' | 'invalid_tool_name'+ | 'invalid_query' | 'query_too_long' | 'invalid_limit' | 'invalid_offset'+ | 'connector_id_required' | 'conflicting_fields';export class ConnectorDiscoveryError extends Error {- constructor(public readonly code: string, message: string) { super(message); }+ constructor(public readonly code: string, message: string, public readonly reason?: DiscoveryValidationReason) { super(message); }}export function validateDiscoveryParams(raw: Record<string, unknown>): Params {- const bad = (message: string): never => { throw new ConnectorDiscoveryError('E_BAD_INPUT', message); };+ const bad = (reason: DiscoveryValidationReason, message: string): never => { throw new ConnectorDiscoveryError('E_BAD_INPUT', message, reason); };const fields = ['connector_id', 'tool_name', 'query', 'limit', 'offset'];const unknown = Object.keys(raw).find(key => !fields.includes(key));if (unknown !== undefined) {const field = unknown.length > 80 ? `${unknown.slice(0, 80)}…` : unknown;- bad(`unsupported discovery field ${JSON.stringify(field)}; allowed fields: ${fields.join(', ')}`);+ bad('unknown_field', `unsupported discovery field ${JSON.stringify(field)}; allowed fields: ${fields.join(', ')}`);}const params: Params = {};for (const key of ['connector_id', 'tool_name', 'query'] as const) {if (raw[key] === undefined) continue;- if (typeof raw[key] !== 'string' || !raw[key].trim()) bad(`${key} must be a non-empty string`);+ if (typeof raw[key] !== 'string' || !raw[key].trim()) bad(`invalid_${key}`, `${key} must be a non-empty string`);params[key] = (raw[key] as string).trim();}- if (params.query && params.query.length > 1024) bad('query must be at most 1024 characters');+ if (params.query && params.query.length > 1024) bad('query_too_long', 'query must be at most 1024 characters');for (const key of ['limit', 'offset'] as const) {if (raw[key] === undefined) continue;const value = key === 'limit' ? defaultNumericRange(raw[key], params.query ? 8 : 20, 1, 50) : raw[key];if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < (key === 'limit' ? 1 : 0) || (key === 'limit' && value > 50)) {- bad(key === 'limit' ? 'limit must be an integer from 1 to 50' : `offset must be an integer from 0 to ${Number.MAX_SAFE_INTEGER}`);+ bad(`invalid_${key}`, key === 'limit' ? 'limit must be an integer from 1 to 50' : `offset must be an integer from 0 to ${Number.MAX_SAFE_INTEGER}`);}params[key] = value as number;}- if (params.tool_name && !params.connector_id) bad('`connector_id` is required when `tool_name` is provided');- if (params.tool_name && (params.query !== undefined || Object.hasOwn(raw, 'limit') || params.offset !== undefined)) bad('tool_name cannot be combined with query, limit or offset');+ if (params.tool_name && !params.connector_id) bad('connector_id_required', '`connector_id` is required when `tool_name` is provided');+ if (params.tool_name && (params.query !== undefined || Object.hasOwn(raw, 'limit') || params.offset !== undefined)) bad('conflicting_fields', 'tool_name cannot be combined with query, limit or offset');return params;}diff --git a/src/main/features/connectors/types.ts b/src/main/features/connectors/types.tsindex c26e59cc..440762bd 100644--- a/src/main/features/connectors/types.ts+++ b/src/main/features/connectors/types.ts@@ -88,6 +88,7 @@ export type ConnectorStatus =* began again from zero. These two fields are persisted precisely so a cooldown survives restart. */| {kind: 'degraded';+ /** Closed diagnostic only; older clients ignore this additive metadata. */message: string;at: number;last_verified_at?: number;diff --git a/src/main/model/core-agent/connector-meta-tools.ts b/src/main/model/core-agent/connector-meta-tools.tsindex 6348177f..609a6a48 100644--- a/src/main/model/core-agent/connector-meta-tools.ts+++ b/src/main/model/core-agent/connector-meta-tools.ts@@ -428,7 +428,7 @@ function createCallConnectorToolTool(opts: ConnectorMetaToolsOpts): AgentTool {);}}- const raw = await manager.callTool(opts.userId, cid, toolName, normalizedArgs, { signal: ctx.signal });+ const raw = await manager.callTool(opts.userId, cid, toolName, normalizedArgs, { signal: ctx.signal, conversationId: opts.cid });if (!ctx.signal?.aborted) observeTaskDraftResult(draftScope, toolName, normalizedArgs, raw);const content = stringifyMcpResult(raw);const protocolError = !!raw && typeof raw === 'object' && (raw as { isError?: unknown }).isError === true;diff --git a/test/main/features/connectors/bootstrap.test.ts b/test/main/features/connectors/bootstrap.test.tsindex f76add60..7550c92f 100644--- a/test/main/features/connectors/bootstrap.test.ts+++ b/test/main/features/connectors/bootstrap.test.ts@@ -34,16 +34,33 @@ describe('connectors bootstrap lifecycle', () => {await feature.bootstrap('account-b');expect(mocks.bootstrap).toHaveBeenCalledTimes(2);expect(mocks.bootstrap).toHaveBeenNthCalledWith(2, 'account-b');- expect(mocks.appOn).toHaveBeenCalledTimes(1);+ expect(mocks.appOn).not.toHaveBeenCalled();});- it('closes connector transports from the single process quit hook', async () => {+ it('lets the shutdown coordinator await connector transport exit', async () => {const feature = await import('../../../../src/main/features/connectors/bootstrap');await feature.bootstrap('account-a');- const beforeQuit = mocks.appOn.mock.calls.find(([event]) => event === 'before-quit')?.[1];- expect(beforeQuit).toBeTypeOf('function');+ let release!: () => void;+ mocks.shutdownAll.mockImplementationOnce(() => new Promise<void>(resolve => { release = resolve; }));+ let done = false;+ const pending = feature.shutdown().then(() => { done = true; });+ await Promise.resolve();+ expect(done).toBe(false);+ expect(mocks.shutdownAll).toHaveBeenCalledOnce();+ release();+ await pending;+ expect(done).toBe(true);+ });- beforeQuit();- await vi.waitFor(() => expect(mocks.shutdownAll).toHaveBeenCalledTimes(1));+ it('bounds a stalled connector close so process cleanup can finish shutdown', async () => {+ vi.useFakeTimers();+ try {+ const feature = await import('../../../../src/main/features/connectors/bootstrap');+ mocks.shutdownAll.mockImplementationOnce(() => new Promise<void>(() => {}));+ const pending = expect(feature.shutdown()).rejects.toThrow('Connector shutdown timed out');+ await vi.advanceTimersByTimeAsync(5_000);+ await pending;+ expect(vi.getTimerCount()).toBe(0);+ } finally { vi.useRealTimers(); }});});diff --git a/test/main/features/connectors/catalog-cache.test.ts b/test/main/features/connectors/catalog-cache.test.tsnew file mode 100644index 00000000..c5daeb7b--- /dev/null+++ b/test/main/features/connectors/catalog-cache.test.ts@@ -0,0 +1,97 @@+import * as fs from 'node:fs';+import * as path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { activateUser } from '../../../../src/main/features/users';+import { userRemoteConfigFile } from '../../../../src/main/paths';+import { ClientConfigManager } from '../../../../src/main/features/client_config';+import { writeJsonSync } from '../../../../src/main/storage';+import * as storage from '../../../../src/main/storage';+import * as registry from '../../../../src/main/features/connectors/registry';+import * as enabled from '../../../../src/main/features/component_enabled';+import { connectorCatalog, findCatalogEntry } from '../../../../src/main/features/connectors/catalog';+import { resolveVisibleConnectors } from '../../../../src/main/features/connectors/tools-adapter';+import type { ConnectorsFile } from '../../../../src/main/features/connectors/types';++const accounts = ['catalog-cache-a', 'catalog-cache-b'];+const entry = (id: string, name = id) => ({+ id, display_name: name, category: 'productivity', auth_mode: 'composio',+ composio: { toolkit: id, auth_config_id: 'ac_cache_fixture' },+ transport_template: null,+});++afterEach(() => {+ vi.restoreAllMocks();+ for (const uid of accounts) fs.rmSync(path.dirname(userRemoteConfigFile(uid)), { recursive: true, force: true });+});++describe('connector catalog cache', () => {+ it('keeps repeated visibility checks within one full config read while honoring live disconnects and user restrictions', async () => {+ const uid = accounts[0];+ activateUser(uid);+ // Match the multi-megabyte catalog behind the reported send/switch stall, without user data.+ const catalog = Array.from({ length: 133 }, (_, index) => ({+ ...entry(`cache-service-${index}`), icon_svg: `<svg>${'x'.repeat(28_000)}</svg>`,+ }));+ const file = userRemoteConfigFile(uid);+ writeJsonSync(file, { active: { immediate: { 'connectors.catalog': catalog } } });+ const state: ConnectorsFile = {+ version: 2, oauth_hints: {}, _deleted_at: {},+ connections: Object.fromEntries(catalog.slice(0, 10).map(item => [item.id, {+ id: item.id, origin: 'catalog', display_name: item.display_name,+ transport: null, status: { kind: 'connected' }, enabled_subtools: null,+ composio_grant: { connection_id: item.id, connection_token: 'a'.repeat(43), toolkit: item.id },+ tools_cache: [{ name: 'read_items', description: 'Read items', inputSchema: { type: 'object' } }],+ created_at: '2026-09-12T00:00:00Z', updated_at: '2026-09-12T00:00:00Z',+ }])),+ };+ vi.spyOn(registry, 'load').mockImplementation(() => structuredClone(state));+ const restrictions = { version: 1, agents: {}, skills: {}, connectors: {} as Record<string, boolean> };+ vi.spyOn(enabled, 'readEnabledMap').mockImplementation(() => restrictions);+ let configReads = 0;+ const originalRead = storage.readJsonSync;+ const reads = vi.spyOn(storage, 'readJsonSync').mockImplementation((target) => {+ // Retain counts, not hundreds of large return values if the IO regression comes back.+ reads.mockClear();+ if (target === file) configReads++;+ return originalRead(target);+ });+ for (let run = 0; run < 3; run++) {+ const visible = await resolveVisibleConnectors(uid);+ expect(visible).toHaveLength(10);+ expect(visible.every(item => item.tools[0]?.name === 'read_items')).toBe(true);+ }+ // Full-file IO is the synchronous blocking cost; this budget is independent of getter calls.+ expect(configReads).toBeLessThanOrEqual(1);+ state.connections['cache-service-0'].status = { kind: 'disconnected' };+ restrictions.connectors['cache-service-1'] = false;+ state.connections['cache-service-2'].enabled_subtools = [];+ const next = await resolveVisibleConnectors(uid);+ expect(next.map(item => item.instance.id)).not.toContain('cache-service-0');+ expect(next.map(item => item.instance.id)).not.toContain('cache-service-1');+ expect(next.find(item => item.instance.id === 'cache-service-2')?.tools).toEqual([]);+ state.connections = {};+ expect(await resolveVisibleConnectors(uid)).toEqual([]);+ });++ it('refreshes catalog metadata across same-hash updates and account switches without retaining caller mutations', () => {+ const manager = new ClientConfigManager();+ const apply = (name: string) => manager.applyServerPayload({+ config_hash: 'unchanged-hash', immediate: { 'connectors.catalog': [entry('cache-service', name)] }, restart: {},+ }, 'unchanged-etag');+ activateUser(accounts[0]);+ apply('Account A');+ const result = findCatalogEntry('cache-service')!;+ result.display_name = 'Mutated';+ result.composio!.toolkit = 'wrong-toolkit';+ connectorCatalog().find(item => item.id === 'cache-service')!.display_name = 'Also mutated';+ expect(findCatalogEntry('cache-service')).toMatchObject({ display_name: 'Account A', composio: { toolkit: 'cache-service' } });+ apply('Updated A');+ expect(findCatalogEntry('cache-service')?.display_name).toBe('Updated A');+ activateUser(accounts[1]);+ expect(findCatalogEntry('cache-service')).toBeNull();+ apply('Account B');+ expect(findCatalogEntry('cache-service')?.display_name).toBe('Account B');+ activateUser(accounts[0]);+ expect(findCatalogEntry('cache-service')?.display_name).toBe('Updated A');+ });+});diff --git a/test/main/features/connectors/custom-mcp-failures.test.ts b/test/main/features/connectors/custom-mcp-failures.test.tsnew file mode 100644index 00000000..96f5dbd3--- /dev/null+++ b/test/main/features/connectors/custom-mcp-failures.test.ts@@ -0,0 +1,242 @@+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';+import * as http from 'node:http';+import type { AddressInfo } from 'node:net';+import { captureMainLogWorkers } from '../../../helpers/capture-main-log-workers';++// Exercise the real registry -> manager -> McpConnection -> SDK -> loopback+// boundary. Peer receipts and actual effects prove remote execution and no replay.+type Fault = 'none' | 'initialize-auth' | 'initialize-forbidden' | 'initialize-rate-limit' | 'initialize-upstream' | 'initialize-deadline' | 'initialize-timeout' | 'initialize-other-server' | 'legacy-auth' | 'list-auth' | 'call-auth' | 'initialize-reset' | 'list-reset'+ | 'call-business' | 'call-reset-after-effect' | 'call-malformed';+const UID = 'u-custom-mcp-failure';+let fault: Fault;+let requests: string[];+let effects: number;+let authorization: string[];+let server: http.Server;+let endpoint: string;+let root: string;+let previousRoot: string | undefined;+let closeLogs: () => Promise<void>;+let manager: typeof import('../../../../src/main/features/connectors/manager');+let registry: typeof import('../../../../src/main/features/connectors/registry');++beforeEach(async () => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-custom-mcp-fault-'));+ previousRoot = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = root;+ vi.resetModules();+ closeLogs = await captureMainLogWorkers();+ fault = 'none'; requests = []; effects = 0; authorization = [];+ server = http.createServer(async (req, res) => {+ if (req.method !== 'POST') {+ if (fault === 'legacy-auth') { requests.push('sse/get'); res.writeHead(401); res.end('private-peer-response'); }+ else { res.writeHead(405); res.end(); }+ return;+ }+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(Buffer.from(chunk));+ const message = JSON.parse(Buffer.concat(chunks).toString('utf8'));+ requests.push(message.method);+ authorization.push(String(req.headers.authorization || ''));+ const handshakeStatus = ({ 'initialize-auth': 401, 'initialize-forbidden': 403,+ 'initialize-rate-limit': 429, 'initialize-upstream': 503,+ 'initialize-deadline': 408, 'initialize-timeout': 504, 'initialize-other-server': 599, 'legacy-auth': 405 } as Record<string, number>)[fault];+ if (message.method === 'initialize' && handshakeStatus) {+ res.writeHead(handshakeStatus); res.end('private-peer-response'); return;+ }+ if ((message.method === 'tools/list' && fault === 'list-auth')+ || (message.method === 'tools/call' && fault === 'call-auth')) {+ res.writeHead(401); res.end('private-peer-response'); return;+ }+ if ((message.method === 'initialize' && fault === 'initialize-reset')+ || (message.method === 'tools/list' && fault === 'list-reset')) {+ req.socket.destroy(); return;+ }+ if (message.method === 'notifications/initialized') { res.writeHead(202); res.end(); return; }+ let result: unknown;+ if (message.method === 'initialize') result = {+ protocolVersion: '2025-11-25', capabilities: { tools: {} },+ serverInfo: { name: 'controlled-fixture', version: '1' },+ };+ else if (message.method === 'tools/list') result = {+ tools: [{ name: 'write_fixture', inputSchema: { type: 'object', properties: {} } }],+ };+ else if (message.method === 'tools/call') {+ if (fault === 'call-business') result = {+ isError: true, content: [{ type: 'text', text: 'Fixture operation rejected' }],+ };+ else {+ effects += 1;+ if (fault === 'call-reset-after-effect') { req.socket.destroy(); return; }+ result = fault === 'call-malformed' ? { content: 'invalid-result-shape' }+ : { content: [{ type: 'text', text: 'Fixture write completed' }] };+ }+ }+ else { res.writeHead(404); res.end(); return; }+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }));+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}/mcp`;+ const actualFetch = globalThis.fetch;+ vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);+ if (url.origin !== new URL(endpoint).origin) throw new Error('Fixture blocks non-peer network');+ return actualFetch(input, init);+ });+ const users = await import('../../../../src/main/features/users');+ users.activateUser(UID);+ manager = await import('../../../../src/main/features/connectors/manager');+ registry = await import('../../../../src/main/features/connectors/registry');+});++afterEach(async () => {+ try {+ await manager?.shutdownAll();+ await closeLogs?.();+ } finally {+ server?.closeAllConnections();+ if (server?.listening) await new Promise<void>(resolve => server.close(() => resolve()));+ vi.restoreAllMocks();+ if (previousRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;+ else process.env.ORKAS_WORKSPACE_ROOT = previousRoot;+ fs.rmSync(root, { recursive: true, force: true });+ }+});++async function add() {+ return manager.addCustomInstance(UID, {+ display_name: 'Failure fixture', transport: {+ kind: 'streamable-http', url: endpoint, headers: { Authorization: 'Bearer synthetic-fixture' },+ },+ });+}++describe('custom MCP failures and recovery through a real local peer', () => {+ it('completes a healthy write once and passes the configured authorization', async () => {+ const instance = await add();+ expect(instance.status.kind).toBe('connected');+ expect(instance.tools_cache.map(tool => tool.name)).toEqual(['write_fixture']);+ await expect(manager.callTool(UID, instance.id, 'write_fixture', {})).resolves.toEqual({+ content: [{ type: 'text', text: 'Fixture write completed' }],+ });+ expect(effects).toBe(1);+ expect(requests.filter(method => method === 'tools/call')).toHaveLength(1);+ expect(authorization.every(value => value === 'Bearer synthetic-fixture')).toBe(true);+ });++ it.each(['initialize-auth', 'initialize-forbidden', 'initialize-rate-limit', 'initialize-upstream',+ 'initialize-deadline', 'initialize-timeout', 'initialize-other-server'] as const)(+ 'rejects %s before writing and recovers after the peer is restored', async (mode) => {+ fault = mode;+ const instance = await add();+ expect(instance.status.kind).toBe('error');+ expect(requests).toEqual(['initialize']);+ expect(effects).toBe(0);++ await expect(manager.callTool(UID, instance.id, 'write_fixture', {})).rejects.toThrow();+ expect(requests).not.toContain('tools/call');++ fault = 'none';+ await manager.refreshTools(UID, instance.id);+ await manager.callTool(UID, instance.id, 'write_fixture', {});+ expect(effects).toBe(1);+ });++ it('retains a legacy SSE authorization error after the handshake selects that transport', async () => {+ fault = 'legacy-auth';+ const instance = await add();+ expect(instance.status.kind).toBe('error');+ expect(requests).toEqual(['initialize', 'sse/get']);+ expect(effects).toBe(0);+ fault = 'none';+ await manager.refreshTools(UID, instance.id);+ await manager.callTool(UID, instance.id, 'write_fixture', {});+ expect(effects).toBe(1);+ });++ it.each(['list-auth', 'call-auth'] as const)('rejects %s without issuing or replaying a write', async mode => {+ const instance = await add();+ if (mode === 'list-auth') await manager.shutdownAll();+ fault = mode; requests = [];+ await expect(manager.callTool(UID, instance.id, 'write_fixture', {})).rejects.toThrow();+ expect(effects).toBe(0);+ expect(requests.filter(method => method === 'tools/call')).toHaveLength(mode === 'call-auth' ? 1 : 0);+ fault = 'none';+ await manager.refreshTools(UID, instance.id);+ await manager.callTool(UID, instance.id, 'write_fixture', {});+ expect(effects).toBe(1);+ });++ it('retains a missing local executable as a failed configuration without calling any tool', async () => {+ const instance = await manager.addCustomInstance(UID, {+ display_name: 'Missing executable', transport: {+ kind: 'stdio', command: path.join(root, 'absent-fixture-command'), args: [], env: {},+ },+ });+ expect(instance.status.kind).toBe('error');+ if (instance.status.kind === 'error') expect(instance.status.message).toContain('ENOENT');+ await expect(manager.callTool(UID, instance.id, 'write_fixture', {})).rejects.toThrow('ENOENT');+ expect(effects).toBe(0);+ expect(requests).toEqual([]);+ });++ it.each(['initialize-reset', 'list-reset'] as const)(+ 'preserves an established connector on %s, blocks cooldown traffic, and supports explicit recovery', async mode => {+ const instance = await add();+ await manager.shutdownAll();+ requests = [];+ fault = mode;+ await expect(manager.callTool(UID, instance.id, 'write_fixture', {})).rejects.toThrow();+ expect(requests.filter(method => method === 'initialize')).toHaveLength(2);+ expect(requests.filter(method => method === 'tools/list')).toHaveLength(mode === 'list-reset' ? 2 : 0);+ expect(requests).not.toContain('tools/call');+ expect(effects).toBe(0);+ expect(registry.load(UID).connections[instance.id]).toMatchObject({+ status: { kind: 'degraded' }, tools_cache: instance.tools_cache,+ });+ const before = [...requests];+ await expect(manager.callTool(UID, instance.id, 'write_fixture', {})).rejects.toThrow();+ expect(requests).toEqual(before);+ fault = 'none';+ await manager.refreshTools(UID, instance.id);+ await manager.callTool(UID, instance.id, 'write_fixture', {});+ expect(effects).toBe(1);+ expect(registry.load(UID).connections[instance.id]?.status.kind).toBe('connected');+ },+ );++ it('reports a tool rejection without executing, replaying or breaking the live connection', async () => {+ const instance = await add(); fault = 'call-business';+ const result = await manager.callTool(UID, instance.id, 'write_fixture', {});+ expect(result).toMatchObject({ isError: true });+ expect(effects).toBe(0);+ expect(requests.filter(method => method === 'tools/call')).toHaveLength(1);+ fault = 'none'; const before = requests.filter(method => method === 'initialize').length;+ await manager.callTool(UID, instance.id, 'write_fixture', {});+ expect(effects).toBe(1);+ expect(requests.filter(method => method === 'initialize')).toHaveLength(before);+ });++ it('does not repeat a write when the response connection drops after the peer applied it', async () => {+ const instance = await add(); fault = 'call-reset-after-effect';+ await expect(manager.callTool(UID, instance.id, 'write_fixture', {})).rejects.toThrow();+ expect(effects).toBe(1);+ expect(requests.filter(method => method === 'tools/call')).toHaveLength(1);+ expect(registry.load(UID).connections[instance.id]?.status.kind).toBe('degraded');+ const before = [...requests];+ await expect(manager.callTool(UID, instance.id, 'write_fixture', {})).rejects.toThrow();+ expect(requests).toEqual(before);+ expect(effects).toBe(1);+ });++ it('rejects a malformed tool response without repeating the write', async () => {+ const instance = await add(); fault = 'call-malformed';+ await expect(manager.callTool(UID, instance.id, 'write_fixture', {})).rejects.toThrow();+ expect(effects).toBe(1);+ expect(requests.filter(method => method === 'tools/call')).toHaveLength(1);+ });+});diff --git a/test/main/features/connectors/fixtures/lark-cli-1.0.93.json b/test/main/features/connectors/fixtures/lark-cli-1.0.93.jsonindex 39a560e0..e23b44c4 100644--- a/test/main/features/connectors/fixtures/lark-cli-1.0.93.json+++ b/test/main/features/connectors/fixtures/lark-cli-1.0.93.json@@ -394,6 +394,16 @@"status": 0,"stdout": "[\n {\n \"name\": \"im chat.members bots\",\n \"description\": \"获取群内机器人列表。Identity: supports `user` and `bot`; the caller must be in the target chat and must belong to the same tenant for internal chats\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"required\": [\n \"params\"\n ],\n \"properties\": {\n \"params\": {\n \"type\": \"object\",\n \"required\": [\n \"chat_id\"\n ],\n \"properties\": {\n \"chat_id\": {\n \"type\": \"string\",\n \"description\": \"群ID\",\n \"flag\": \"--chat-id\",\n \"example\": \"oc_a0553eda9014c201e6969b478895c230\"\n }\n }\n }\n }\n },\n \"outputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"items\": {\n \"type\": \"array\",\n \"description\": \"机器人列表\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"bot_id\": {\n \"type\": \"string\",\n \"description\": \"机器人的 open_id\",\n \"example\": \"ou_a0553eda9014c201e6969b478895c230\"\n },\n \"bot_name\": {\n \"type\": \"string\",\n \"description\": \"机器人名称\",\n \"example\": \"值班机器人\"\n }\n }\n }\n }\n }\n },\n \"_meta\": {\n \"envelope_version\": \"1.0\",\n \"scopes\": [\n \"im:chat:readonly\",\n \"im:chat\",\n \"im:chat.group_info:readonly\",\n \"im:chat.members:read\"\n ],\n \"required_scopes\": [],\n \"access_tokens\": [\n \"bot\",\n \"user\"\n ],\n \"danger\": false,\n \"risk\": \"read\"\n }\n },\n {\n \"name\": \"im chat.members create\",\n \"description\": \"将用户或机器人拉入群聊。Identity: supports `user` and `bot`; the caller must be in the target chat; for `bot` calls, added users must be within the app's availability; for internal chats the operator must belong to the same tenant; if only owners/admins can add members, the caller must be an owner/admin, or a chat-creator bot with `im:chat:operate_as_owner`\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"required\": [\n \"params\"\n ],\n \"properties\": {\n \"params\": {\n \"type\": \"object\",\n \"required\": [\n \"chat_id\"\n ],\n \"properties\": {\n \"chat_id\": {\n \"type\": \"string\",\n \"description\": \"群 ID。获取方式:; - [创建群](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/create),从返回结果中获取该群的 chat_id。;- 调用[获取用户或机器人所在的群列表](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/list)接口,可以查询用户或机器人所在群的 chat_id。;- 调用[搜索对用户或机器人可见的群列表](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/search),可搜索用户或机器人所在的群、对用户或机器人公开的群的 chat_id。; 注意:仅支持群模式为 群组(group)、话题(topic) 的群组 ID。你可以调用[获取群信息](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/get)接口,在返回结果中查看 `chat_mode` 参数取值是否为 `group`、`topic`\",\n \"flag\": \"--chat-id\",\n \"example\": \"oc_a0553eda9014c201e6969b478895c230\"\n },\n \"member_id_type\": {\n \"type\": \"string\",\n \"description\": \"用户 ID 类型\",\n \"flag\": \"--member-id-type\",\n \"enum\": [\n \"user_id\",\n \"union_id\",\n \"open_id\",\n \"app_id\"\n ],\n \"enumDescriptions\": [\n \"标识一个用户在某个租户内的身份。同一个用户在租户 A 和租户 B 内的 User ID 是不同的。在同一个租户内,一个用户的 User ID 在所有应用(包括商店应用)中都保持一致。User ID 主要用于在不同的应用间打通用户数据。[了解更多:如何获取 User ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-user-id)\",\n \"标识一个用户在某个应用开发商下的身份。同一用户在同一开发商下的应用中的 Union ID 是相同的,在不同开发商下的应用中的 Union ID 是不同的。通过 Union ID,应用开发商可以把同个用户在多个应用中的身份关联起来。[了解更多:如何获取 Union ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-union-id)\",\n \"标识一个用户在某个应用中的身份。同一个用户在不同应用中的 Open ID 不同。[了解更多:如何获取 Open ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-openid)\",\n \"飞书开放平台应用的唯一标识。在创建应用时,由系统自动生成,用户不能自行修改。[了解更多:如何获取应用的 App ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-app-id)\"\n ],\n \"default\": \"open_id\",\n \"example\": \"open_id\"\n },\n \"succeed_type\": {\n \"type\": \"integer\",\n \"description\": \"出现不可用ID后的处理方式 0/1/2; 默认值:`0`\",\n \"flag\": \"--succeed-type\",\n \"enum\": [\n 0,\n 1,\n 2\n ],\n \"enumDescriptions\": [\n \"不存在/不可见的 ID 会拉群失败,并返回错误响应。存在已离职 ID 时,会将其他可用 ID 拉入群聊,返回拉群成功的响应。\",\n \"将参数中可用的 ID 全部拉入群聊,返回拉群成功的响应,并展示剩余不可用的 ID 及原因。\",\n \"参数中只要存在任一不可用的 ID ,就会拉群失败,返回错误响应,并展示出不可用的 ID。\"\n ],\n \"example\": 0\n }\n }\n },\n \"data\": {\n \"type\": \"object\",\n \"carrier\": \"--data\",\n \"properties\": {\n \"id_list\": {\n \"type\": \"array\",\n \"description\": \"成员 ID 列表。; - 邀请用户进群时推荐使用 OpenID,获取方式可参考文档[如何获取 Open ID?](https://open.feishu.cn/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-openid); - 邀请机器人进群时需填写应用的 App ID,请参考[如何获取应用的 App ID?](https://open.feishu.cn/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-app-id); 注意:;- 成员列表不可为空;- 列表中填写的成员 ID 类型应与 ==member_id_type== 参数中选择的类型相对应;- 每次请求最多拉 50 个用户且不超过群人数上限。对于已认证企业的飞书的群人数默认上限:普通群 5000 人,会议群 3000 人,话题群 5000 人。若租户管理员配置了群人数上限,则群人数上限为该人数上限;- 最多同时邀请 5 个机器人,且邀请后群组中机器人数量不能超过 15 个\",\n \"items\": {}\n }\n }\n }\n }\n },\n \"outputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"invalid_id_list\": {\n \"type\": \"array\",\n \"description\": \"无效成员列表; 注意:;- 当`success_type` 取值为 `0`时,`invalid_id_list`只包含已离职的用户ID;- 当`success_type` 取值为 `1`时,`invalid_id_list`中包含已离职的、不可见的、应用未激活的 ID\",\n \"items\": {}\n },\n \"not_existed_id_list\": {\n \"type\": \"array\",\n \"description\": \"ID 不存在的成员列表\",\n \"items\": {}\n },\n \"pending_approval_id_list\": {\n \"type\": \"array\",\n \"description\": \"等待群主或管理员审批的成员 ID 列表\",\n \"items\": {}\n }\n }\n },\n \"_meta\": {\n \"envelope_version\": \"1.0\",\n \"scopes\": [\n \"im:chat\",\n \"im:chat.members:write_only\"\n ],\n \"required_scopes\": [],\n \"access_tokens\": [\n \"bot\",\n \"user\"\n ],\n \"danger\": true,\n \"risk\": \"write\",\n \"doc_url\": \"https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat-members/create\",\n \"affordance\": {\n \"use_when\": [\n \"Use this raw method for the skill's two-step recovery flow when a bot-created group cannot invite users because they are invisible to the bot.\"\n ],\n \"prerequisites\": [\n \"Create the group first, then add members as a user who is already in that group.\"\n ],\n \"examples\": [\n {\n \"description\": \"Add reachable users and report invalid ids separately\",\n \"command\": \"lark-cli im chat.members create --params '{\\\"chat_id\\\":\\\"oc_xxx\\\",\\\"member_id_type\\\":\\\"open_id\\\",\\\"succeed_type\\\":1}' --data '{\\\"id_list\\\":[\\\"ou_aaa\\\",\\\"ou_bbb\\\"]}' --as user\"\n }\n ],\n \"skills\": [\n \"lark-im\",\n \"lark-im/references/lark-im-chat-create.md\",\n \"lark-im/references/lark-im-chat-identity.md\"\n ]\n }\n }\n },\n {\n \"name\": \"im chat.members delete\",\n \"description\": \"将用户或机器人移出群聊。Identity: supports `user` and `bot`; only group owner, admin, or creator bot can remove others; max 50 users or 5 bots per request\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"required\": [\n \"params\"\n ],\n \"properties\": {\n \"params\": {\n \"type\": \"object\",\n \"required\": [\n \"chat_id\"\n ],\n \"properties\": {\n \"chat_id\": {\n \"type\": \"string\",\n \"description\": \"群 ID。获取方式:; - [创建群](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/create),从返回结果中获取该群的 chat_id。;- 调用[获取用户或机器人所在的群列表](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/list)接口,可以查询用户或机器人所在群的 chat_id。;- 调用[搜索对用户或机器人可见的群列表](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/search),可搜索用户或机器人所在的群、对用户或机器人公开的群的 chat_id。; 注意:仅支持群模式为 群组(group)、话题(topic) 的群组 ID。你可以调用[获取群信息](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/get)接口,在返回结果中查看 `chat_mode` 参数取值是否为 `group`、`topic`\",\n \"flag\": \"--chat-id\",\n \"example\": \"oc_a0553eda9014c201e6969b478895c230\"\n },\n \"member_id_type\": {\n \"type\": \"string\",\n \"description\": \"用户 ID 类型\",\n \"flag\": \"--member-id-type\",\n \"enum\": [\n \"user_id\",\n \"union_id\",\n \"open_id\",\n \"app_id\"\n ],\n \"enumDescriptions\": [\n \"标识一个用户在某个租户内的身份。同一个用户在租户 A 和租户 B 内的 User ID 是不同的。在同一个租户内,一个用户的 User ID 在所有应用(包括商店应用)中都保持一致。User ID 主要用于在不同的应用间打通用户数据。[了解更多:如何获取 User ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-user-id)\",\n \"标识一个用户在某个应用开发商下的身份。同一用户在同一开发商下的应用中的 Union ID 是相同的,在不同开发商下的应用中的 Union ID 是不同的。通过 Union ID,应用开发商可以把同个用户在多个应用中的身份关联起来。[了解更多:如何获取 Union ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-union-id)\",\n \"标识一个用户在某个应用中的身份。同一个用户在不同应用中的 Open ID 不同。[了解更多:如何获取 Open ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-openid)\",\n \"飞书开放平台应用的唯一标识。在创建应用时,由系统自动生成,用户不能自行修改。[了解更多:如何获取应用的 App ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-app-id)\"\n ],\n \"default\": \"open_id\",\n \"example\": \"open_id\"\n }\n }\n },\n \"data\": {\n \"type\": \"object\",\n \"carrier\": \"--data\",\n \"properties\": {\n \"id_list\": {\n \"type\": \"array\",\n \"description\": \"成员 ID 列表。ID 类型与查询参数 member_id_type 的取值一致。; - 移除群内的用户时推荐使用 OpenID,获取方式可参考文档[如何获取 Open ID?](https://open.feishu.cn/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-openid)。;- 移除群内的机器人时需填写应用的 App ID,请参考[如何获取应用的 App ID?](https://open.feishu.cn/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-app-id)。; 注意:;- 成员列表不可为空。;- 每次请求,最多移除 50 个用户或者 5 个机器人\",\n \"items\": {}\n }\n }\n },\n \"yes\": {\n \"type\": \"boolean\",\n \"description\": \"CLI confirmation gate. Must be true to execute; lark-cli rejects with confirmation_required if absent or false. Pass --yes only after the user has explicitly confirmed; not sent to the backend.\",\n \"flag\": \"--yes\",\n \"default\": false\n }\n }\n },\n \"outputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"invalid_id_list\": {\n \"type\": \"array\",\n \"description\": \"无效成员列表\",\n \"items\": {}\n }\n }\n },\n \"_meta\": {\n \"envelope_version\": \"1.0\",\n \"scopes\": [\n \"im:chat\",\n \"im:chat.members:write_only\"\n ],\n \"required_scopes\": [],\n \"access_tokens\": [\n \"bot\",\n \"user\"\n ],\n \"danger\": true,\n \"risk\": \"high-risk-write\",\n \"doc_url\": \"https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat-members/delete\"\n }\n },\n {\n \"name\": \"im chat.members get\",\n \"description\": \"获取群成员列表。Identity: supports `user` and `bot`; the caller must be in the target chat and must belong to the same tenant for internal chats\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"required\": [\n \"params\"\n ],\n \"properties\": {\n \"params\": {\n \"type\": \"object\",\n \"required\": [\n \"chat_id\"\n ],\n \"properties\": {\n \"chat_id\": {\n \"type\": \"string\",\n \"description\": \"群 ID。获取方式:; - [创建群](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/create),从返回结果中获取该群的 chat_id。;- 调用[获取用户或机器人所在的群列表](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/list)接口,可以查询用户或机器人所在群的 chat_id。;- 调用[搜索对用户或机器人可见的群列表](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/search),可搜索用户或机器人所在的群、对用户或机器人公开的群的 chat_id\",\n \"flag\": \"--chat-id\",\n \"example\": \"oc_a0553eda9014c201e6969b478895c230\"\n },\n \"check_security_conf\": {\n \"type\": \"boolean\",\n \"description\": \"是否检查安全配置\",\n \"flag\": \"--check-security-conf\"\n },\n \"member_id_type\": {\n \"type\": \"string\",\n \"description\": \"用户 ID 类型\",\n \"flag\": \"--member-id-type\",\n \"enum\": [\n \"user_id\",\n \"union_id\",\n \"open_id\"\n ],\n \"enumDescriptions\": [\n \"标识一个用户在某个租户内的身份。同一个用户在租户 A 和租户 B 内的 User ID 是不同的。在同一个租户内,一个用户的 User ID 在所有应用(包括商店应用)中都保持一致。User ID 主要用于在不同的应用间打通用户数据。[了解更多:如何获取 User ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-user-id)\",\n \"标识一个用户在某个应用开发商下的身份。同一用户在同一开发商下的应用中的 Union ID 是相同的,在不同开发商下的应用中的 Union ID 是不同的。通过 Union ID,应用开发商可以把同个用户在多个应用中的身份关联起来。[了解更多:如何获取 Union ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-union-id)\",\n \"标识一个用户在某个应用中的身份。同一个用户在不同应用中的 Open ID 不同。[了解更多:如何获取 Open ID?](/ssl:ttdoc/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-openid)\"\n ],\n \"default\": \"\",\n \"example\": \"open_id\"\n },\n \"page_size\": {\n \"type\": \"integer\",\n \"description\": \"分页大小,用来限制一次请求所返回的数据条目数。; - 由于返回的群成员列表会过滤掉机器人成员,因此返回的群成员个数可能会小于指定的 page_size。; - 如果有同一时间加入群的群成员,会一次性返回,这会导致返回的群成员个数可能会大于指定的 page_size\",\n \"flag\": \"--page-size\"\n },\n \"page_token\": {\n \"type\": \"string\",\n \"description\": \"分页标记,第一次请求不填,表示从头开始遍历;分页查询结果还有更多项时会同时返回新的 page_token,下次遍历可采用该 page_token 获取查询结果\",\n \"flag\": \"--page-token\",\n \"default\": \"\",\n \"example\": \"WWxHTStrOEs5WHZpNktGbU94bUcvMWlxdDUzTWt1OXNrRmlLaGRNVG0yaz0=\"\n }\n }\n }\n }\n },\n \"outputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"has_more\": {\n \"type\": \"boolean\",\n \"description\": \"是否还有更多项\",\n \"example\": true\n },\n \"items\": {\n \"type\": \"array\",\n \"description\": \"成员列表\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"member_id\": {\n \"type\": \"string\",\n \"description\": \"成员的用户ID,ID 值与查询参数中的 member_id_type 对应。; 不同 ID 的说明参见 [用户相关的 ID 概念](https://open.feishu.cn/document/home/user-identity-introduction/introduction)\",\n \"example\": \"4d7a3c6g\"\n },\n \"member_id_type\": {\n \"type\": \"string\",\n \"description\": \"成员的用户 ID 类型,与查询参数中的 member_id_type 相同。取值为:`open_id`、`user_id`、`union_id`其中之一\",\n \"example\": \"user_id\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"名字\",\n \"example\": \"张三\"\n },\n \"tenant_key\": {\n \"type\": \"string\",\n \"description\": \"租户Key,为租户在飞书上的唯一标识,用来换取对应的tenant_access_token,也可以用作租户在应用中的唯一标识\",\n \"example\": \"736588c9260f175d\"\n }\n }\n }\n },\n \"member_total\": {\n \"type\": \"integer\",\n \"description\": \"成员总数\",\n \"example\": 2\n },\n \"page_token\": {\n \"type\": \"string\",\n \"description\": \"分页标记,当 has_more 为 true 时,会同时返回新的 page_token,否则不返回 page_token\",\n \"example\": \"0\"\n },\n \"security_conf_limit\": {\n \"type\": \"integer\",\n \"description\": \"安全配置支持的最大查询群成员数量\",\n \"example\": 100\n },\n \"trigger_security_conf_limit\": {\n \"type\": \"boolean\",\n \"description\": \"是否触发了安全配置\"\n }\n }\n },\n \"_meta\": {\n \"envelope_version\": \"1.0\",\n \"scopes\": [\n \"im:chat:readonly\",\n \"im:chat\",\n \"im:chat.group_info:readonly\",\n \"im:chat.members:read\"\n ],\n \"required_scopes\": [],\n \"access_tokens\": [\n \"bot\",\n \"user\"\n ],\n \"danger\": false,\n \"risk\": \"read\",\n \"doc_url\": \"https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat-members/get\"\n }\n }\n]\n","stderr": ""+ },+ {+ "args": [+ "im",+ "+messages-resources-download",+ "--help"+ ],+ "status": 0,+ "stdout": "Download images/files from a message; user/bot; downloads image/file resources by message-id and file-key to a safe relative output path\n\nRisk: write\n\nWhen to use:\n • Use this after a read command exposes a message_id and matching file_key and the binary content is actually needed.\n\nExamples:\n • Download an image resource to the current directory\n lark-cli im +messages-resources-download --message-id om_xxx --file-key img_v3_xxx --type image\n\nRelated skills (read for end-to-end usage):\n lark-cli skills read lark-im\n lark-cli skills read lark-im/references/lark-im-messages-resources-download.md\n\nUsage:\n lark-cli im +messages-resources-download [flags]\n\nFlags:\n --as string identity type: user | bot\n --dry-run print request without executing\n --file-key string resource key (img_xxx or file_xxx)\n --format string output format: json (default) | pretty | table | ndjson | csv (default \"json\")\n -h, --help help for +messages-resources-download\n -q, --jq string jq expression to filter JSON output\n --json shorthand for --format json\n --message-id string message ID (om_xxx)\n --output string local save path, relative or absolute, within the allowed roots (cwd, /tmp, ~/files); when omitted, uses the server's Content-Disposition filename if available, otherwise file_key; extension is inferred from Content-Disposition or Content-Type if not provided\n --type string resource type (image or file) (image|file)\n",+ "stderr": ""}]}diff --git a/test/main/features/connectors/local-cli-lark-contract.test.ts b/test/main/features/connectors/local-cli-lark-contract.test.tsindex 28079b4e..399d6fb8 100644--- a/test/main/features/connectors/local-cli-lark-contract.test.ts+++ b/test/main/features/connectors/local-cli-lark-contract.test.ts@@ -340,6 +340,40 @@ describe('Lark user journeys against the pinned official command contract', () =// installs software, opens real profiles, reads credentials, or calls business APIs.const nativeCli = process.env.ORKAS_TEST_LARK_CLI_BIN;describe.skipIf(!nativeCli)('installed official Lark CLI compatibility canary', () => {+ it('passes download path validation outside configuration with the same native binary and parameters', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-lark-download-canary-'));+ const config = path.join(root, 'config');+ const work = path.join(config, 'work');+ const staging = path.join(root, 'download');+ fs.mkdirSync(work, { recursive: true });+ fs.mkdirSync(staging);+ fs.writeFileSync(path.join(config, 'config.json'), JSON.stringify({+ currentApp: 'contract-profile', apps: [{ name: 'contract-profile', appId: 'cli_fixture', appSecret: 'fixture-only', brand: 'feishu' }],+ }));+ const env = { ...envFor(config), LARKSUITE_CLI_CONFIG_DIR: config };+ const parameters = { message_id: 'om_0123456789abcdef0123456789abcdef', file_key: 'file_fixture', type: 'file' };+ const args = ['im', '+messages-resources-download', '--message-id', parameters.message_id,+ '--file-key', parameters.file_key, '--type', parameters.type, '--profile', 'contract-profile', '--format', 'json', '--dry-run'];+ try {+ // Negative control reproduces the upstream denylist, without credentials or network.+ const blocked = spawnSync(nativeCli!, args, { cwd: work, env, encoding: 'utf8', timeout: 10_000 });+ expect(blocked.status).toBe(2);+ expect(JSON.parse(blocked.stderr || blocked.stdout).error).toMatchObject({ type: 'validation', subtype: 'invalid_argument', param: '--output' });+ const runner = (_command: string, argv: string[], options: any) => {+ const cliArgs = argv.slice(4);+ return spawnSync(nativeCli!, cliArgs.includes('--help') ? cliArgs : [...cliArgs, '--dry-run'], {+ cwd: options.cwd, env: options.env, encoding: 'utf8', timeout: 10_000,+ });+ };+ const result = await adapter.callTool('execute_write', { action: 'im.+messages-resources-download', parameters }, {+ runner, skipPackageIntegrityCheck: true, localFileOutputDirectory: staging,+ }, env);+ expect(result.result).toMatchObject({ ok: true, dry_run: true });+ expect(fs.readdirSync(work)).toEqual([]);+ expect(fs.readdirSync(staging)).toEqual([]);+ } finally { fs.rmSync(root, { recursive: true, force: true }); }+ });+it('matches frozen discovery/help/schema contracts in an isolated configuration', () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-lark-canary-'));try {diff --git a/test/main/features/connectors/local-cli.test.ts b/test/main/features/connectors/local-cli.test.tsindex 62523328..da840c64 100644--- a/test/main/features/connectors/local-cli.test.ts+++ b/test/main/features/connectors/local-cli.test.ts@@ -7,8 +7,10 @@ import path from 'node:path';import { shell } from 'electron';import { describe, expect, it, vi } from 'vitest';+import { findTestNpmCli } from '../../../helpers/npm-cli';const diagnostics = vi.hoisted(() => ({ warn: vi.fn() }));+const bundledRuntime = vi.hoisted(() => ({ node: '/opt/orkas/runtime/node' }));vi.mock('../../../../src/main/logger', async importOriginal => {const actual = await importOriginal<typeof import('../../../../src/main/logger')>();return { ...actual, createLogger: (scope: string) => ({ ...actual.createLogger(scope), warn: diagnostics.warn }) };@@ -36,7 +38,7 @@ vi.mock('node:child_process', () => ({}),}));vi.mock('../../../../src/main/util/bundled-runtime', () => ({- bundledNodeExecutable: () => '/opt/orkas/runtime/node',+ bundledNodeExecutable: () => bundledRuntime.node,bundledNpxCli: () => '/opt/orkas/runtime/lib/node_modules/npm/bin/npx-cli.js',}));vi.mock('../../../../src/main/util/proxy-dispatcher', () => ({@@ -760,6 +762,99 @@ describe('official local CLI connector runtime', () => {}});+ it.each(['missing', 'shadowed'])('uses bundled Node for real npm lifecycle and connector children with %s system Node', async mode => {+ const realProcess = await vi.importActual<typeof import('node:child_process')>('node:child_process');+ const npmCli = findTestNpmCli(TEST_NODE);+ expect(npmCli, 'An installed npm CLI must be available on PATH or beside the test Node').toBeTruthy();+ const entry = findCatalogEntry('feishu')!;+ const uid = `bundled-node-child-${mode}`;+ const runtimeDir = localCliRuntimeDir(uid, entry.id);+ const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas CLI 路径-'));+ const nodeDir = path.join(fixture, 'bundled Node 空格');+ const hostPath = path.join(fixture, 'host-bin');+ const home = path.join(fixture, 'home');+ for (const directory of [hostPath, home]) fs.mkdirSync(directory);+ // Junctions need no Windows symlink privilege; the selected runtime remains real Node.+ fs.symlinkSync(path.dirname(TEST_NODE), nodeDir, 'junction');+ if (mode === 'shadowed') fs.writeFileSync(path.join(hostPath, process.platform === 'win32' ? 'node.exe' : 'node'),+ '#!/bin/sh\nexit 91\n', { mode: 0o755 });+ fs.writeFileSync(path.join(fixture, 'package.json'), JSON.stringify({+ name: 'local-cli-lifecycle-fixture', version: '1.0.0',+ scripts: { postinstall: 'node postinstall.cjs' },+ }));+ fs.writeFileSync(path.join(fixture, 'postinstall.cjs'), [+ "require('node:fs').writeFileSync('attempt.json', JSON.stringify({ node: process.execPath, exit: Number(process.env.FIXTURE_EXIT) }));",+ "if (process.env.FIXTURE_EXIT !== '0') process.exit(Number(process.env.FIXTURE_EXIT));",+ "require('node:fs').writeFileSync('receipt.json', JSON.stringify({ node: process.execPath }));",+ ].join('\n'));+ const previousNode = bundledRuntime.node;+ bundledRuntime.node = path.join(nodeDir, path.basename(TEST_NODE));+ vi.stubEnv('PATH', hostPath);+ vi.stubEnv('Path', hostPath);+ const assertChildNode = (env: Record<string, string>) => {+ // The selected runtime must win even when canonical/CI paths contain another Node.+ expect(env.PATH.split(path.delimiter)[0]).toBe(nodeDir);+ const result = realProcess.spawnSync('node', ['-p', 'process.execPath'], {+ env, encoding: 'utf8', timeout: 10_000, windowsHide: true,+ });+ expect(result.error).toBeUndefined();+ expect(result.status).toBe(0);+ expect(result.stderr).toBe('');+ expect(fs.realpathSync(result.stdout.trim())).toBe(fs.realpathSync(TEST_NODE));+ };+ let fixtureExit = 17;+ const runner = async (options: { env: Record<string, string> }) => {+ assertChildNode(options.env);+ const result = realProcess.spawnSync(bundledRuntime.node, [npmCli!, '--silent', 'run', 'postinstall'], {+ cwd: fixture, encoding: 'utf8', timeout: 15_000, windowsHide: true,+ env: {+ ...options.env, HOME: home, USERPROFILE: home, FIXTURE_EXIT: String(fixtureExit),+ NPM_CONFIG_USERCONFIG: path.join(home, '.npmrc'), NPM_CONFIG_GLOBALCONFIG: path.join(home, 'global.npmrc'),+ NPM_CONFIG_CACHE: path.join(fixture, 'npm-cache'), NPM_CONFIG_OFFLINE: 'true', NPM_CONFIG_LOGS_MAX: '0',+ },+ });+ expect(result.error).toBeUndefined();+ expect(result.stdout).toBe('');+ expect(result.stderr).toBe('');+ expect(result.status).toBe(fixtureExit);+ // Only the network/package extraction is a fixture. A real npm lifecycle+ // must execute successfully before the managed-package postcheck can pass.+ if (result.status === 0) {+ const receipt = JSON.parse(fs.readFileSync(path.join(fixture, 'receipt.json'), 'utf8'));+ expect(fs.realpathSync(receipt.node)).toBe(fs.realpathSync(TEST_NODE));+ seedInstalled(uid, entry);+ }+ return { exitCode: result.status, stderr: result.stderr };+ };+ try {+ await expect(installLocalCli(uid, entry, { runHelper: runner }))+ .rejects.toMatchObject({ code: 'local_cli_install_failed' });+ const attempt = JSON.parse(fs.readFileSync(path.join(fixture, 'attempt.json'), 'utf8'));+ expect(attempt.exit).toBe(17);+ expect(fs.realpathSync(attempt.node)).toBe(fs.realpathSync(TEST_NODE));+ expect(localCliInstallStatus(uid, entry).installed).toBe(false);+ expect(fs.existsSync(path.join(runtimeDir, '.orkas-cli-integrity.json'))).toBe(false);+ expect(fs.existsSync(path.join(fixture, 'receipt.json'))).toBe(false);+ await expect(authorizeLocalCli(uid, entry)).rejects.toMatchObject({ code: 'local_cli_install_required' });+ fixtureExit = 0;+ await expect(installLocalCli(uid, entry, { runHelper: runner })).resolves.toMatchObject({ installed: true });+ const transport = localCliTransport(uid, entry);+ expect(transport.kind).toBe('stdio');+ if (transport.kind === 'stdio') assertChildNode(transport.env!);+ await authorizeLocalCli(uid, entry);+ assertChildNode(interactiveMocks.start.mock.calls.at(-1)![0].sandboxEnv);+ await checkLocalCliPermissions(uid, entry, true, async options => {+ assertChildNode(options.env);+ return { exitCode: 0, stderr: '' };+ });+ } finally {+ bundledRuntime.node = previousNode;+ vi.unstubAllEnvs();+ fs.rmSync(runtimeDir, { recursive: true, force: true });+ fs.rmSync(fixture, { recursive: true, force: true });+ }+ });+it('maps registry verification failures to a stable renderer-safe install code', async () => {const entry = findCatalogEntry('wecom');expect(entry).toBeTruthy();diff --git a/test/main/features/connectors/local-cli_e2e_download.test.ts b/test/main/features/connectors/local-cli_e2e_download.test.tsnew file mode 100644index 00000000..e7f3e2b1--- /dev/null+++ b/test/main/features/connectors/local-cli_e2e_download.test.ts@@ -0,0 +1,87 @@+import { createRequire } from 'node:module';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { expect, it, vi } from 'vitest';+import { makeMinimalDocx } from '../../../fixtures/make-minimal-docx';+import { docxBufferToMarkdown } from '../../../../src/main/util/extract-docx';++vi.mock('../../../../src/main/util/proxy-dispatcher', () => ({ buildChildProxyEnvironment: async () => ({}) }));+import { McpConnection } from '../../../../src/main/features/connectors/mcp-client';++const require = createRequire(import.meta.url);+const adapter = require('../../../../bin/local-cli-mcp-server.cjs');+const fixture = require('./fixtures/lark-cli-1.0.93.json');++it('downloads a readable document through the real MCP client without writing into CLI configuration or accepting output overrides', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-download-mcp-'));+ const config = path.join(root, 'config');+ const work = path.join(config, 'work');+ const stage = path.join(root, 'stage');+ fs.mkdirSync(work, { recursive: true });+ fs.mkdirSync(stage);+ const bytes = makeMinimalDocx({ paragraphs: ['Download regression document.'] });+ const trace = path.join(root, 'downloads.json');+ const cli = path.join(root, 'npx.cjs');+ const marker = path.join(config, 'integrity.json');+ fs.writeFileSync(marker, JSON.stringify(adapter.MANIFESTS.lark));+ fs.writeFileSync(cli, [+ "const fs = require('node:fs'), path = require('node:path');",+ 'const args = process.argv.slice(5);',+ `const samples = ${JSON.stringify(fixture.samples)};`,+ "if (args[0] === 'im' && args[1] === '+messages-resources-download' && !args.includes('--help')) {",+ ' const cwd = fs.realpathSync(process.cwd()), config = fs.realpathSync(process.env.LARKSUITE_CLI_CONFIG_DIR);',+ " if (cwd === config || cwd.startsWith(config + path.sep)) { process.stderr.write(JSON.stringify({ok:false,error:{type:'validation',subtype:'invalid_argument',message:'config directory is protected'}})); process.exit(2); }",+ ` fs.writeFileSync(${JSON.stringify(trace)}, JSON.stringify({ cwd, args }));`,+ " const saved = path.resolve('report 宇涛.docx');",+ ` const bytes = Buffer.from(${JSON.stringify(bytes.toString('base64'))}, 'base64');`,+ ' fs.writeFileSync(saved, bytes);',+ ' process.stdout.write(JSON.stringify({ok:true,identity:"user",data:{saved_path:saved,size_bytes:bytes.length}}));',+ '} else {',+ ' const sample = samples.find(sample => JSON.stringify(sample.args) === JSON.stringify(args));',+ ' if (!sample) process.exit(3);',+ ' process.stdout.write(sample.stdout); process.stderr.write(sample.stderr); process.exitCode = sample.status;',+ '}',+ ].join('\n'));+ const node = process.env.ORKAS_TEST_NODE || process.execPath;+ const connection = new McpConnection('feishu', { kind: 'stdio', command: node,+ args: [path.resolve('bin/local-cli-mcp-server.cjs')], env: {+ ORKAS_LOCAL_CLI_PROVIDER: 'lark', ORKAS_LOCAL_CLI_PACKAGE: adapter.MANIFESTS.lark.package,+ ORKAS_LOCAL_CLI_PACKAGE_INTEGRITY: adapter.MANIFESTS.lark.integrity,+ ORKAS_LOCAL_CLI_EXECUTABLE: adapter.MANIFESTS.lark.executable,+ ORKAS_LOCAL_CLI_ALLOWED_DOMAINS_JSON: JSON.stringify(adapter.MANIFESTS.lark.domains),+ ORKAS_LOCAL_CLI_RUNTIME_DIR: config, ORKAS_LOCAL_CLI_WORK_DIR: work,+ LARKSUITE_CLI_CONFIG_DIR: config, ORKAS_LOCAL_CLI_PROFILE: 'download-fixture',+ ORKAS_LOCAL_CLI_SKIP_AUTH_CHECK: '1', ORKAS_LOCAL_CLI_NPX_CLI: cli,+ ORKAS_LOCAL_CLI_INTEGRITY_MARKER: marker, ORKAS_NODE: node,+ } });+ const args = { action: 'im.+messages-resources-download', parameters: {+ message_id: 'om_fixture', file_key: 'file_fixture', type: 'file',+ } };+ try {+ await connection.connect();+ const missing: any = await connection.callTool('execute_write', args);+ expect(missing.isError).toBe(true);+ expect(fs.existsSync(trace)).toBe(false);+ const invalid: any = await connection.callTool('execute_write', args, { localFileOutputDirectory: work });+ expect(invalid.isError).toBe(true);+ expect(fs.existsSync(trace)).toBe(false);+ const overridden: any = await connection.callTool('execute_write', {+ ...args, parameters: { ...args.parameters, output: path.join(stage, 'override.docx') },+ }, { localFileOutputDirectory: stage });+ expect(overridden.isError).toBe(true);+ expect(fs.existsSync(trace)).toBe(false);+ const raw: any = await connection.callTool('execute_write', args, { localFileOutputDirectory: stage });+ expect(raw.isError, JSON.stringify(raw)).not.toBe(true);+ const saved = JSON.parse(raw.content[0].text).result.data.saved_path;+ expect(fs.readFileSync(saved)).toEqual(bytes);+ expect(await docxBufferToMarkdown(fs.readFileSync(saved))).toContain('Download regression document');+ const recorded = JSON.parse(fs.readFileSync(trace, 'utf8'));+ expect(recorded.cwd).toBe(fs.realpathSync(stage));+ expect(recorded.args).not.toContain('--output');+ expect(fs.readdirSync(work)).toEqual([]);+ } finally {+ await connection.close();+ fs.rmSync(root, { recursive: true, force: true });+ }+});diff --git a/test/main/features/connectors/manager.test.ts b/test/main/features/connectors/manager.test.tsindex e926e238..24afe1f5 100644--- a/test/main/features/connectors/manager.test.ts+++ b/test/main/features/connectors/manager.test.ts@@ -3,6 +3,7 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import { captureMainLogWorkers } from '../../../helpers/capture-main-log-workers';+import { makeMinimalDocx } from '../../../fixtures/make-minimal-docx';const TEST_UID = 'u-connectors-manager';@@ -1897,6 +1898,21 @@ describe('features/connectors/manager authorization recovery', () => {});});+ it('reports a DCR browser launch rejection without provisioning a connector', async () => {+ mocks.dcr.startMcpDcrOAuth = vi.fn(async () => {+ throw Object.assign(new Error('failed to open authorization browser'), { code: 'browser_open_failed' });+ });+ const manager = await import('../../../../src/main/features/connectors/manager');+ const registry = await import('../../../../src/main/features/connectors/registry');+ manager.beginOAuthConnect(TEST_UID, 'notion');+ await vi.waitFor(() => expect(mocks.events.broadcastOAuthConnectOutcome).toHaveBeenCalledOnce());+ expect(mocks.events.broadcastOAuthConnectOutcome).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({+ catalog_id: 'notion', result: 'failure', code: 'browser_open_failed',+ }));+ expect(mocks.mcp.connect).not.toHaveBeenCalled();+ expect(registry.load(TEST_UID).connections.notion).toBeUndefined();+ });+it('does not count an authorized but degraded MCP connection as a successful installation', async () => {const registry = await import('../../../../src/main/features/connectors/registry');const manager = await import('../../../../src/main/features/connectors/manager');@@ -2361,6 +2377,159 @@ describe('OAuth refresh ownership', () => {expect(options).toEqual({ signal: controller.signal });});+ it('imports downloaded message files into only the calling conversation and keeps their document bytes readable', async () => {+ mocks.mcp.listTools = vi.fn(async () => [{ name: 'execute_write', description: 'Download.', input_schema: {} }]);+ const manager = await import('../../../../src/main/features/connectors/manager');+ const attachments = await import('../../../../src/main/features/chat_attachments');+ const { docxBufferToMarkdown } = await import('../../../../src/main/util/extract-docx');+ await manager.connectViaOAuth(TEST_UID, 'feishu');+ const body = makeMinimalDocx({ paragraphs: ['Cache reuse investigation fixture.'] });+ const directories: string[] = [];+ mocks.mcp.callTool = vi.fn(async (_name, _args, options) => {+ expect(typeof options?.localFileOutputDirectory).toBe('string');+ const directory = options.localFileOutputDirectory;+ directories.push(directory);+ const saved = path.join(directory, 'cache-report.docx');+ fs.writeFileSync(saved, body);+ return { content: [{ type: 'text', text: JSON.stringify({ action: 'im.+messages-resources-download', risk: 'W',+ result: { ok: true, data: { saved_path: saved, size_bytes: body.length } } }) }] };+ });+ const returned: string[] = [];+ for (const conversationId of ['download-a', 'download-a', 'download-b']) {+ const raw: any = await manager.callTool(TEST_UID, 'feishu', 'execute_write', {+ action: 'im.+messages-resources-download', parameters: { message_id: 'om_fixture', file_key: 'file_fixture', type: 'file' },+ }, { conversationId });+ const saved = JSON.parse(raw.content[0].text).result.data.saved_path;+ returned.push(saved);+ const resolved = attachments.resolveAttachmentAbsPath(TEST_UID, conversationId, path.basename(saved));+ expect(resolved).toMatchObject({ ok: true, absPath: saved });+ expect(fs.readFileSync(saved)).toEqual(body);+ expect(await docxBufferToMarkdown(fs.readFileSync(saved))).toContain('Cache reuse investigation fixture');+ expect(attachments.listPendingAttachments(TEST_UID, conversationId)).toEqual([]);+ }+ expect(new Set(returned).size).toBe(3);+ expect(new Set(directories).size).toBe(3);+ expect(directories.every(directory => !fs.existsSync(directory))).toBe(true);+ });++ it.each(['success', 'provider-error', 'throw'])('preserves the download outcome when staging cleanup fails (%s)', async mode => {+ mocks.mcp.listTools = vi.fn(async () => [{ name: 'execute_write', description: 'Download.', input_schema: {} }]);+ const denied = { isError: true, content: [{ type: 'text', text: '{"error_code":"connector_permission_denied"}' }] };+ const original = new Error('MCP tool call timed out');+ let directory = '';+ const realRm = fs.promises.rm;+ const remove = vi.fn(async (target: any, options: any) => {+ if (directory && String(target) === directory) throw new Error('private staging path: ' + directory);+ return realRm(target, options);+ });+ vi.doMock('node:fs/promises', async importOriginal => ({+ ...await importOriginal<typeof import('node:fs/promises')>(), rm: remove,+ }));+ const manager = await import('../../../../src/main/features/connectors/manager');+ const attachments = await import('../../../../src/main/features/chat_attachments');+ await manager.connectViaOAuth(TEST_UID, 'feishu');+ const { default: electronLog } = await import('electron-log/main');+ const records: unknown[][] = [];+ const hook = (message: any) => {+ if (message.scope === 'connectors:local-cli-downloads' && message.level === 'warn') records.push(message.data);+ return message;+ };+ electronLog.hooks.push(hook);+ mocks.mcp.callTool = vi.fn(async (_name, _args, options) => {+ directory = options.localFileOutputDirectory;+ if (mode === 'provider-error') return denied;+ if (mode === 'throw') throw original;+ const saved = path.join(directory, 'download.txt');+ fs.writeFileSync(saved, 'download fixture');+ return { content: [{ type: 'text', text: JSON.stringify({ result: { ok: true,+ data: { saved_path: saved, size_bytes: 16 } } }) }] };+ });+ try {+ const pending = manager.callTool(TEST_UID, 'feishu', 'execute_write', {+ action: 'im.+messages-resources-download',+ }, { conversationId: 'download-cleanup' });+ if (mode === 'throw') await expect(pending).rejects.toBe(original);+ else if (mode === 'provider-error') expect(await pending).toEqual(denied);+ else {+ const raw: any = await pending;+ const saved = JSON.parse(raw.content[0].text).result.data.saved_path;+ expect(fs.readFileSync(saved, 'utf8')).toBe('download fixture');+ expect(attachments.listAttachments(TEST_UID, 'download-cleanup')).toHaveLength(1);+ expect(attachments.listPendingAttachments(TEST_UID, 'download-cleanup')).toEqual([]);+ }+ expect(records).toEqual([['temporary download cleanup failed', { error: {+ message_hash: expect.stringMatching(/^[a-f0-9]{12}$/),+ message_chars: ('private staging path: ' + directory).length,+ } }]]);+ expect(JSON.stringify(records)).not.toContain(directory);+ expect(mocks.mcp.callTool).toHaveBeenCalledOnce();+ expect(remove).toHaveBeenCalledWith(directory, expect.objectContaining({ recursive: true, force: true }));+ if (mode !== 'success') expect(attachments.listAttachments(TEST_UID, 'download-cleanup')).toEqual([]);+ } finally {+ const hookIndex = electronLog.hooks.indexOf(hook);+ if (hookIndex >= 0) electronLog.hooks.splice(hookIndex, 1);+ vi.doUnmock('node:fs/promises');+ if (directory) await realRm(directory, { recursive: true, force: true });+ }+ });++ it.each(['outside', 'symlink', 'hardlink', 'directory', 'missing', 'no-receipt', 'wrong-size', 'unsupported', 'cancel', 'timeout', 'provider-error'])(+ 'does not publish an unsafe or incomplete download (%s), cleans staging and never replays', async mode => {+ mocks.mcp.listTools = vi.fn(async () => [{ name: 'execute_write', description: 'Download.', input_schema: {} }]);+ const manager = await import('../../../../src/main/features/connectors/manager');+ const attachments = await import('../../../../src/main/features/chat_attachments');+ await manager.connectViaOAuth(TEST_UID, 'feishu');+ const outside = path.join(tmpDir, 'private.txt');+ fs.writeFileSync(outside, 'private');+ const controller = new AbortController();+ let directory = '';+ const denied = { isError: true, content: [{ type: 'text', text: '{"error_code":"connector_permission_denied"}' }] };+ mocks.mcp.callTool = vi.fn(async (_name, _args, options) => {+ expect(typeof options?.localFileOutputDirectory).toBe('string');+ directory = options.localFileOutputDirectory;+ let saved = path.join(directory, mode === 'unsupported' ? 'payload.exe' : 'download.txt');+ if (mode === 'outside') saved = outside;+ else if (mode === 'symlink') fs.symlinkSync(outside, saved);+ else if (mode === 'hardlink') fs.linkSync(outside, saved);+ else if (mode === 'directory') fs.mkdirSync(saved);+ else if (mode === 'missing') { /* A success receipt without file bytes must fail. */ }+ else fs.writeFileSync(saved, 'private');+ if (mode === 'timeout') throw new Error('MCP tool call timed out');+ if (mode === 'cancel') controller.abort();+ if (mode === 'provider-error') return denied;+ if (mode === 'no-receipt') return { content: [{ type: 'text', text: 'done' }] };+ return { content: [{ type: 'text', text: JSON.stringify({ result: { ok: true,+ data: { saved_path: saved, size_bytes: mode === 'wrong-size' ? 1 : 7 } } }) }] };+ });+ const pending = manager.callTool(TEST_UID, 'feishu', 'execute_write', {+ action: 'im.+messages-resources-download', parameters: { message_id: 'om_fixture', file_key: 'file_fixture', type: 'file' },+ }, { conversationId: 'download-failure', signal: controller.signal });+ if (mode === 'provider-error') expect(await pending).toEqual(denied);+ else {+ const error = await pending.catch(error => error);+ expect(error).toBeInstanceOf(Error);+ expect(error.message).toMatch(/download|cancelled|timed out/);+ expect(error.message).not.toContain(directory);+ expect(error.message).not.toContain(outside);+ if (mode === 'cancel') expect(error.code).toBe('E_TOOL_CALL_CANCELLED');+ }+ expect(mocks.mcp.callTool).toHaveBeenCalledOnce();+ expect(directory).not.toBe('');+ expect(fs.existsSync(directory)).toBe(false);+ expect(attachments.listAttachments(TEST_UID, 'download-failure')).toEqual([]);+ expect(fs.readFileSync(outside, 'utf8')).toBe('private');+ },+ );++ it('requires host conversation context before requesting a message download', async () => {+ mocks.mcp.listTools = vi.fn(async () => [{ name: 'execute_write', description: 'Download.', input_schema: {} }]);+ const manager = await import('../../../../src/main/features/connectors/manager');+ await manager.connectViaOAuth(TEST_UID, 'feishu');+ await expect(manager.callTool(TEST_UID, 'feishu', 'execute_write', { action: 'im.+messages-resources-download' }))+ .rejects.toThrow('conversation');+ expect(mocks.mcp.callTool).not.toHaveBeenCalled();+ });+it('keeps legacy standalone Lark installs mutually exclusive with the unified Feishu entry', async () => {mocks.mcp.listTools = vi.fn(async () => [{ name: 'execute_read', description: 'Read an official action.', input_schema: {} },diff --git a/test/main/features/connectors/mcp-client.test.ts b/test/main/features/connectors/mcp-client.test.tsindex 782684d9..ced6626e 100644--- a/test/main/features/connectors/mcp-client.test.ts+++ b/test/main/features/connectors/mcp-client.test.ts@@ -1,14 +1,197 @@-import { spawnSync } from 'node:child_process';+import { spawn, spawnSync } from 'node:child_process';import { createRequire } from 'node:module';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';const require = createRequire(import.meta.url);describe('MCP stdio diagnostic boundary', () => {+ it.runIf(process.platform === 'darwin' || process.platform === 'win32')+ .each(['graceful', 'ignores-eof', 'failed-initialize', 'reconnect'])(+ 'closes native stdio before shutdown or reconnect: %s', async mode => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-mcp-native-close-'));+ const serverPath = path.join(root, 'server.cjs');+ const probePath = path.join(root, 'probe.cjs');+ const pidsPath = path.join(root, 'pids.jsonl');+ const receiptsPath = path.join(root, 'eof.jsonl');+ fs.writeFileSync(serverPath, [+ `const { Server } = require(${JSON.stringify(require.resolve('@modelcontextprotocol/sdk/server/index.js'))});`,+ `const { StdioServerTransport } = require(${JSON.stringify(require.resolve('@modelcontextprotocol/sdk/server/stdio.js'))});`,+ `require('node:fs').appendFileSync(${JSON.stringify(pidsPath)}, JSON.stringify(process.pid) + '\\n');`,+ 'process.stdin.on("end", () => {',+ ...(mode === 'ignores-eof' ? [] : [+ ` require('node:fs').appendFileSync(${JSON.stringify(receiptsPath)}, JSON.stringify(process.pid) + '\\n');`,+ ' process.exit(0);',+ ]),+ '});',+ 'setTimeout(() => process.exit(1), 15000).unref();',+ ...(mode === 'failed-initialize' ? ['process.stdin.resume();'] : [+ "void new Server({ name: 'native-close', version: '1' }, { capabilities: {} }).connect(new StdioServerTransport());",+ ]),+ ...(mode === 'ignores-eof' ? ['setInterval(() => {}, 1000);'] : []),+ ].join('\n'));+ fs.writeFileSync(probePath, [+ 'const warnings = [];',+ `require.cache[require.resolve(${JSON.stringify(path.resolve('src/main/logger.ts'))})] = { exports: { createLogger: () => ({ info() {}, warn(message) { warnings.push(message); } }) } };`,+ `require.cache[require.resolve(${JSON.stringify(path.resolve('src/main/util/proxy-dispatcher.ts'))})] = { exports: { buildChildProxyEnvironment: async () => ({}) } };`,+ `const { McpConnection } = require(${JSON.stringify(path.resolve('src/main/features/connectors/mcp-client.ts'))});`,+ `const connection = new McpConnection('custom-native-close', { kind: 'stdio', command: ${JSON.stringify(process.env.ORKAS_TEST_NODE)}, args: [${JSON.stringify(serverPath)}], env: {} });`,+ 'const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };',+ ...(mode === 'failed-initialize' ? [+ 'const originalSetTimeout = global.setTimeout;',+ 'global.setTimeout = (fn, ms, ...args) => originalSetTimeout(fn, ms === 30000 ? 1000 : ms, ...args);',+ ] : []),+ '(async () => {',+ ' try {',+ ' let connectFailed = false; try { await connection.connect(); } catch { connectFailed = true; }',+ ' const closing = connection.close();',+ ' const duplicate = connection.close();',+ ...(mode === 'reconnect' ? [' const reconnecting = connection.connect();'] : []),+ ' await Promise.all([closing, duplicate]);',+ ...(mode === 'reconnect' ? [' await reconnecting; await connection.close();'] : []),+ ` const pids = require('node:fs').readFileSync(${JSON.stringify(pidsPath)}, 'utf8').trim().split('\\n').map(JSON.parse);`,+ ` const receipts = require('node:fs').existsSync(${JSON.stringify(receiptsPath)}) ? require('node:fs').readFileSync(${JSON.stringify(receiptsPath)}, 'utf8').trim().split('\\n').map(JSON.parse) : [];`,+ ' process.stdout.write(JSON.stringify({ connectFailed, connected: connection.isConnected, sharedClose: connectFailed || closing === duplicate, count: pids.length, alive: pids.some(alive), graceful: pids.every(pid => receipts.includes(pid)), warnings }));',+ ' } finally { await connection.close(); }',+ '})().catch(error => { process.stderr.write(error.name); process.exitCode = 1; });',+ ].join('\n'));+ try {+ const result = spawnSync(process.execPath, ['-r', require.resolve('tsx/cjs'), probePath], {+ cwd: root, env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', ORKAS_WORKSPACE_ROOT: root },+ encoding: 'utf8', timeout: 12000, maxBuffer: 1024 * 1024,+ });+ expect(result.status, result.stderr || result.stdout).toBe(0);+ expect(result.stderr).toBe('');+ expect(JSON.parse(result.stdout)).toEqual({+ connectFailed: mode === 'failed-initialize', connected: false, sharedClose: true,+ count: mode === 'reconnect' ? 2 : 1, alive: false, graceful: mode !== 'ignores-eof',+ warnings: mode === 'failed-initialize' ? ['connect failed'] : [],+ });+ } finally {+ if (fs.existsSync(pidsPath)) for (const pid of fs.readFileSync(pidsPath, 'utf8').trim().split('\n').map(JSON.parse)) {+ try { process.kill(pid, 'SIGKILL'); } catch { /* already closed */ }+ }+ await fs.promises.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ }+ }, 15000,+ );++ it.runIf(process.platform === 'win32').each(['direct', 'cmd', 'failed-initialize', 'app-shutdown', 'app-late-connection', 'shared-runtime'])(+ 'releases a Windows MCP descendant file lock before disconnect completes: %s', async mode => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas MCP 更新 '));+ const serverPath = path.join(root, 'server.cjs');+ const probePath = path.join(root, 'probe.cjs');+ const lockPath = path.join(root, 'runtime.exe');+ const replacementPath = path.join(root, 'replacement.exe');+ const pidPath = path.join(root, 'lock.pid');+ const readyPath = path.join(root, 'lock.ready');+ const foreignReadyPath = path.join(root, 'foreign.ready');+ const shimPath = path.join(root, 'server.cmd');+ fs.copyFileSync(process.env.ORKAS_TEST_NODE!, lockPath);+ const unrelated = spawn(mode === 'shared-runtime' ? lockPath : process.env.ORKAS_TEST_NODE!, ['-e',+ `require('node:fs').writeFileSync(${JSON.stringify(foreignReadyPath)}, 'ready'); setTimeout(() => {}, 30000);`,+ ], {+ windowsHide: true, stdio: 'ignore',+ });+ const unrelatedClosed = new Promise(resolve => unrelated.once('close', resolve));+ fs.writeFileSync(replacementPath, 'new runtime');+ const lockScript = `require('node:fs').writeFileSync(${JSON.stringify(readyPath)}, 'locked'); setTimeout(() => {}, 30000);`;+ fs.writeFileSync(serverPath, [+ `const { Server } = require(${JSON.stringify(require.resolve('@modelcontextprotocol/sdk/server/index.js'))});`,+ `const { StdioServerTransport } = require(${JSON.stringify(require.resolve('@modelcontextprotocol/sdk/server/stdio.js'))});`,+ `const child = require('node:child_process').spawn(${JSON.stringify(lockPath)}, ['-e', ${JSON.stringify(lockScript)}],`,+ ` { windowsHide: true, detached: true, stdio: 'ignore' });`,+ `require('node:fs').writeFileSync(${JSON.stringify(pidPath)}, String(child.pid));`,+ 'const timer = setInterval(() => {',+ ` if (!require('node:fs').existsSync(${JSON.stringify(readyPath)})) return; clearInterval(timer);`,+ " const server = new Server({ name: 'tree', version: '1' }, { capabilities: {} });",+ // The wrapper exits on EOF; Windows must still reap its non-cooperating child.+ ' process.stdin.once("end", () => process.exit(0));',+ mode === 'failed-initialize' ? ' process.stdin.resume();' : ' void server.connect(new StdioServerTransport());',+ '}, 20);',+ ].join('\n'));+ fs.writeFileSync(shimPath, `@echo off\r\n"${process.env.ORKAS_TEST_NODE}" "%~dp0server.cjs"\r\n`);+ fs.writeFileSync(probePath, [+ 'const warnings = [];',+ `require.cache[require.resolve(${JSON.stringify(path.resolve('src/main/logger.ts'))})] = { exports: { createLogger: () => ({ info() {}, warn(message) { warnings.push(message); } }) } };`,+ `require.cache[require.resolve(${JSON.stringify(path.resolve('src/main/util/proxy-dispatcher.ts'))})] = { exports: { buildChildProxyEnvironment: async () => ({}) } };`,+ `const { McpConnection } = require(${JSON.stringify(path.resolve('src/main/features/connectors/mcp-client.ts'))});`,+ 'const childProcess = require("node:child_process"); const originalSpawn = childProcess.spawn; let processHelpers = 0;',+ 'childProcess.spawn = (...args) => { if (require("node:path").basename(args[0]).toLowerCase() === "powershell.exe") processHelpers++; return originalSpawn(...args); };',+ `const connection = new McpConnection('custom-tree', { kind: 'stdio', command: ${JSON.stringify(mode === 'cmd' ? shimPath : process.env.ORKAS_TEST_NODE)}, args: ${JSON.stringify(mode === 'cmd' ? [] : [serverPath])}, env: {} });`,+ ...(mode === 'failed-initialize' ? [+ 'const realSetTimeout = global.setTimeout;',+ 'global.setTimeout = (fn, ms, ...args) => realSetTimeout(fn, ms === 30000 ? 1500 : ms, ...args);',+ ] : []),+ '(async () => {',+ ' let processSnapshot;',+ ' try {',+ ...(mode === 'app-late-connection' ? [+ ` processSnapshot = await require(${JSON.stringify(path.resolve('src/main/util/windows-shutdown-processes.ts'))}).captureWindowsShutdownProcesses();`,+ ] : []),+ ' const connecting = connection.connect().then(() => false, () => true);',+ ` const deadline = Date.now() + 3000; while (!require('node:fs').existsSync(${JSON.stringify(readyPath)})) { if (Date.now() > deadline) throw new Error('fixture not ready'); await new Promise(resolve => setTimeout(resolve, 20)); }`,+ ' let wasLocked = false;',+ ` try { require('node:fs').renameSync(${JSON.stringify(replacementPath)}, ${JSON.stringify(lockPath)}); } catch (error) { wasLocked = error.code === 'EPERM'; }`,+ ' const connectFailed = await connecting;',+ ' let sharedClose = false;',+ ' const close = async () => { const first = connection.close(); const second = connection.close(); sharedClose = connectFailed || first === second; await Promise.all([first, second]); };',+ ...(mode.startsWith('app-') || mode === 'shared-runtime' ? [+ ` const { captureWindowsShutdownProcesses } = require(${JSON.stringify(path.resolve('src/main/util/windows-shutdown-processes.ts'))});`,+ ` const { createShutdownCoordinator } = require(${JSON.stringify(path.resolve('src/main/util/shutdown.ts'))});`,+ ' const shutdown = createShutdownCoordinator({ captureProcesses: () => processSnapshot || captureWindowsShutdownProcesses(), localTasks: [{ name: "connectors", run: close }], sync: async () => {}, onFailure: name => { throw new Error(name); } });',+ ' await shutdown.prepare();',+ ] : [' await close();']),+ ` const pid = Number(require('node:fs').readFileSync(${JSON.stringify(pidPath)}, 'utf8'));`,+ ' let alive = false; try { process.kill(pid, 0); alive = true; } catch {}',+ // The outer test represents another host. In shared-runtime mode it+ // executes the exact locked binary and must survive app cleanup.+ ` let unrelatedAlive = false; try { process.kill(${unrelated.pid}, 0); unrelatedAlive = true; } catch {}`,+ ' let replaced = false;',+ ` try { require('node:fs').renameSync(${JSON.stringify(replacementPath)}, ${JSON.stringify(lockPath)}); replaced = true; } catch {}`,+ ' process.stdout.write(JSON.stringify({ wasLocked, alive, replaced, unrelatedAlive, connectFailed, sharedClose, warnings, processHelpers }));',+ ' } finally { await connection.close(); processSnapshot?.dispose(); }',+ '})().catch(error => { process.stderr.write(error.name); process.exitCode = 1; });',+ ].join('\n'));+ try {+ await vi.waitFor(() => expect(fs.existsSync(foreignReadyPath)).toBe(true), { timeout: 3000, interval: 20 });+ const result = spawnSync(process.execPath, ['-r', require.resolve('tsx/cjs'), probePath], {+ cwd: root, env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', ORKAS_WORKSPACE_ROOT: root },+ encoding: 'utf8', timeout: 15000, maxBuffer: 1024 * 1024,+ });+ expect(result.status, result.stderr || result.stdout).toBe(0);+ expect(result.stderr).toBe('');+ const { processHelpers, ...outcome } = JSON.parse(result.stdout);+ expect(outcome).toEqual({+ wasLocked: true, alive: false, replaced: mode !== 'shared-runtime', unrelatedAlive: true,+ connectFailed: mode === 'failed-initialize', sharedClose: true,+ warnings: mode === 'failed-initialize' ? ['connect failed'] : [],+ });+ expect(processHelpers, 'only a connection created after the app snapshot needs another snapshot')+ .toBeLessThanOrEqual(mode === 'app-late-connection' ? 2 : 1);+ if (mode === 'shared-runtime') {+ // Only the external host can release its remaining lock. Orkas must+ // neither kill that host nor report the shared binary as replaceable.+ unrelated.kill();+ await unrelatedClosed;+ fs.renameSync(replacementPath, lockPath);+ }+ expect(fs.readFileSync(lockPath, 'utf8')).toBe('new runtime');+ } finally {+ if (unrelated.exitCode === null && unrelated.signalCode === null) unrelated.kill();+ await unrelatedClosed;+ if (fs.existsSync(pidPath)) {+ const pid = Number(fs.readFileSync(pidPath, 'utf8'));+ try { process.kill(pid, 'SIGKILL'); } catch {}+ await new Promise(resolve => setTimeout(resolve, 500));+ }+ await fs.promises.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ }+ }, 20000);+it.each(['complete', 'cycle', 'failure', 'cancel', 'deadline'])('collects paged tools atomically through the real SDK: %s', mode => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-mcp-pages-'));const childPath = path.join(root, 'server.cjs');@@ -63,7 +246,14 @@ describe('MCP stdio diagnostic boundary', () => {expect(pages).toEqual([null, 'page-2', 'page-3']);} else {expect(outcome.failed).toBe(true); expect(outcome).not.toHaveProperty('tools');- expect(pages).toEqual([null, 'page-2']);+ if (mode === 'deadline') {+ // The 300ms operation budget covers two 180ms page delays. A busy+ // host can expire on the first page; it must never complete all three+ // or publish the partial catalog. Receipt of page two is not promised.+ expect(pages.length).toBeGreaterThanOrEqual(1);+ expect(pages.length).toBeLessThanOrEqual(2);+ expect(pages).toEqual([null, 'page-2'].slice(0, pages.length));+ } else expect(pages).toEqual([null, 'page-2']);if (mode === 'cycle') expect(outcome.message).toContain('repeated a pagination cursor');if (mode === 'failure') expect(outcome.message).toContain('fixture page failed');if (mode === 'deadline') expect(outcome.message).toMatch(/timed out/i);diff --git a/test/main/features/connectors/mcp-remote_e2e_compat.test.ts b/test/main/features/connectors/mcp-remote_e2e_compat.test.tsindex 134b68cc..31ea1e4c 100644--- a/test/main/features/connectors/mcp-remote_e2e_compat.test.ts+++ b/test/main/features/connectors/mcp-remote_e2e_compat.test.ts@@ -10,7 +10,7 @@ const require = createRequire(import.meta.url);/** A real loopback MCP peer verifies protocol fallback, credential propagation,* and the absence of a second connection on auth/server failures. */-function probe(mode: 'modern' | 'legacy' | 'unauthorized' | 'broken' | 'catalog', status = 405) {+function probe(mode: 'modern' | 'legacy' | 'unauthorized' | 'broken' | 'catalog' | 'redirect-same' | 'redirect-other', status = 405) {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-mcp-remote-'));const probePath = path.join(root, 'probe.cjs');fs.writeFileSync(probePath, [@@ -21,10 +21,12 @@ function probe(mode: 'modern' | 'legacy' | 'unauthorized' | 'broken' | 'catalog'`const { ListToolsRequestSchema } = require(${JSON.stringify(require.resolve('@modelcontextprotocol/sdk/types.js'))});`,"const http = require('node:http');",`const mode = ${JSON.stringify(mode)}; const status = ${status};`,- 'const requests = []; let peer;',+ 'const requests = []; const sinkRequests = []; let peer;',+ "const sink = http.createServer(async (req, res) => { const chunks = []; for await (const chunk of req) chunks.push(chunk); sinkRequests.push({ key: req.headers['x-api-key'], body: Buffer.concat(chunks).toString('utf8') }); res.writeHead(500); res.end(); });","const server = http.createServer(async (req, res) => {",- " requests.push({ method: req.method, path: req.url, authorization: req.headers.authorization || null, accept: req.headers.accept || null });",- " if (mode === 'modern') {",+ " requests.push({ method: req.method, path: req.url, authorization: req.headers.authorization || null, key: req.headers['x-api-key'] || null, accept: req.headers.accept || null });",+ " if (mode.startsWith('redirect-') && req.url === '/sse') { res.writeHead(307, { location: mode === 'redirect-same' ? '/mcp' : 'http://127.0.0.1:' + sink.address().port + '/mcp' }); res.end(); return; }",+ " if (mode === 'modern' || mode === 'redirect-same') {"," if (req.method === 'GET') { res.writeHead(405); res.end(); return; }"," const chunks = []; for await (const chunk of req) chunks.push(chunk);"," const message = JSON.parse(Buffer.concat(chunks).toString('utf8'));",@@ -46,14 +48,15 @@ function probe(mode: 'modern' | 'legacy' | 'unauthorized' | 'broken' | 'catalog'' res.writeHead(404); res.end();','});','(async () => {',+ " await new Promise(resolve => sink.listen(0, '127.0.0.1', resolve));"," await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));",- " const conn = new McpConnection(mode === 'catalog' ? 'catalog-fixture' : 'custom-fixture', { kind: 'streamable-http', url: 'http://127.0.0.1:' + server.address().port + '/sse', headers: { Authorization: 'Bearer fixture-token' } });",+ " const conn = new McpConnection(mode === 'catalog' ? 'catalog-fixture' : 'custom-fixture', { kind: 'streamable-http', url: 'http://127.0.0.1:' + server.address().port + '/sse', headers: { Authorization: 'Bearer fixture-token', 'X-Api-Key': 'synthetic-fixture-key' } });",' let tools, error;',' try { await conn.connect(); tools = await conn.listTools();'," if (mode === 'modern') await new Promise(resolve => { let waited = 0; const check = () => { if (requests.some(r => r.method === 'GET') || waited >= 500) resolve(); else { waited += 10; setTimeout(check, 10); } }; check(); });",' } catch (e) { error = { code: e.code, name: e.name, message: e.message }; }',- ' finally { await conn.close(); if (peer) await peer.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }',- ' process.stdout.write(JSON.stringify({ tools, error, requests }));',+ ' finally { await conn.close(); if (peer) await peer.close(); server.closeAllConnections(); sink.closeAllConnections(); await Promise.all([new Promise(resolve => server.close(resolve)), new Promise(resolve => sink.close(resolve))]); }',+ ' process.stdout.write(JSON.stringify({ tools, error, requests, sinkRequests }));','})().catch(error => { process.stderr.write(error.stack || String(error)); process.exitCode = 1; });',].join('\n'));try {@@ -67,7 +70,8 @@ function probe(mode: 'modern' | 'legacy' | 'unauthorized' | 'broken' | 'catalog'return JSON.parse(result.stdout) as {tools?: { name: string }[];error?: { code?: number; name: string };- requests: { method: string; path: string; authorization: string | null; accept: string | null }[];+ requests: { method: string; path: string; authorization: string | null; key: string | null; accept: string | null }[];+ sinkRequests: { key?: string; body: string }[];};} finally {fs.rmSync(root, { recursive: true, force: true });@@ -75,6 +79,23 @@ function probe(mode: 'modern' | 'legacy' | 'unauthorized' | 'broken' | 'catalog'}describe('custom MCP remote transport compatibility', () => {+ it('preserves initialization, tool discovery and credentials across a same-origin redirect', () => {+ const outcome = probe('redirect-same');+ expect(outcome.error, JSON.stringify(outcome)).toBeUndefined();+ expect(outcome.tools?.map(tool => tool.name)).toEqual(['read_fixture']);+ expect(outcome.requests.some(req => req.method === 'POST' && req.path === '/mcp')).toBe(true);+ expect(outcome.requests.every(req => req.authorization === 'Bearer fixture-token' && req.key === 'synthetic-fixture-key')).toBe(true);+ expect(outcome.sinkRequests).toEqual([]);+ });++ it('rejects a different-port redirect before sending custom credentials or the initialization body', () => {+ const outcome = probe('redirect-other');+ expect(outcome.error).toBeDefined();+ expect(outcome.tools).toBeUndefined();+ expect(outcome.requests.map(req => `${req.method} ${req.path}`)).toEqual(['POST /sse']);+ expect(outcome.sinkRequests).toEqual([]);+ });+it('sends both required Accept types and tolerates a 405 on the optional HTTP GET stream', () => {const outcome = probe('modern');expect(outcome.error, JSON.stringify(outcome)).toBeUndefined();diff --git a/test/main/features/connectors/oauth-dcr.test.ts b/test/main/features/connectors/oauth-dcr.test.tsindex 01d08e4c..759acf50 100644--- a/test/main/features/connectors/oauth-dcr.test.ts+++ b/test/main/features/connectors/oauth-dcr.test.ts@@ -129,6 +129,30 @@ afterEach(() => {});describe('features/connectors/oauth-dcr', () => {+ it.each(['catalog', 'custom'] as const)('preserves the browser launch failure cause for %s OAuth without exchanging or storing a grant', async kind => {+ const fetchMock = vi.fn(async (raw: string) => {+ if (raw.includes('oauth-protected-resource')) return jsonResponse({+ authorization_servers: ['https://auth.notion.example'], resource: 'https://mcp.notion.example/mcp',+ });+ if (raw.includes('oauth-authorization-server')) return jsonResponse({+ issuer: 'https://auth.notion.example', authorization_endpoint: 'https://auth.notion.example/authorize',+ token_endpoint: 'https://auth.notion.example/token', registration_endpoint: 'https://auth.notion.example/register',+ });+ if (raw.endsWith('/register')) return jsonResponse({ client_id: 'fixture-client' });+ throw new Error('Token exchange or grant storage must not follow a browser launch failure');+ });+ vi.stubGlobal('fetch', fetchMock);+ electronMock.openExternal.mockRejectedValueOnce(new Error('PRIVATE_BROWSER_FAILURE'));+ const oauth = await import('../../../../src/main/features/connectors/oauth-dcr');+ const flow = kind === 'catalog' ? oauth.startMcpDcrOAuth('uid-1', notionEntry())+ : oauth.startCustomMcpOAuth('fixture-custom', 'https://mcp.notion.example/mcp');+ await expect(flow).rejects.toMatchObject({ code: 'browser_open_failed' });+ expect(electronMock.openExternal).toHaveBeenCalledOnce();+ expect(fetchMock.mock.calls.filter(([url]) => url.endsWith('/register'))).toHaveLength(1);+ expect(fetchMock.mock.calls.some(([url]) => /\/(?:token|dcr-store|dcr-exchange)$/.test(url))).toBe(false);+ expect(oauth.cancelDcrOAuth()).toBe(false);+ });+it('continues discovery after a candidate sends headers but stalls its metadata body', async () => {vi.useFakeTimers();let release!: () => void;diff --git a/test/main/features/connectors/tool-discovery.test.ts b/test/main/features/connectors/tool-discovery.test.tsindex bfe8c32d..6a778b47 100644--- a/test/main/features/connectors/tool-discovery.test.ts+++ b/test/main/features/connectors/tool-discovery.test.ts@@ -175,21 +175,25 @@ describe('bounded connector discovery', () => {});it.each([- [{ query: '' }, 'query must be a non-empty string'],- [{ query: ' ' }, 'query must be a non-empty string'],- [{ query: 3 }, 'query must be a non-empty string'],- [{ query: 'x'.repeat(1025) }, 'query must be at most 1024 characters'],- [{ limit: '20' }, 'limit must be an integer from 1 to 50'],- [{ limit: 1.5 }, 'limit must be an integer from 1 to 50'],- [{ offset: -1 }, 'offset must be an integer from 0 to 9007199254740991'],- [{ offset: Infinity }, 'offset must be an integer from 0 to 9007199254740991'],- [{ offset: '1' }, 'offset must be an integer from 0 to 9007199254740991'],- [{ offset: Number.MAX_SAFE_INTEGER + 1 }, 'offset must be an integer from 0 to 9007199254740991'],- [{ tool_name: 'read' }, '`connector_id` is required'],- [{ connector_id: 'x', tool_name: 'read', query: 'read' }, 'tool_name cannot be combined'],- [{ unknown: 'private value' }, 'unsupported discovery field "unknown"; allowed fields: connector_id, tool_name, query, limit, offset'],- ] as const)('rejects malformed parameters with field constraints: %j', (raw, message) => {- expect(() => validateDiscoveryParams(raw)).toThrow(message);+ [{ connector_id: 4 }, 'connector_id must be a non-empty string', 'invalid_connector_id'],+ [{ tool_name: false }, 'tool_name must be a non-empty string', 'invalid_tool_name'],+ [{ query: '' }, 'query must be a non-empty string', 'invalid_query'],+ [{ query: ' ' }, 'query must be a non-empty string', 'invalid_query'],+ [{ query: 3 }, 'query must be a non-empty string', 'invalid_query'],+ [{ query: 'x'.repeat(1025) }, 'query must be at most 1024 characters', 'query_too_long'],+ [{ limit: '20' }, 'limit must be an integer from 1 to 50', 'invalid_limit'],+ [{ limit: 1.5 }, 'limit must be an integer from 1 to 50', 'invalid_limit'],+ [{ offset: -1 }, 'offset must be an integer from 0 to 9007199254740991', 'invalid_offset'],+ [{ offset: Infinity }, 'offset must be an integer from 0 to 9007199254740991', 'invalid_offset'],+ [{ offset: '1' }, 'offset must be an integer from 0 to 9007199254740991', 'invalid_offset'],+ [{ offset: Number.MAX_SAFE_INTEGER + 1 }, 'offset must be an integer from 0 to 9007199254740991', 'invalid_offset'],+ [{ tool_name: 'read' }, '`connector_id` is required', 'connector_id_required'],+ [{ connector_id: 'x', tool_name: 'read', query: 'read' }, 'tool_name cannot be combined', 'conflicting_fields'],+ [{ unknown: 'private value' }, 'unsupported discovery field "unknown"; allowed fields: connector_id, tool_name, query, limit, offset', 'unknown_field'],+ ] as const)('rejects malformed parameters with field constraints: %j', (raw, message, reason) => {+ expect(() => validateDiscoveryParams(raw)).toThrowError(expect.objectContaining({+ code: 'E_BAD_INPUT', message: expect.stringContaining(message), reason,+ }));});it('bounds and escapes unsupported field names without echoing values', () => {diff --git a/test/main/model/core-agent/connector-meta-tools.test.ts b/test/main/model/core-agent/connector-meta-tools.test.tsindex 32af28a1..97ff5eac 100644--- a/test/main/model/core-agent/connector-meta-tools.test.ts+++ b/test/main/model/core-agent/connector-meta-tools.test.ts@@ -27,7 +27,7 @@ const fixtures: {id: string,name: string,args: Record<string, unknown>,- opts?: { signal?: AbortSignal },+ opts?: { signal?: AbortSignal; conversationId?: string },) => Promise<unknown>;} = {instances: [],@@ -50,7 +50,7 @@ vi.mock('../../../../src/main/features/connectors/manager', () => ({},refreshStaleToolCaches: async () => 0,addCustomInstance: (uid: string, input: unknown) => fixtures.addCustomInstance(uid, input),- callTool: (uid: string, id: string, name: string, args: Record<string, unknown>, opts?: { signal?: AbortSignal }) =>+ callTool: (uid: string, id: string, name: string, args: Record<string, unknown>, opts?: { signal?: AbortSignal; conversationId?: string }) =>fixtures.callTool(uid, id, name, args, opts),}));@@ -1409,11 +1409,13 @@ describe('call_connector_tool', () => {expect(result.isError).toBe(true);});- it('passes the task AbortSignal to manager and classifies cancellation separately', async () => {+ it('passes host conversation context and the task AbortSignal to manager and classifies cancellation separately', async () => {fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];let receivedSignal: AbortSignal | undefined;+ let receivedConversation: string | undefined;fixtures.callTool = async (_uid, _id, _name, _args, opts) => {receivedSignal = opts?.signal;+ receivedConversation = opts?.conversationId;throw Object.assign(new Error('connector tool call cancelled'), {name: 'AbortError',code: 'E_TOOL_CALL_CANCELLED',@@ -1421,13 +1423,14 @@ describe('call_connector_tool', () => {};const controller = new AbortController();const { createConnectorMetaTools } = await loadModule();- const [, call] = await createConnectorMetaTools({ userId: UID });+ const [, call] = await createConnectorMetaTools({ userId: UID, cid: 'download-conversation' });const result = await runTool(call, {connector_id: 'notion', tool_name: 'search', args: { query: 'x' },}, controller.signal);expect(receivedSignal).toBe(controller.signal);+ expect(receivedConversation).toBe('download-conversation');expect(result.isError).toBe(true);});